diff --git a/node_modules/bake/bake.js b/node_modules/bake/bake.js index d2db806..0139a51 100644 --- a/node_modules/bake/bake.js +++ b/node_modules/bake/bake.js @@ -127,8 +127,10 @@ var bake = function(conf, hooks, cb) { '.' + fileExt[masterExt]); // New file's path - if (typeof prop._id == 'undefined') + if (typeof prop._id == 'undefined') { prop._id = resName.replace(inputDir, ''); + prop._id = prop._id.replace(/\\/g, '/'); + } // Remove first slash if (/^\//, prop._id) @@ -157,7 +159,7 @@ var bake = function(conf, hooks, cb) { return cb(err); // Log status on success - console.log(' ' + resName + ' written.'); + console.log(' * ' + resName + ' written.'); // When file counter is zero if (!--todo) { diff --git a/node_modules/bake/node_modules/async/.gitmodules b/node_modules/bake/node_modules/async/.gitmodules deleted file mode 100644 index a9aae98..0000000 --- a/node_modules/bake/node_modules/async/.gitmodules +++ /dev/null @@ -1,9 +0,0 @@ -[submodule "deps/nodeunit"] - path = deps/nodeunit - url = git://github.com/caolan/nodeunit.git -[submodule "deps/UglifyJS"] - path = deps/UglifyJS - url = https://github.com/mishoo/UglifyJS.git -[submodule "deps/nodelint"] - path = deps/nodelint - url = https://github.com/tav/nodelint.git diff --git a/node_modules/bake/node_modules/async/LICENSE b/node_modules/bake/node_modules/async/LICENSE deleted file mode 100644 index b7f9d50..0000000 --- a/node_modules/bake/node_modules/async/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Caolan McMahon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/bake/node_modules/async/Makefile b/node_modules/bake/node_modules/async/Makefile deleted file mode 100644 index 00f07ea..0000000 --- a/node_modules/bake/node_modules/async/Makefile +++ /dev/null @@ -1,21 +0,0 @@ -PACKAGE = asyncjs -NODEJS = $(if $(shell test -f /usr/bin/nodejs && echo "true"),nodejs,node) - -BUILDDIR = dist - -all: build - -build: $(wildcard lib/*.js) - mkdir -p $(BUILDDIR) - uglifyjs lib/async.js > $(BUILDDIR)/async.min.js - -test: - nodeunit test - -clean: - rm -rf $(BUILDDIR) - -lint: - nodelint --config nodelint.cfg lib/async.js - -.PHONY: test build all diff --git a/node_modules/bake/node_modules/async/README.md b/node_modules/bake/node_modules/async/README.md deleted file mode 100644 index 0cf7fc9..0000000 --- a/node_modules/bake/node_modules/async/README.md +++ /dev/null @@ -1,1022 +0,0 @@ -# Async.js - -Async is a utility module which provides straight-forward, powerful functions -for working with asynchronous JavaScript. Although originally designed for -use with [node.js](http://nodejs.org), it can also be used directly in the -browser. - -Async provides around 20 functions that include the usual 'functional' -suspects (map, reduce, filter, forEach…) as well as some common patterns -for asynchronous control flow (parallel, series, waterfall…). All these -functions assume you follow the node.js convention of providing a single -callback as the last argument of your async function. - - -## Quick Examples - - async.map(['file1','file2','file3'], fs.stat, function(err, results){ - // results is now an array of stats for each file - }); - - async.filter(['file1','file2','file3'], path.exists, function(results){ - // results now equals an array of the existing files - }); - - async.parallel([ - function(){ ... }, - function(){ ... } - ], callback); - - async.series([ - function(){ ... }, - function(){ ... } - ]); - -There are many more functions available so take a look at the docs below for a -full list. This module aims to be comprehensive, so if you feel anything is -missing please create a GitHub issue for it. - - -## Download - -Releases are available for download from -[GitHub](http://github.com/caolan/async/downloads). -Alternatively, you can install using Node Package Manager (npm): - - npm install async - - -__Development:__ [async.js](https://github.com/caolan/async/raw/master/lib/async.js) - 17.5kb Uncompressed - -__Production:__ [async.min.js](https://github.com/caolan/async/raw/master/dist/async.min.js) - 1.7kb Packed and Gzipped - - -## In the Browser - -So far its been tested in IE6, IE7, IE8, FF3.6 and Chrome 5. Usage: - - - - - -## Documentation - -### Collections - -* [forEach](#forEach) -* [map](#map) -* [filter](#filter) -* [reject](#reject) -* [reduce](#reduce) -* [detect](#detect) -* [sortBy](#sortBy) -* [some](#some) -* [every](#every) -* [concat](#concat) - -### Control Flow - -* [series](#series) -* [parallel](#parallel) -* [whilst](#whilst) -* [until](#until) -* [waterfall](#waterfall) -* [queue](#queue) -* [auto](#auto) -* [iterator](#iterator) -* [apply](#apply) -* [nextTick](#nextTick) - -### Utils - -* [memoize](#memoize) -* [unmemoize](#unmemoize) -* [log](#log) -* [dir](#dir) -* [noConflict](#noConflict) - - -## Collections - - -### forEach(arr, iterator, callback) - -Applies an iterator function to each item in an array, in parallel. -The iterator is called with an item from the list and a callback for when it -has finished. If the iterator passes an error to this callback, the main -callback for the forEach function is immediately called with the error. - -Note, that since this function applies the iterator to each item in parallel -there is no guarantee that the iterator functions will complete in order. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(err) - A callback which is called after all the iterator functions - have finished, or an error has occurred. - -__Example__ - - // assuming openFiles is an array of file names and saveFile is a function - // to save the modified contents of that file: - - async.forEach(openFiles, saveFile, function(err){ - // if any of the saves produced an error, err would equal that error - }); - ---------------------------------------- - - -### forEachSeries(arr, iterator, callback) - -The same as forEach only the iterator is applied to each item in the array in -series. The next iterator is only called once the current one has completed -processing. This means the iterator functions will complete in order. - - ---------------------------------------- - - -### forEachLimit(arr, limit, iterator, callback) - -The same as forEach only the iterator is applied to batches of items in the -array, in series. The next batch of iterators is only called once the current -one has completed processing. - -__Arguments__ - -* arr - An array to iterate over. -* limit - How many items should be in each batch. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(err) - A callback which is called after all the iterator functions - have finished, or an error has occurred. - -__Example__ - - // Assume documents is an array of JSON objects and requestApi is a - // function that interacts with a rate-limited REST api. - - async.forEachLimit(documents, 20, requestApi, function(err){ - // if any of the saves produced an error, err would equal that error - }); ---------------------------------------- - - -### map(arr, iterator, callback) - -Produces a new array of values by mapping each value in the given array through -the iterator function. The iterator is called with an item from the array and a -callback for when it has finished processing. The callback takes 2 arguments, -an error and the transformed item from the array. If the iterator passes an -error to this callback, the main callback for the map function is immediately -called with the error. - -Note, that since this function applies the iterator to each item in parallel -there is no guarantee that the iterator functions will complete in order, however -the results array will be in the same order as the original array. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed - with an error (which can be null) and a transformed item. -* callback(err, results) - A callback which is called after all the iterator - functions have finished, or an error has occurred. Results is an array of the - transformed items from the original array. - -__Example__ - - async.map(['file1','file2','file3'], fs.stat, function(err, results){ - // results is now an array of stats for each file - }); - ---------------------------------------- - - -### mapSeries(arr, iterator, callback) - -The same as map only the iterator is applied to each item in the array in -series. The next iterator is only called once the current one has completed -processing. The results array will be in the same order as the original. - - ---------------------------------------- - - -### filter(arr, iterator, callback) - -__Alias:__ select - -Returns a new array of all the values which pass an async truth test. -_The callback for each iterator call only accepts a single argument of true or -false, it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like path.exists. This operation is -performed in parallel, but the results array will be in the same order as the -original. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(results) - A callback which is called after all the iterator - functions have finished. - -__Example__ - - async.filter(['file1','file2','file3'], path.exists, function(results){ - // results now equals an array of the existing files - }); - ---------------------------------------- - - -### filterSeries(arr, iterator, callback) - -__alias:__ selectSeries - -The same as filter only the iterator is applied to each item in the array in -series. The next iterator is only called once the current one has completed -processing. The results array will be in the same order as the original. - ---------------------------------------- - - -### reject(arr, iterator, callback) - -The opposite of filter. Removes values that pass an async truth test. - ---------------------------------------- - - -### rejectSeries(arr, iterator, callback) - -The same as filter, only the iterator is applied to each item in the array -in series. - - ---------------------------------------- - - -### reduce(arr, memo, iterator, callback) - -__aliases:__ inject, foldl - -Reduces a list of values into a single value using an async iterator to return -each successive step. Memo is the initial state of the reduction. This -function only operates in series. For performance reasons, it may make sense to -split a call to this function into a parallel map, then use the normal -Array.prototype.reduce on the results. This function is for situations where -each step in the reduction needs to be async, if you can get the data before -reducing it then its probably a good idea to do so. - -__Arguments__ - -* arr - An array to iterate over. -* memo - The initial state of the reduction. -* iterator(memo, item, callback) - A function applied to each item in the - array to produce the next step in the reduction. The iterator is passed a - callback which accepts an optional error as its first argument, and the state - of the reduction as the second. If an error is passed to the callback, the - reduction is stopped and the main callback is immediately called with the - error. -* callback(err, result) - A callback which is called after all the iterator - functions have finished. Result is the reduced value. - -__Example__ - - async.reduce([1,2,3], 0, function(memo, item, callback){ - // pointless async: - process.nextTick(function(){ - callback(null, memo + item) - }); - }, function(err, result){ - // result is now equal to the last value of memo, which is 6 - }); - ---------------------------------------- - - -### reduceRight(arr, memo, iterator, callback) - -__Alias:__ foldr - -Same as reduce, only operates on the items in the array in reverse order. - - ---------------------------------------- - - -### detect(arr, iterator, callback) - -Returns the first value in a list that passes an async truth test. The -iterator is applied in parallel, meaning the first iterator to return true will -fire the detect callback with that result. That means the result might not be -the first item in the original array (in terms of order) that passes the test. - -If order within the original array is important then look at detectSeries. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(result) - A callback which is called as soon as any iterator returns - true, or after all the iterator functions have finished. Result will be - the first item in the array that passes the truth test (iterator) or the - value undefined if none passed. - -__Example__ - - async.detect(['file1','file2','file3'], path.exists, function(result){ - // result now equals the first file in the list that exists - }); - ---------------------------------------- - - -### detectSeries(arr, iterator, callback) - -The same as detect, only the iterator is applied to each item in the array -in series. This means the result is always the first in the original array (in -terms of array order) that passes the truth test. - - ---------------------------------------- - - -### sortBy(arr, iterator, callback) - -Sorts a list by the results of running each value through an async iterator. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed - with an error (which can be null) and a value to use as the sort criteria. -* callback(err, results) - A callback which is called after all the iterator - functions have finished, or an error has occurred. Results is the items from - the original array sorted by the values returned by the iterator calls. - -__Example__ - - async.sortBy(['file1','file2','file3'], function(file, callback){ - fs.stat(file, function(err, stats){ - callback(err, stats.mtime); - }); - }, function(err, results){ - // results is now the original array of files sorted by - // modified date - }); - - ---------------------------------------- - - -### some(arr, iterator, callback) - -__Alias:__ any - -Returns true if at least one element in the array satisfies an async test. -_The callback for each iterator call only accepts a single argument of true or -false, it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like path.exists. Once any iterator -call returns true, the main callback is immediately called. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(result) - A callback which is called as soon as any iterator returns - true, or after all the iterator functions have finished. Result will be - either true or false depending on the values of the async tests. - -__Example__ - - async.some(['file1','file2','file3'], path.exists, function(result){ - // if result is true then at least one of the files exists - }); - ---------------------------------------- - - -### every(arr, iterator, callback) - -__Alias:__ all - -Returns true if every element in the array satisfies an async test. -_The callback for each iterator call only accepts a single argument of true or -false, it does not accept an error argument first!_ This is in-line with the -way node libraries work with truth tests like path.exists. - -__Arguments__ - -* arr - An array to iterate over. -* iterator(item, callback) - A truth test to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed. -* callback(result) - A callback which is called after all the iterator - functions have finished. Result will be either true or false depending on - the values of the async tests. - -__Example__ - - async.every(['file1','file2','file3'], path.exists, function(result){ - // if result is true then every file exists - }); - ---------------------------------------- - - -### concat(arr, iterator, callback) - -Applies an iterator to each item in a list, concatenating the results. Returns the -concatenated list. The iterators are called in parallel, and the results are -concatenated as they return. There is no guarantee that the results array will -be returned in the original order of the arguments passed to the iterator function. - -__Arguments__ - -* arr - An array to iterate over -* iterator(item, callback) - A function to apply to each item in the array. - The iterator is passed a callback which must be called once it has completed - with an error (which can be null) and an array of results. -* callback(err, results) - A callback which is called after all the iterator - functions have finished, or an error has occurred. Results is an array containing - the concatenated results of the iterator function. - -__Example__ - - async.concat(['dir1','dir2','dir3'], fs.readdir, function(err, files){ - // files is now a list of filenames that exist in the 3 directories - }); - ---------------------------------------- - - -### concatSeries(arr, iterator, callback) - -Same as async.concat, but executes in series instead of parallel. - - -## Control Flow - - -### series(tasks, [callback]) - -Run an array of functions in series, each one running once the previous -function has completed. If any functions in the series pass an error to its -callback, no more functions are run and the callback for the series is -immediately called with the value of the error. Once the tasks have completed, -the results are passed to the final callback as an array. - -It is also possible to use an object instead of an array. Each property will be -run as a function and the results will be passed to the final callback as an object -instead of an array. This can be a more readable way of handling results from -async.series. - - -__Arguments__ - -* tasks - An array or object containing functions to run, each function is passed - a callback it must call on completion. -* callback(err, results) - An optional callback to run once all the functions - have completed. This function gets an array of all the arguments passed to - the callbacks used in the array. - -__Example__ - - async.series([ - function(callback){ - // do some stuff ... - callback(null, 'one'); - }, - function(callback){ - // do some more stuff ... - callback(null, 'two'); - }, - ], - // optional callback - function(err, results){ - // results is now equal to ['one', 'two'] - }); - - - // an example using an object instead of an array - async.series({ - one: function(callback){ - setTimeout(function(){ - callback(null, 1); - }, 200); - }, - two: function(callback){ - setTimeout(function(){ - callback(null, 2); - }, 100); - }, - }, - function(err, results) { - // results is now equal to: {one: 1, two: 2} - }); - - ---------------------------------------- - - -### parallel(tasks, [callback]) - -Run an array of functions in parallel, without waiting until the previous -function has completed. If any of the functions pass an error to its -callback, the main callback is immediately called with the value of the error. -Once the tasks have completed, the results are passed to the final callback as an -array. - -It is also possible to use an object instead of an array. Each property will be -run as a function and the results will be passed to the final callback as an object -instead of an array. This can be a more readable way of handling results from -async.parallel. - - -__Arguments__ - -* tasks - An array or object containing functions to run, each function is passed a - callback it must call on completion. -* callback(err, results) - An optional callback to run once all the functions - have completed. This function gets an array of all the arguments passed to - the callbacks used in the array. - -__Example__ - - async.parallel([ - function(callback){ - setTimeout(function(){ - callback(null, 'one'); - }, 200); - }, - function(callback){ - setTimeout(function(){ - callback(null, 'two'); - }, 100); - }, - ], - // optional callback - function(err, results){ - // in this case, the results array will equal ['two','one'] - // because the functions were run in parallel and the second - // function had a shorter timeout before calling the callback. - }); - - - // an example using an object instead of an array - async.parallel({ - one: function(callback){ - setTimeout(function(){ - callback(null, 1); - }, 200); - }, - two: function(callback){ - setTimeout(function(){ - callback(null, 2); - }, 100); - }, - }, - function(err, results) { - // results is now equals to: {one: 1, two: 2} - }); - - ---------------------------------------- - - -### whilst(test, fn, callback) - -Repeatedly call fn, while test returns true. Calls the callback when stopped, -or an error occurs. - -__Arguments__ - -* test() - synchronous truth test to perform before each execution of fn. -* fn(callback) - A function to call each time the test passes. The function is - passed a callback which must be called once it has completed with an optional - error as the first argument. -* callback(err) - A callback which is called after the test fails and repeated - execution of fn has stopped. - -__Example__ - - var count = 0; - - async.whilst( - function () { return count < 5; }, - function (callback) { - count++; - setTimeout(callback, 1000); - }, - function (err) { - // 5 seconds have passed - } - ); - - ---------------------------------------- - - -### until(test, fn, callback) - -Repeatedly call fn, until test returns true. Calls the callback when stopped, -or an error occurs. - -The inverse of async.whilst. - - ---------------------------------------- - - -### waterfall(tasks, [callback]) - -Runs an array of functions in series, each passing their results to the next in -the array. However, if any of the functions pass an error to the callback, the -next function is not executed and the main callback is immediately called with -the error. - -__Arguments__ - -* tasks - An array of functions to run, each function is passed a callback it - must call on completion. -* callback(err, [results]) - An optional callback to run once all the functions - have completed. This will be passed the results of the last task's callback. - - - -__Example__ - - async.waterfall([ - function(callback){ - callback(null, 'one', 'two'); - }, - function(arg1, arg2, callback){ - callback(null, 'three'); - }, - function(arg1, callback){ - // arg1 now equals 'three' - callback(null, 'done'); - } - ], function (err, result) { - // result now equals 'done' - }); - - ---------------------------------------- - - -### queue(worker, concurrency) - -Creates a queue object with the specified concurrency. Tasks added to the -queue will be processed in parallel (up to the concurrency limit). If all -workers are in progress, the task is queued until one is available. Once -a worker has completed a task, the task's callback is called. - -__Arguments__ - -* worker(task, callback) - An asynchronous function for processing a queued - task. -* concurrency - An integer for determining how many worker functions should be - run in parallel. - -__Queue objects__ - -The queue object returned by this function has the following properties and -methods: - -* length() - a function returning the number of items waiting to be processed. -* concurrency - an integer for determining how many worker functions should be - run in parallel. This property can be changed after a queue is created to - alter the concurrency on-the-fly. -* push(task, [callback]) - add a new task to the queue, the callback is called - once the worker has finished processing the task. - instead of a single task, an array of tasks can be submitted. the respective callback is used for every task in the list. -* saturated - a callback that is called when the queue length hits the concurrency and further tasks will be queued -* empty - a callback that is called when the last item from the queue is given to a worker -* drain - a callback that is called when the last item from the queue has returned from the worker - -__Example__ - - // create a queue object with concurrency 2 - - var q = async.queue(function (task, callback) { - console.log('hello ' + task.name); - callback(); - }, 2); - - - // assign a callback - q.drain = function() { - console.log('all items have been processed'); - } - - // add some items to the queue - - q.push({name: 'foo'}, function (err) { - console.log('finished processing foo'); - }); - q.push({name: 'bar'}, function (err) { - console.log('finished processing bar'); - }); - - // add some items to the queue (batch-wise) - - q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function (err) { - console.log('finished processing bar'); - }); - - ---------------------------------------- - - -### auto(tasks, [callback]) - -Determines the best order for running functions based on their requirements. -Each function can optionally depend on other functions being completed first, -and each function is run as soon as its requirements are satisfied. If any of -the functions pass an error to their callback, that function will not complete -(so any other functions depending on it will not run) and the main callback -will be called immediately with the error. Functions also receive an object -containing the results of functions which have completed so far. - -__Arguments__ - -* tasks - An object literal containing named functions or an array of - requirements, with the function itself the last item in the array. The key - used for each function or array is used when specifying requirements. The - syntax is easier to understand by looking at the example. -* callback(err, results) - An optional callback which is called when all the - tasks have been completed. The callback will receive an error as an argument - if any tasks pass an error to their callback. If all tasks complete - successfully, it will receive an object containing their results. - -__Example__ - - async.auto({ - get_data: function(callback){ - // async code to get some data - }, - make_folder: function(callback){ - // async code to create a directory to store a file in - // this is run at the same time as getting the data - }, - write_file: ['get_data', 'make_folder', function(callback){ - // once there is some data and the directory exists, - // write the data to a file in the directory - callback(null, filename); - }], - email_link: ['write_file', function(callback, results){ - // once the file is written let's email a link to it... - // results.write_file contains the filename returned by write_file. - }] - }); - -This is a fairly trivial example, but to do this using the basic parallel and -series functions would look like this: - - async.parallel([ - function(callback){ - // async code to get some data - }, - function(callback){ - // async code to create a directory to store a file in - // this is run at the same time as getting the data - } - ], - function(results){ - async.series([ - function(callback){ - // once there is some data and the directory exists, - // write the data to a file in the directory - }, - email_link: function(callback){ - // once the file is written let's email a link to it... - } - ]); - }); - -For a complicated series of async tasks using the auto function makes adding -new tasks much easier and makes the code more readable. - - ---------------------------------------- - - -### iterator(tasks) - -Creates an iterator function which calls the next function in the array, -returning a continuation to call the next one after that. Its also possible to -'peek' the next iterator by doing iterator.next(). - -This function is used internally by the async module but can be useful when -you want to manually control the flow of functions in series. - -__Arguments__ - -* tasks - An array of functions to run, each function is passed a callback it - must call on completion. - -__Example__ - - var iterator = async.iterator([ - function(){ sys.p('one'); }, - function(){ sys.p('two'); }, - function(){ sys.p('three'); } - ]); - - node> var iterator2 = iterator(); - 'one' - node> var iterator3 = iterator2(); - 'two' - node> iterator3(); - 'three' - node> var nextfn = iterator2.next(); - node> nextfn(); - 'three' - - ---------------------------------------- - - -### apply(function, arguments..) - -Creates a continuation function with some arguments already applied, a useful -shorthand when combined with other control flow functions. Any arguments -passed to the returned function are added to the arguments originally passed -to apply. - -__Arguments__ - -* function - The function you want to eventually apply all arguments to. -* arguments... - Any number of arguments to automatically apply when the - continuation is called. - -__Example__ - - // using apply - - async.parallel([ - async.apply(fs.writeFile, 'testfile1', 'test1'), - async.apply(fs.writeFile, 'testfile2', 'test2'), - ]); - - - // the same process without using apply - - async.parallel([ - function(callback){ - fs.writeFile('testfile1', 'test1', callback); - }, - function(callback){ - fs.writeFile('testfile2', 'test2', callback); - }, - ]); - -It's possible to pass any number of additional arguments when calling the -continuation: - - node> var fn = async.apply(sys.puts, 'one'); - node> fn('two', 'three'); - one - two - three - ---------------------------------------- - - -### nextTick(callback) - -Calls the callback on a later loop around the event loop. In node.js this just -calls process.nextTick, in the browser it falls back to setTimeout(callback, 0), -which means other higher priority events may precede the execution of the callback. - -This is used internally for browser-compatibility purposes. - -__Arguments__ - -* callback - The function to call on a later loop around the event loop. - -__Example__ - - var call_order = []; - async.nextTick(function(){ - call_order.push('two'); - // call_order now equals ['one','two] - }); - call_order.push('one') - - -## Utils - - -### memoize(fn, [hasher]) - -Caches the results of an async function. When creating a hash to store function -results against, the callback is omitted from the hash and an optional hash -function can be used. - -__Arguments__ - -* fn - the function you to proxy and cache results from. -* hasher - an optional function for generating a custom hash for storing - results, it has all the arguments applied to it apart from the callback, and - must be synchronous. - -__Example__ - - var slow_fn = function (name, callback) { - // do something - callback(null, result); - }; - var fn = async.memoize(slow_fn); - - // fn can now be used as if it were slow_fn - fn('some name', function () { - // callback - }); - - -### unmemoize(fn) - -Undoes a memoized function, reverting it to the original, unmemoized -form. Comes handy in tests. - -__Arguments__ - -* fn - the memoized function - - -### log(function, arguments) - -Logs the result of an async function to the console. Only works in node.js or -in browsers that support console.log and console.error (such as FF and Chrome). -If multiple arguments are returned from the async function, console.log is -called on each argument in order. - -__Arguments__ - -* function - The function you want to eventually apply all arguments to. -* arguments... - Any number of arguments to apply to the function. - -__Example__ - - var hello = function(name, callback){ - setTimeout(function(){ - callback(null, 'hello ' + name); - }, 1000); - }; - - node> async.log(hello, 'world'); - 'hello world' - - ---------------------------------------- - - -### dir(function, arguments) - -Logs the result of an async function to the console using console.dir to -display the properties of the resulting object. Only works in node.js or -in browsers that support console.dir and console.error (such as FF and Chrome). -If multiple arguments are returned from the async function, console.dir is -called on each argument in order. - -__Arguments__ - -* function - The function you want to eventually apply all arguments to. -* arguments... - Any number of arguments to apply to the function. - -__Example__ - - var hello = function(name, callback){ - setTimeout(function(){ - callback(null, {hello: name}); - }, 1000); - }; - - node> async.dir(hello, 'world'); - {hello: 'world'} - - ---------------------------------------- - - -### noConflict() - -Changes the value of async back to its original value, returning a reference to the -async object. diff --git a/node_modules/bake/node_modules/async/deps/nodeunit.css b/node_modules/bake/node_modules/async/deps/nodeunit.css deleted file mode 100644 index 274434a..0000000 --- a/node_modules/bake/node_modules/async/deps/nodeunit.css +++ /dev/null @@ -1,70 +0,0 @@ -/*! - * Styles taken from qunit.css - */ - -h1#nodeunit-header, h1.nodeunit-header { - padding: 15px; - font-size: large; - background-color: #06b; - color: white; - font-family: 'trebuchet ms', verdana, arial; - margin: 0; -} - -h1#nodeunit-header a { - color: white; -} - -h2#nodeunit-banner { - height: 2em; - border-bottom: 1px solid white; - background-color: #eee; - margin: 0; - font-family: 'trebuchet ms', verdana, arial; -} -h2#nodeunit-banner.pass { - background-color: green; -} -h2#nodeunit-banner.fail { - background-color: red; -} - -h2#nodeunit-userAgent, h2.nodeunit-userAgent { - padding: 10px; - background-color: #eee; - color: black; - margin: 0; - font-size: small; - font-weight: normal; - font-family: 'trebuchet ms', verdana, arial; - font-size: 10pt; -} - -div#nodeunit-testrunner-toolbar { - background: #eee; - border-top: 1px solid black; - padding: 10px; - font-family: 'trebuchet ms', verdana, arial; - margin: 0; - font-size: 10pt; -} - -ol#nodeunit-tests { - font-family: 'trebuchet ms', verdana, arial; - font-size: 10pt; -} -ol#nodeunit-tests li strong { - cursor:pointer; -} -ol#nodeunit-tests .pass { - color: green; -} -ol#nodeunit-tests .fail { - color: red; -} - -p#nodeunit-testresult { - margin-left: 1em; - font-size: 10pt; - font-family: 'trebuchet ms', verdana, arial; -} diff --git a/node_modules/bake/node_modules/async/deps/nodeunit.js b/node_modules/bake/node_modules/async/deps/nodeunit.js deleted file mode 100644 index 5957184..0000000 --- a/node_modules/bake/node_modules/async/deps/nodeunit.js +++ /dev/null @@ -1,1966 +0,0 @@ -/*! - * Nodeunit - * https://github.com/caolan/nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * json2.js - * http://www.JSON.org/json2.js - * Public Domain. - * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - */ -nodeunit = (function(){ -/* - http://www.JSON.org/json2.js - 2010-11-17 - - 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, regexp: 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 () { - "use strict"; - - 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'); - }; - } -}()); -var assert = this.assert = {}; -var types = {}; -var core = {}; -var nodeunit = {}; -var reporter = {}; -/*global setTimeout: false, console: false */ -(function () { - - var async = {}; - - // global on the server, window in the browser - var root = this, - previous_async = root.async; - - if (typeof module !== 'undefined' && module.exports) { - module.exports = async; - } - else { - root.async = async; - } - - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - //// cross-browser compatiblity functions //// - - var _forEach = function (arr, iterator) { - if (arr.forEach) { - return arr.forEach(iterator); - } - for (var i = 0; i < arr.length; i += 1) { - iterator(arr[i], i, arr); - } - }; - - var _map = function (arr, iterator) { - if (arr.map) { - return arr.map(iterator); - } - var results = []; - _forEach(arr, function (x, i, a) { - results.push(iterator(x, i, a)); - }); - return results; - }; - - var _reduce = function (arr, iterator, memo) { - if (arr.reduce) { - return arr.reduce(iterator, memo); - } - _forEach(arr, function (x, i, a) { - memo = iterator(memo, x, i, a); - }); - return memo; - }; - - var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; - }; - - var _indexOf = function (arr, item) { - if (arr.indexOf) { - return arr.indexOf(item); - } - for (var i = 0; i < arr.length; i += 1) { - if (arr[i] === item) { - return i; - } - } - return -1; - }; - - //// exported async module functions //// - - //// nextTick implementation with browser-compatible fallback //// - async.nextTick = function (fn) { - if (typeof process === 'undefined' || !(process.nextTick)) { - setTimeout(fn, 0); - } - else { - process.nextTick(fn); - } - }; - - async.forEach = function (arr, iterator, callback) { - if (!arr.length) { - return callback(); - } - var completed = 0; - _forEach(arr, function (x) { - iterator(x, function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed === arr.length) { - callback(); - } - } - }); - }); - }; - - async.forEachSeries = function (arr, iterator, callback) { - if (!arr.length) { - return callback(); - } - var completed = 0; - var iterate = function () { - iterator(arr[completed], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed === arr.length) { - callback(); - } - else { - iterate(); - } - } - }); - }; - iterate(); - }; - - - var doParallel = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.forEach].concat(args)); - }; - }; - var doSeries = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.forEachSeries].concat(args)); - }; - }; - - - var _asyncMap = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (err, v) { - results[x.index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - }; - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_asyncMap); - - - // reduce only has a series version, as doing reduce in parallel won't - // work in many situations. - async.reduce = function (arr, memo, iterator, callback) { - async.forEachSeries(arr, function (x, callback) { - iterator(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); - }; - // inject alias - async.inject = async.reduce; - // foldl alias - async.foldl = async.reduce; - - async.reduceRight = function (arr, memo, iterator, callback) { - var reversed = _map(arr, function (x) { - return x; - }).reverse(); - async.reduce(reversed, memo, iterator, callback); - }; - // foldr alias - async.foldr = async.reduceRight; - - var _filter = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.filter = doParallel(_filter); - async.filterSeries = doSeries(_filter); - // select alias - async.select = async.filter; - async.selectSeries = async.filterSeries; - - var _reject = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (!v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.reject = doParallel(_reject); - async.rejectSeries = doSeries(_reject); - - var _detect = function (eachfn, arr, iterator, main_callback) { - eachfn(arr, function (x, callback) { - iterator(x, function (result) { - if (result) { - main_callback(x); - } - else { - callback(); - } - }); - }, function (err) { - main_callback(); - }); - }; - async.detect = doParallel(_detect); - async.detectSeries = doSeries(_detect); - - async.some = function (arr, iterator, main_callback) { - async.forEach(arr, function (x, callback) { - iterator(x, function (v) { - if (v) { - main_callback(true); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(false); - }); - }; - // any alias - async.any = async.some; - - async.every = function (arr, iterator, main_callback) { - async.forEach(arr, function (x, callback) { - iterator(x, function (v) { - if (!v) { - main_callback(false); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(true); - }); - }; - // all alias - async.all = async.every; - - async.sortBy = function (arr, iterator, callback) { - async.map(arr, function (x, callback) { - iterator(x, function (err, criteria) { - if (err) { - callback(err); - } - else { - callback(null, {value: x, criteria: criteria}); - } - }); - }, function (err, results) { - if (err) { - return callback(err); - } - else { - var fn = function (left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - if (!keys.length) { - return callback(null); - } - - var completed = []; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - _forEach(listeners, function (fn) { - fn(); - }); - }; - - addListener(function () { - if (completed.length === keys.length) { - callback(null); - } - }); - - _forEach(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - if (err) { - callback(err); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - completed.push(k); - taskComplete(); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && _indexOf(completed, x) !== -1); - }, true); - }; - if (ready()) { - task[task.length - 1](taskCallback); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - if (!tasks.length) { - return callback(); - } - callback = callback || function () {}; - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.nextTick(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - async.parallel = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args || null); - }); - } - }, callback); - } - else { - var results = {}; - async.forEach(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args || null); - }); - } - }, callback); - } - else { - var results = {}; - async.forEachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.queue = function (worker, concurrency) { - var workers = 0; - var tasks = []; - var q = { - concurrency: concurrency, - push: function (data, callback) { - tasks.push({data: data, callback: callback}); - async.nextTick(q.process); - }, - process: function () { - if (workers < q.concurrency && tasks.length) { - var task = tasks.splice(0, 1)[0]; - workers += 1; - worker(task.data, function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - q.process(); - }); - } - }, - length: function () { - return tasks.length; - } - }; - return q; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _forEach(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - -}()); -(function(exports){ -/** - * This file is based on the node.js assert module, but with some small - * changes for browser-compatibility - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - */ - - -/** - * Added for browser compatibility - */ - -var _keys = function(obj){ - if(Object.keys) return Object.keys(obj); - var keys = []; - for(var k in obj){ - if(obj.hasOwnProperty(k)) keys.push(k); - } - return keys; -}; - - - -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var pSlice = Array.prototype.slice; - -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = exports; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({message: message, actual: actual, expected: expected}) - -assert.AssertionError = function AssertionError (options) { - this.name = "AssertionError"; - this.message = options.message; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } -}; -// code from util.inherits in node -assert.AssertionError.super_ = Error; - - -// EDITED FOR BROWSER COMPATIBILITY: replaced Object.create call -// TODO: test what effect this may have -var ctor = function () { this.constructor = assert.AssertionError; }; -ctor.prototype = Error.prototype; -assert.AssertionError.prototype = new ctor(); - - -assert.AssertionError.prototype.toString = function() { - if (this.message) { - return [this.name+":", this.message].join(' '); - } else { - return [ this.name+":" - , JSON.stringify(this.expected ) - , this.operator - , JSON.stringify(this.actual) - ].join(" "); - } -}; - -// assert.AssertionError instanceof Error - -assert.AssertionError.__proto__ = Error.prototype; - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -assert.ok = function ok(value, message) { - if (!!!value) fail(value, true, message, "==", assert.ok); -}; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, "==", assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, "!=", assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, "deepEqual", assert.deepEqual); - } -}; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - // 7.3. Other pairs that do not both pass typeof value == "object", - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; - - // 7.4. For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical "prototype" property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isUndefinedOrNull (value) { - return value === null || value === undefined; -} - -function isArguments (object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv (a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) - return false; - // an identical "prototype" property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try{ - var ka = _keys(a), - kb = _keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key] )) - return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, "notDeepEqual", assert.notDeepEqual); - } -}; - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, "===", assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as determined by !==. -// assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, "!==", assert.notStrictEqual); - } -}; - -function _throws (shouldThrow, block, err, message) { - var exception = null, - threw = false, - typematters = true; - - message = message || ""; - - //handle optional arguments - if (arguments.length == 3) { - if (typeof(err) == "string") { - message = err; - typematters = false; - } - } else if (arguments.length == 2) { - typematters = false; - } - - try { - block(); - } catch (e) { - threw = true; - exception = e; - } - - if (shouldThrow && !threw) { - fail( "Missing expected exception" - + (err && err.name ? " ("+err.name+")." : '.') - + (message ? " " + message : "") - ); - } - if (!shouldThrow && threw && typematters && exception instanceof err) { - fail( "Got unwanted exception" - + (err && err.name ? " ("+err.name+")." : '.') - + (message ? " " + message : "") - ); - } - if ((shouldThrow && threw && typematters && !(exception instanceof err)) || - (!shouldThrow && threw)) { - throw exception; - } -}; - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function (err) { if (err) {throw err;}}; -})(assert); -(function(exports){ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -/** - * Module dependencies - */ - - - -/** - * Creates assertion objects representing the result of an assert call. - * Accepts an object or AssertionError as its argument. - * - * @param {object} obj - * @api public - */ - -exports.assertion = function (obj) { - return { - method: obj.method || '', - message: obj.message || (obj.error && obj.error.message) || '', - error: obj.error, - passed: function () { - return !this.error; - }, - failed: function () { - return Boolean(this.error); - } - }; -}; - -/** - * Creates an assertion list object representing a group of assertions. - * Accepts an array of assertion objects. - * - * @param {Array} arr - * @param {Number} duration - * @api public - */ - -exports.assertionList = function (arr, duration) { - var that = arr || []; - that.failures = function () { - var failures = 0; - for (var i=0; i(' + - '' + assertions.failures() + ', ' + - '' + assertions.passes() + ', ' + - assertions.length + - ')'; - test.className = assertions.failures() ? 'fail': 'pass'; - test.appendChild(strong); - - var aList = document.createElement('ol'); - aList.style.display = 'none'; - test.onclick = function () { - var d = aList.style.display; - aList.style.display = (d == 'none') ? 'block': 'none'; - }; - for (var i=0; i' + (a.error.stack || a.error) + ''; - li.className = 'fail'; - } - else { - li.innerHTML = a.message || a.method || 'no message'; - li.className = 'pass'; - } - aList.appendChild(li); - } - test.appendChild(aList); - tests.appendChild(test); - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - - var failures = assertions.failures(); - banner.className = failures ? 'fail': 'pass'; - - result.innerHTML = 'Tests completed in ' + duration + - ' milliseconds.
' + - assertions.passes() + ' assertions of ' + - '' + assertions.length + ' passed, ' + - assertions.failures() + ' failed.'; - } - }); -}; -})(reporter); -nodeunit = core; -nodeunit.assert = assert; -nodeunit.reporter = reporter; -nodeunit.run = reporter.run; -return nodeunit; })(); diff --git a/node_modules/bake/node_modules/async/dist/async.min.js b/node_modules/bake/node_modules/async/dist/async.min.js deleted file mode 100644 index 2c5b58f..0000000 --- a/node_modules/bake/node_modules/async/dist/async.min.js +++ /dev/null @@ -1 +0,0 @@ -/*global setTimeout: false, console: false */(function(){var a={},b=this,c=b.async;typeof module!="undefined"&&module.exports?module.exports=a:b.async=a,a.noConflict=function(){return b.async=c,a};var d=function(a,b){if(a.forEach)return a.forEach(b);for(var c=0;cd?1:0};d(null,e(b.sort(c),function(a){return a.value}))})},a.auto=function(a,b){b=b||function(){};var c=g(a);if(!c.length)return b(null);var e={},h=[],i=function(a){h.unshift(a)},j=function(a){for(var b=0;b b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - if (!keys.length) { - return callback(null); - } - - var results = {}; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - _forEach(listeners.slice(0), function (fn) { - fn(); - }); - }; - - addListener(function () { - if (_keys(results).length === keys.length) { - callback(null, results); - callback = function () {}; - } - }); - - _forEach(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - if (err) { - callback(err); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - taskComplete(); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && results.hasOwnProperty(x)); - }, true); - }; - if (ready()) { - task[task.length - 1](taskCallback, results); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback, results); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - if (!tasks.length) { - return callback(); - } - callback = callback || function () {}; - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.nextTick(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - async.parallel = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - async.forEach(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args); - }); - } - }, callback); - } - else { - var results = {}; - async.forEachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.queue = function (worker, concurrency) { - var workers = 0; - var q = { - tasks: [], - concurrency: concurrency, - saturated: null, - empty: null, - drain: null, - push: function (data, callback) { - if(data.constructor !== Array) { - data = [data]; - } - _forEach(data, function(task) { - q.tasks.push({ - data: task, - callback: typeof callback === 'function' ? callback : null - }); - if (q.saturated && q.tasks.length == concurrency) { - q.saturated(); - } - async.nextTick(q.process); - }); - }, - process: function () { - if (workers < q.concurrency && q.tasks.length) { - var task = q.tasks.shift(); - if(q.empty && q.tasks.length == 0) q.empty(); - workers += 1; - worker(task.data, function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - if(q.drain && q.tasks.length + workers == 0) q.drain(); - q.process(); - }); - } - }, - length: function () { - return q.tasks.length; - }, - running: function () { - return workers; - } - }; - return q; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _forEach(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - - async.memoize = function (fn, hasher) { - var memo = {}; - var queues = {}; - hasher = hasher || function (x) { - return x; - }; - var memoized = function () { - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - var key = hasher.apply(null, args); - if (key in memo) { - callback.apply(null, memo[key]); - } - else if (key in queues) { - queues[key].push(callback); - } - else { - queues[key] = [callback]; - fn.apply(null, args.concat([function () { - memo[key] = arguments; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, arguments); - } - }])); - } - }; - memoized.unmemoized = fn; - return memoized; - }; - - async.unmemoize = function (fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - } - }; - -}()); diff --git a/node_modules/bake/node_modules/async/nodelint.cfg b/node_modules/bake/node_modules/async/nodelint.cfg deleted file mode 100644 index 457a967..0000000 --- a/node_modules/bake/node_modules/async/nodelint.cfg +++ /dev/null @@ -1,4 +0,0 @@ -var options = { - indent: 4, - onevar: false -}; diff --git a/node_modules/bake/node_modules/async/package.json b/node_modules/bake/node_modules/async/package.json deleted file mode 100644 index 92f5546..0000000 --- a/node_modules/bake/node_modules/async/package.json +++ /dev/null @@ -1,16 +0,0 @@ -{ "name": "async" -, "description": "Higher-order functions and common patterns for asynchronous code" -, "main": "./index" -, "author": "Caolan McMahon" -, "version": "0.1.16" -, "repository" : - { "type" : "git" - , "url" : "http://github.com/caolan/async.git" - } -, "bugs" : { "url" : "http://github.com/caolan/async/issues" } -, "licenses" : - [ { "type" : "MIT" - , "url" : "http://github.com/caolan/async/raw/master/LICENSE" - } - ] -} diff --git a/node_modules/bake/node_modules/async/test/.swp b/node_modules/bake/node_modules/async/test/.swp deleted file mode 100644 index 8672264..0000000 Binary files a/node_modules/bake/node_modules/async/test/.swp and /dev/null differ diff --git a/node_modules/bake/node_modules/async/test/test-async.js b/node_modules/bake/node_modules/async/test/test-async.js deleted file mode 100644 index b654a97..0000000 --- a/node_modules/bake/node_modules/async/test/test-async.js +++ /dev/null @@ -1,1625 +0,0 @@ -var async = require('../lib/async'); - - -exports['auto'] = function(test){ - var callOrder = []; - var testdata = [{test: 'test'}]; - async.auto({ - task1: ['task2', function(callback){ - setTimeout(function(){ - callOrder.push('task1'); - callback(); - }, 25); - }], - task2: function(callback){ - setTimeout(function(){ - callOrder.push('task2'); - callback(); - }, 50); - }, - task3: ['task2', function(callback){ - callOrder.push('task3'); - callback(); - }], - task4: ['task1', 'task2', function(callback){ - callOrder.push('task4'); - callback(); - }] - }, - function(err){ - test.same(callOrder, ['task2','task3','task1','task4']); - test.done(); - }); -}; - -exports['auto results'] = function(test){ - var callOrder = []; - async.auto({ - task1: ['task2', function(callback, results){ - test.same(results.task2, 'task2'); - setTimeout(function(){ - callOrder.push('task1'); - callback(null, 'task1a', 'task1b'); - }, 25); - }], - task2: function(callback){ - setTimeout(function(){ - callOrder.push('task2'); - callback(null, 'task2'); - }, 50); - }, - task3: ['task2', function(callback, results){ - test.same(results.task2, 'task2'); - callOrder.push('task3'); - callback(null); - }], - task4: ['task1', 'task2', function(callback, results){ - test.same(results.task1, ['task1a','task1b']); - test.same(results.task2, 'task2'); - callOrder.push('task4'); - callback(null, 'task4'); - }] - }, - function(err, results){ - test.same(callOrder, ['task2','task3','task1','task4']); - test.same(results, {task1: ['task1a','task1b'], task2: 'task2', task3: undefined, task4: 'task4'}); - test.done(); - }); -}; - - -exports['auto empty object'] = function(test){ - async.auto({}, function(err){ - test.done(); - }); -}; - -exports['auto error'] = function(test){ - test.expect(1); - async.auto({ - task1: function(callback){ - callback('testerror'); - }, - task2: ['task1', function(callback){ - test.ok(false, 'task2 should not be called'); - callback(); - }], - task3: function(callback){ - callback('testerror2'); - } - }, - function(err){ - test.equals(err, 'testerror'); - }); - setTimeout(test.done, 100); -}; - -exports['auto no callback'] = function(test){ - async.auto({ - task1: function(callback){callback();}, - task2: ['task1', function(callback){callback(); test.done();}] - }); -}; - -// Issue 24 on github: https://github.com/caolan/async/issues#issue/24 -// Issue 76 on github: https://github.com/caolan/async/issues#issue/76 -exports['auto removeListener has side effect on loop iterator'] = function(test) { - async.auto({ - task1: ['task3', function(callback) { test.done() }], - task2: ['task3', function(callback) { /* by design: DON'T call callback */ }], - task3: function(callback) { callback(); } - }); -}; - -exports['waterfall'] = function(test){ - test.expect(6); - var call_order = []; - async.waterfall([ - function(callback){ - call_order.push('fn1'); - setTimeout(function(){callback(null, 'one', 'two');}, 0); - }, - function(arg1, arg2, callback){ - call_order.push('fn2'); - test.equals(arg1, 'one'); - test.equals(arg2, 'two'); - setTimeout(function(){callback(null, arg1, arg2, 'three');}, 25); - }, - function(arg1, arg2, arg3, callback){ - call_order.push('fn3'); - test.equals(arg1, 'one'); - test.equals(arg2, 'two'); - test.equals(arg3, 'three'); - callback(null, 'four'); - }, - function(arg4, callback){ - call_order.push('fn4'); - test.same(call_order, ['fn1','fn2','fn3','fn4']); - callback(null, 'test'); - } - ], function(err){ - test.done(); - }); -}; - -exports['waterfall empty array'] = function(test){ - async.waterfall([], function(err){ - test.done(); - }); -}; - -exports['waterfall no callback'] = function(test){ - async.waterfall([ - function(callback){callback();}, - function(callback){callback(); test.done();} - ]); -}; - -exports['waterfall async'] = function(test){ - var call_order = []; - async.waterfall([ - function(callback){ - call_order.push(1); - callback(); - call_order.push(2); - }, - function(callback){ - call_order.push(3); - callback(); - }, - function(){ - test.same(call_order, [1,2,3]); - test.done(); - } - ]); -}; - -exports['waterfall error'] = function(test){ - test.expect(1); - async.waterfall([ - function(callback){ - callback('error'); - }, - function(callback){ - test.ok(false, 'next function should not be called'); - callback(); - } - ], function(err){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['waterfall multiple callback calls'] = function(test){ - var call_order = []; - var arr = [ - function(callback){ - call_order.push(1); - // call the callback twice. this should call function 2 twice - callback(null, 'one', 'two'); - callback(null, 'one', 'two'); - }, - function(arg1, arg2, callback){ - call_order.push(2); - callback(null, arg1, arg2, 'three'); - }, - function(arg1, arg2, arg3, callback){ - call_order.push(3); - callback(null, 'four'); - }, - function(arg4){ - call_order.push(4); - arr[3] = function(){ - call_order.push(4); - test.same(call_order, [1,2,2,3,3,4,4]); - test.done(); - }; - } - ]; - async.waterfall(arr); -}; - - -exports['parallel'] = function(test){ - var call_order = []; - async.parallel([ - function(callback){ - setTimeout(function(){ - call_order.push(1); - callback(null, 1); - }, 50); - }, - function(callback){ - setTimeout(function(){ - call_order.push(2); - callback(null, 2); - }, 100); - }, - function(callback){ - setTimeout(function(){ - call_order.push(3); - callback(null, 3,3); - }, 25); - } - ], - function(err, results){ - test.equals(err, null); - test.same(call_order, [3,1,2]); - test.same(results, [1,2,[3,3]]); - test.done(); - }); -}; - -exports['parallel empty array'] = function(test){ - async.parallel([], function(err, results){ - test.equals(err, null); - test.same(results, []); - test.done(); - }); -}; - -exports['parallel error'] = function(test){ - async.parallel([ - function(callback){ - callback('error', 1); - }, - function(callback){ - callback('error2', 2); - } - ], - function(err, results){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 100); -}; - -exports['parallel no callback'] = function(test){ - async.parallel([ - function(callback){callback();}, - function(callback){callback(); test.done();}, - ]); -}; - -exports['parallel object'] = function(test){ - var call_order = []; - async.parallel({ - one: function(callback){ - setTimeout(function(){ - call_order.push(1); - callback(null, 1); - }, 25); - }, - two: function(callback){ - setTimeout(function(){ - call_order.push(2); - callback(null, 2); - }, 50); - }, - three: function(callback){ - setTimeout(function(){ - call_order.push(3); - callback(null, 3,3); - }, 15); - } - }, - function(err, results){ - test.equals(err, null); - test.same(call_order, [3,1,2]); - test.same(results, { - one: 1, - two: 2, - three: [3,3] - }); - test.done(); - }); -}; - -exports['series'] = function(test){ - var call_order = []; - async.series([ - function(callback){ - setTimeout(function(){ - call_order.push(1); - callback(null, 1); - }, 25); - }, - function(callback){ - setTimeout(function(){ - call_order.push(2); - callback(null, 2); - }, 50); - }, - function(callback){ - setTimeout(function(){ - call_order.push(3); - callback(null, 3,3); - }, 15); - } - ], - function(err, results){ - test.equals(err, null); - test.same(results, [1,2,[3,3]]); - test.same(call_order, [1,2,3]); - test.done(); - }); -}; - -exports['series empty array'] = function(test){ - async.series([], function(err, results){ - test.equals(err, null); - test.same(results, []); - test.done(); - }); -}; - -exports['series error'] = function(test){ - test.expect(1); - async.series([ - function(callback){ - callback('error', 1); - }, - function(callback){ - test.ok(false, 'should not be called'); - callback('error2', 2); - } - ], - function(err, results){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 100); -}; - -exports['series no callback'] = function(test){ - async.series([ - function(callback){callback();}, - function(callback){callback(); test.done();}, - ]); -}; - -exports['series object'] = function(test){ - var call_order = []; - async.series({ - one: function(callback){ - setTimeout(function(){ - call_order.push(1); - callback(null, 1); - }, 25); - }, - two: function(callback){ - setTimeout(function(){ - call_order.push(2); - callback(null, 2); - }, 50); - }, - three: function(callback){ - setTimeout(function(){ - call_order.push(3); - callback(null, 3,3); - }, 15); - } - }, - function(err, results){ - test.equals(err, null); - test.same(results, { - one: 1, - two: 2, - three: [3,3] - }); - test.same(call_order, [1,2,3]); - test.done(); - }); -}; - -exports['iterator'] = function(test){ - var call_order = []; - var iterator = async.iterator([ - function(){call_order.push(1);}, - function(arg1){ - test.equals(arg1, 'arg1'); - call_order.push(2); - }, - function(arg1, arg2){ - test.equals(arg1, 'arg1'); - test.equals(arg2, 'arg2'); - call_order.push(3); - } - ]); - iterator(); - test.same(call_order, [1]); - var iterator2 = iterator(); - test.same(call_order, [1,1]); - var iterator3 = iterator2('arg1'); - test.same(call_order, [1,1,2]); - var iterator4 = iterator3('arg1', 'arg2'); - test.same(call_order, [1,1,2,3]); - test.equals(iterator4, undefined); - test.done(); -}; - -exports['iterator empty array'] = function(test){ - var iterator = async.iterator([]); - test.equals(iterator(), undefined); - test.equals(iterator.next(), undefined); - test.done(); -}; - -exports['iterator.next'] = function(test){ - var call_order = []; - var iterator = async.iterator([ - function(){call_order.push(1);}, - function(arg1){ - test.equals(arg1, 'arg1'); - call_order.push(2); - }, - function(arg1, arg2){ - test.equals(arg1, 'arg1'); - test.equals(arg2, 'arg2'); - call_order.push(3); - } - ]); - var fn = iterator.next(); - var iterator2 = fn('arg1'); - test.same(call_order, [2]); - iterator2('arg1','arg2'); - test.same(call_order, [2,3]); - test.equals(iterator2.next(), undefined); - test.done(); -}; - -exports['forEach'] = function(test){ - var args = []; - async.forEach([1,3,2], function(x, callback){ - setTimeout(function(){ - args.push(x); - callback(); - }, x*25); - }, function(err){ - test.same(args, [1,2,3]); - test.done(); - }); -}; - -exports['forEach empty array'] = function(test){ - test.expect(1); - async.forEach([], function(x, callback){ - test.ok(false, 'iterator should not be called'); - callback(); - }, function(err){ - test.ok(true, 'should call callback'); - }); - setTimeout(test.done, 25); -}; - -exports['forEach error'] = function(test){ - test.expect(1); - async.forEach([1,2,3], function(x, callback){ - callback('error'); - }, function(err){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['forEachSeries'] = function(test){ - var args = []; - async.forEachSeries([1,3,2], function(x, callback){ - setTimeout(function(){ - args.push(x); - callback(); - }, x*25); - }, function(err){ - test.same(args, [1,3,2]); - test.done(); - }); -}; - -exports['forEachSeries empty array'] = function(test){ - test.expect(1); - async.forEachSeries([], function(x, callback){ - test.ok(false, 'iterator should not be called'); - callback(); - }, function(err){ - test.ok(true, 'should call callback'); - }); - setTimeout(test.done, 25); -}; - -exports['forEachSeries error'] = function(test){ - test.expect(2); - var call_order = []; - async.forEachSeries([1,2,3], function(x, callback){ - call_order.push(x); - callback('error'); - }, function(err){ - test.same(call_order, [1]); - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['forEachLimit'] = function(test){ - var args = []; - var arr = [0,1,2,3,4,5,6,7,8,9]; - async.forEachLimit(arr, 2, function(x,callback){ - setTimeout(function(){ - args.push(x); - callback(); - }, x*5); - }, function(err){ - test.same(args, arr); - test.done(); - }); -}; - -exports['forEachLimit empty array'] = function(test){ - test.expect(1); - async.forEachLimit([], 2, function(x, callback){ - test.ok(false, 'iterator should not be called'); - callback(); - }, function(err){ - test.ok(true, 'should call callback'); - }); - setTimeout(test.done, 25); -}; - -exports['forEachLimit limit exceeds size'] = function(test){ - var args = []; - var arr = [0,1,2,3,4,5,6,7,8,9]; - async.forEachLimit(arr, 20, function(x,callback){ - setTimeout(function(){ - args.push(x); - callback(); - }, x*25); - }, function(err){ - test.same(args, arr); - test.done(); - }); -}; - -exports['forEachLimit limit equal size'] = function(test){ - var args = []; - var arr = [0,1,2,3,4,5,6,7,8,9]; - async.forEachLimit(arr, 10, function(x,callback){ - setTimeout(function(){ - args.push(x); - callback(); - }, x*25); - }, function(err){ - test.same(args, arr); - test.done(); - }); -}; - -exports['forEachLimit zero limit'] = function(test){ - test.expect(1); - async.forEachLimit([0,1,2,3,4,5], 0, function(x, callback){ - test.ok(false, 'iterator should not be called'); - callback(); - }, function(err){ - test.ok(true, 'should call callback'); - }); - setTimeout(test.done, 25); -}; - -exports['forEachLimit error'] = function(test){ - test.expect(2); - var arr = [0,1,2,3,4,5,6,7,8,9]; - var call_order = []; - - async.forEachLimit(arr, 3, function(x, callback){ - call_order.push(x); - if (x === 2) { - callback('error'); - } - }, function(err){ - test.same(call_order, [0,1,2]); - test.equals(err, 'error'); - }); - setTimeout(test.done, 25); -}; - -exports['map'] = function(test){ - var call_order = []; - async.map([1,3,2], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(null, x*2); - }, x*25); - }, function(err, results){ - test.same(call_order, [1,2,3]); - test.same(results, [2,6,4]); - test.done(); - }); -}; - -exports['map original untouched'] = function(test){ - var a = [1,2,3]; - async.map(a, function(x, callback){ - callback(null, x*2); - }, function(err, results){ - test.same(results, [2,4,6]); - test.same(a, [1,2,3]); - test.done(); - }); -}; - -exports['map error'] = function(test){ - test.expect(1); - async.map([1,2,3], function(x, callback){ - callback('error'); - }, function(err, results){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['mapSeries'] = function(test){ - var call_order = []; - async.mapSeries([1,3,2], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(null, x*2); - }, x*25); - }, function(err, results){ - test.same(call_order, [1,3,2]); - test.same(results, [2,6,4]); - test.done(); - }); -}; - -exports['mapSeries error'] = function(test){ - test.expect(1); - async.mapSeries([1,2,3], function(x, callback){ - callback('error'); - }, function(err, results){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['reduce'] = function(test){ - var call_order = []; - async.reduce([1,2,3], 0, function(a, x, callback){ - call_order.push(x); - callback(null, a + x); - }, function(err, result){ - test.equals(result, 6); - test.same(call_order, [1,2,3]); - test.done(); - }); -}; - -exports['reduce async with non-reference memo'] = function(test){ - async.reduce([1,3,2], 0, function(a, x, callback){ - setTimeout(function(){callback(null, a + x)}, Math.random()*100); - }, function(err, result){ - test.equals(result, 6); - test.done(); - }); -}; - -exports['reduce error'] = function(test){ - test.expect(1); - async.reduce([1,2,3], 0, function(a, x, callback){ - callback('error'); - }, function(err, result){ - test.equals(err, 'error'); - }); - setTimeout(test.done, 50); -}; - -exports['inject alias'] = function(test){ - test.equals(async.inject, async.reduce); - test.done(); -}; - -exports['foldl alias'] = function(test){ - test.equals(async.foldl, async.reduce); - test.done(); -}; - -exports['reduceRight'] = function(test){ - var call_order = []; - var a = [1,2,3]; - async.reduceRight(a, 0, function(a, x, callback){ - call_order.push(x); - callback(null, a + x); - }, function(err, result){ - test.equals(result, 6); - test.same(call_order, [3,2,1]); - test.same(a, [1,2,3]); - test.done(); - }); -}; - -exports['foldr alias'] = function(test){ - test.equals(async.foldr, async.reduceRight); - test.done(); -}; - -exports['filter'] = function(test){ - async.filter([3,1,2], function(x, callback){ - setTimeout(function(){callback(x % 2);}, x*25); - }, function(results){ - test.same(results, [3,1]); - test.done(); - }); -}; - -exports['filter original untouched'] = function(test){ - var a = [3,1,2]; - async.filter(a, function(x, callback){ - callback(x % 2); - }, function(results){ - test.same(results, [3,1]); - test.same(a, [3,1,2]); - test.done(); - }); -}; - -exports['filterSeries'] = function(test){ - async.filterSeries([3,1,2], function(x, callback){ - setTimeout(function(){callback(x % 2);}, x*25); - }, function(results){ - test.same(results, [3,1]); - test.done(); - }); -}; - -exports['select alias'] = function(test){ - test.equals(async.select, async.filter); - test.done(); -}; - -exports['selectSeries alias'] = function(test){ - test.equals(async.selectSeries, async.filterSeries); - test.done(); -}; - -exports['reject'] = function(test){ - async.reject([3,1,2], function(x, callback){ - setTimeout(function(){callback(x % 2);}, x*25); - }, function(results){ - test.same(results, [2]); - test.done(); - }); -}; - -exports['reject original untouched'] = function(test){ - var a = [3,1,2]; - async.reject(a, function(x, callback){ - callback(x % 2); - }, function(results){ - test.same(results, [2]); - test.same(a, [3,1,2]); - test.done(); - }); -}; - -exports['rejectSeries'] = function(test){ - async.rejectSeries([3,1,2], function(x, callback){ - setTimeout(function(){callback(x % 2);}, x*25); - }, function(results){ - test.same(results, [2]); - test.done(); - }); -}; - -exports['some true'] = function(test){ - async.some([3,1,2], function(x, callback){ - setTimeout(function(){callback(x === 1);}, 0); - }, function(result){ - test.equals(result, true); - test.done(); - }); -}; - -exports['some false'] = function(test){ - async.some([3,1,2], function(x, callback){ - setTimeout(function(){callback(x === 10);}, 0); - }, function(result){ - test.equals(result, false); - test.done(); - }); -}; - -exports['some early return'] = function(test){ - var call_order = []; - async.some([1,2,3], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x === 1); - }, x*25); - }, function(result){ - call_order.push('callback'); - }); - setTimeout(function(){ - test.same(call_order, [1,'callback',2,3]); - test.done(); - }, 100); -}; - -exports['any alias'] = function(test){ - test.equals(async.any, async.some); - test.done(); -}; - -exports['every true'] = function(test){ - async.every([1,2,3], function(x, callback){ - setTimeout(function(){callback(true);}, 0); - }, function(result){ - test.equals(result, true); - test.done(); - }); -}; - -exports['every false'] = function(test){ - async.every([1,2,3], function(x, callback){ - setTimeout(function(){callback(x % 2);}, 0); - }, function(result){ - test.equals(result, false); - test.done(); - }); -}; - -exports['every early return'] = function(test){ - var call_order = []; - async.every([1,2,3], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x === 1); - }, x*25); - }, function(result){ - call_order.push('callback'); - }); - setTimeout(function(){ - test.same(call_order, [1,2,'callback',3]); - test.done(); - }, 100); -}; - -exports['all alias'] = function(test){ - test.equals(async.all, async.every); - test.done(); -}; - -exports['detect'] = function(test){ - var call_order = []; - async.detect([3,2,1], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x == 2); - }, x*25); - }, function(result){ - call_order.push('callback'); - test.equals(result, 2); - }); - setTimeout(function(){ - test.same(call_order, [1,2,'callback',3]); - test.done(); - }, 100); -}; - -exports['detect - mulitple matches'] = function(test){ - var call_order = []; - async.detect([3,2,2,1,2], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x == 2); - }, x*25); - }, function(result){ - call_order.push('callback'); - test.equals(result, 2); - }); - setTimeout(function(){ - test.same(call_order, [1,2,'callback',2,2,3]); - test.done(); - }, 100); -}; - -exports['detectSeries'] = function(test){ - var call_order = []; - async.detectSeries([3,2,1], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x == 2); - }, x*25); - }, function(result){ - call_order.push('callback'); - test.equals(result, 2); - }); - setTimeout(function(){ - test.same(call_order, [3,2,'callback']); - test.done(); - }, 200); -}; - -exports['detectSeries - multiple matches'] = function(test){ - var call_order = []; - async.detectSeries([3,2,2,1,2], function(x, callback){ - setTimeout(function(){ - call_order.push(x); - callback(x == 2); - }, x*25); - }, function(result){ - call_order.push('callback'); - test.equals(result, 2); - }); - setTimeout(function(){ - test.same(call_order, [3,2,'callback']); - test.done(); - }, 200); -}; - -exports['sortBy'] = function(test){ - async.sortBy([{a:1},{a:15},{a:6}], function(x, callback){ - setTimeout(function(){callback(null, x.a);}, 0); - }, function(err, result){ - test.same(result, [{a:1},{a:6},{a:15}]); - test.done(); - }); -}; - -exports['apply'] = function(test){ - test.expect(6); - var fn = function(){ - test.same(Array.prototype.slice.call(arguments), [1,2,3,4]) - }; - async.apply(fn, 1, 2, 3, 4)(); - async.apply(fn, 1, 2, 3)(4); - async.apply(fn, 1, 2)(3, 4); - async.apply(fn, 1)(2, 3, 4); - async.apply(fn)(1, 2, 3, 4); - test.equals( - async.apply(function(name){return 'hello ' + name}, 'world')(), - 'hello world' - ); - test.done(); -}; - - -// generates tests for console functions such as async.log -var console_fn_tests = function(name){ - - if (typeof console !== 'undefined') { - exports[name] = function(test){ - test.expect(5); - var fn = function(arg1, callback){ - test.equals(arg1, 'one'); - setTimeout(function(){callback(null, 'test');}, 0); - }; - var fn_err = function(arg1, callback){ - test.equals(arg1, 'one'); - setTimeout(function(){callback('error');}, 0); - }; - var _console_fn = console[name]; - var _error = console.error; - console[name] = function(val){ - test.equals(val, 'test'); - test.equals(arguments.length, 1); - console.error = function(val){ - test.equals(val, 'error'); - console[name] = _console_fn; - console.error = _error; - test.done(); - }; - async[name](fn_err, 'one'); - }; - async[name](fn, 'one'); - }; - - exports[name + ' with multiple result params'] = function(test){ - var fn = function(callback){callback(null,'one','two','three');}; - var _console_fn = console[name]; - var called_with = []; - console[name] = function(x){ - called_with.push(x); - }; - async[name](fn); - test.same(called_with, ['one','two','three']); - console[name] = _console_fn; - test.done(); - }; - } - - // browser-only test - exports[name + ' without console.' + name] = function(test){ - if (typeof window !== 'undefined') { - var _console = window.console; - window.console = undefined; - var fn = function(callback){callback(null, 'val');}; - var fn_err = function(callback){callback('error');}; - async[name](fn); - async[name](fn_err); - window.console = _console; - } - test.done(); - }; - -}; - -console_fn_tests('log'); -console_fn_tests('dir'); -/*console_fn_tests('info'); -console_fn_tests('warn'); -console_fn_tests('error');*/ - -exports['nextTick'] = function(test){ - var call_order = []; - async.nextTick(function(){call_order.push('two');}); - call_order.push('one'); - setTimeout(function(){ - test.same(call_order, ['one','two']); - test.done(); - }, 50); -}; - -exports['nextTick in the browser'] = function(test){ - if (typeof process !== 'undefined') { - // skip this test in node - return test.done(); - } - test.expect(1); - - var call_order = []; - async.nextTick(function(){call_order.push('two');}); - - call_order.push('one'); - setTimeout(function(){ - if (typeof process !== 'undefined') { - process.nextTick = _nextTick; - } - test.same(call_order, ['one','two']); - }, 50); - setTimeout(test.done, 100); -}; - -exports['noConflict - node only'] = function(test){ - if (typeof process !== 'undefined') { - // node only test - test.expect(3); - var fs = require('fs'); - var filename = __dirname + '/../lib/async.js'; - fs.readFile(filename, function(err, content){ - if(err) return test.done(); - - // Script -> NodeScript in node v0.6.x - var Script = process.binding('evals').Script || process.binding('evals').NodeScript; - - var s = new Script(content, filename); - var s2 = new Script( - content + 'this.async2 = this.async.noConflict();', - filename - ); - - var sandbox1 = {async: 'oldvalue'}; - s.runInNewContext(sandbox1); - test.ok(sandbox1.async); - - var sandbox2 = {async: 'oldvalue'}; - s2.runInNewContext(sandbox2); - test.equals(sandbox2.async, 'oldvalue'); - test.ok(sandbox2.async2); - - test.done(); - }); - } - else test.done(); -}; - -exports['concat'] = function(test){ - var call_order = []; - var iterator = function (x, cb) { - setTimeout(function(){ - call_order.push(x); - var r = []; - while (x > 0) { - r.push(x); - x--; - } - cb(null, r); - }, x*25); - }; - async.concat([1,3,2], iterator, function(err, results){ - test.same(results, [1,2,1,3,2,1]); - test.same(call_order, [1,2,3]); - test.ok(!err); - test.done(); - }); -}; - -exports['concat error'] = function(test){ - var iterator = function (x, cb) { - cb(new Error('test error')); - }; - async.concat([1,2,3], iterator, function(err, results){ - test.ok(err); - test.done(); - }); -}; - -exports['concatSeries'] = function(test){ - var call_order = []; - var iterator = function (x, cb) { - setTimeout(function(){ - call_order.push(x); - var r = []; - while (x > 0) { - r.push(x); - x--; - } - cb(null, r); - }, x*25); - }; - async.concatSeries([1,3,2], iterator, function(err, results){ - test.same(results, [1,3,2,1,2,1]); - test.same(call_order, [1,3,2]); - test.ok(!err); - test.done(); - }); -}; - -exports['until'] = function (test) { - var call_order = []; - - var count = 0; - async.until( - function () { - call_order.push(['test', count]); - return (count == 5); - }, - function (cb) { - call_order.push(['iterator', count]); - count++; - cb(); - }, - function (err) { - test.same(call_order, [ - ['test', 0], - ['iterator', 0], ['test', 1], - ['iterator', 1], ['test', 2], - ['iterator', 2], ['test', 3], - ['iterator', 3], ['test', 4], - ['iterator', 4], ['test', 5], - ]); - test.equals(count, 5); - test.done(); - } - ); -}; - -exports['whilst'] = function (test) { - var call_order = []; - - var count = 0; - async.whilst( - function () { - call_order.push(['test', count]); - return (count < 5); - }, - function (cb) { - call_order.push(['iterator', count]); - count++; - cb(); - }, - function (err) { - test.same(call_order, [ - ['test', 0], - ['iterator', 0], ['test', 1], - ['iterator', 1], ['test', 2], - ['iterator', 2], ['test', 3], - ['iterator', 3], ['test', 4], - ['iterator', 4], ['test', 5], - ]); - test.equals(count, 5); - test.done(); - } - ); -}; - -exports['queue'] = function (test) { - var call_order = [], - delays = [160,80,240,80]; - - // worker1: --1-4 - // worker2: -2---3 - // order of completion: 2,1,4,3 - - var q = async.queue(function (task, callback) { - setTimeout(function () { - call_order.push('process ' + task); - callback('error', 'arg'); - }, delays.splice(0,1)[0]); - }, 2); - - q.push(1, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 1); - call_order.push('callback ' + 1); - }); - q.push(2, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 2); - call_order.push('callback ' + 2); - }); - q.push(3, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 0); - call_order.push('callback ' + 3); - }); - q.push(4, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 0); - call_order.push('callback ' + 4); - }); - test.equal(q.length(), 4); - test.equal(q.concurrency, 2); - - setTimeout(function () { - test.same(call_order, [ - 'process 2', 'callback 2', - 'process 1', 'callback 1', - 'process 4', 'callback 4', - 'process 3', 'callback 3' - ]); - test.equal(q.concurrency, 2); - test.equal(q.length(), 0); - test.done(); - }, 800); -}; - -exports['queue changing concurrency'] = function (test) { - var call_order = [], - delays = [40,20,60,20]; - - // worker1: --1-2---3-4 - // order of completion: 1,2,3,4 - - var q = async.queue(function (task, callback) { - setTimeout(function () { - call_order.push('process ' + task); - callback('error', 'arg'); - }, delays.splice(0,1)[0]); - }, 2); - - q.push(1, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 3); - call_order.push('callback ' + 1); - }); - q.push(2, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 2); - call_order.push('callback ' + 2); - }); - q.push(3, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 1); - call_order.push('callback ' + 3); - }); - q.push(4, function (err, arg) { - test.equal(err, 'error'); - test.equal(arg, 'arg'); - test.equal(q.length(), 0); - call_order.push('callback ' + 4); - }); - test.equal(q.length(), 4); - test.equal(q.concurrency, 2); - q.concurrency = 1; - - setTimeout(function () { - test.same(call_order, [ - 'process 1', 'callback 1', - 'process 2', 'callback 2', - 'process 3', 'callback 3', - 'process 4', 'callback 4' - ]); - test.equal(q.concurrency, 1); - test.equal(q.length(), 0); - test.done(); - }, 250); -}; - -exports['queue push without callback'] = function (test) { - var call_order = [], - delays = [160,80,240,80]; - - // worker1: --1-4 - // worker2: -2---3 - // order of completion: 2,1,4,3 - - var q = async.queue(function (task, callback) { - setTimeout(function () { - call_order.push('process ' + task); - callback('error', 'arg'); - }, delays.splice(0,1)[0]); - }, 2); - - q.push(1); - q.push(2); - q.push(3); - q.push(4); - - setTimeout(function () { - test.same(call_order, [ - 'process 2', - 'process 1', - 'process 4', - 'process 3' - ]); - test.done(); - }, 800); -}; - -exports['queue bulk task'] = function (test) { - var call_order = [], - delays = [160,80,240,80]; - - // worker1: --1-4 - // worker2: -2---3 - // order of completion: 2,1,4,3 - - var q = async.queue(function (task, callback) { - setTimeout(function () { - call_order.push('process ' + task); - callback('error', task); - }, delays.splice(0,1)[0]); - }, 2); - - q.push( [1,2,3,4], function (err, arg) { - test.equal(err, 'error'); - call_order.push('callback ' + arg); - }); - - test.equal(q.length(), 4); - test.equal(q.concurrency, 2); - - setTimeout(function () { - test.same(call_order, [ - 'process 2', 'callback 2', - 'process 1', 'callback 1', - 'process 4', 'callback 4', - 'process 3', 'callback 3' - ]); - test.equal(q.concurrency, 2); - test.equal(q.length(), 0); - test.done(); - }, 800); -}; - -exports['memoize'] = function (test) { - test.expect(4); - var call_order = []; - - var fn = function (arg1, arg2, callback) { - call_order.push(['fn', arg1, arg2]); - callback(null, arg1 + arg2); - }; - - var fn2 = async.memoize(fn); - fn2(1, 2, function (err, result) { - test.equal(result, 3); - }); - fn2(1, 2, function (err, result) { - test.equal(result, 3); - }); - fn2(2, 2, function (err, result) { - test.equal(result, 4); - }); - - test.same(call_order, [['fn',1,2], ['fn',2,2]]); - test.done(); -}; - -exports['unmemoize'] = function(test) { - test.expect(4); - var call_order = []; - - var fn = function (arg1, arg2, callback) { - call_order.push(['fn', arg1, arg2]); - callback(null, arg1 + arg2); - }; - - var fn2 = async.memoize(fn); - var fn3 = async.unmemoize(fn2); - fn3(1, 2, function (err, result) { - test.equal(result, 3); - }); - fn3(1, 2, function (err, result) { - test.equal(result, 3); - }); - fn3(2, 2, function (err, result) { - test.equal(result, 4); - }); - - test.same(call_order, [['fn',1,2], ['fn',1,2], ['fn',2,2]]); - - test.done(); -} - -exports['unmemoize a not memoized function'] = function(test) { - test.expect(1); - - var fn = function (arg1, arg2, callback) { - callback(null, arg1 + arg2); - }; - - var fn2 = async.unmemoize(fn); - fn2(1, 2, function(err, result) { - test.equal(result, 3); - }); - - test.done(); -} - -exports['memoize error'] = function (test) { - test.expect(1); - var testerr = new Error('test'); - var fn = function (arg1, arg2, callback) { - callback(testerr, arg1 + arg2); - }; - async.memoize(fn)(1, 2, function (err, result) { - test.equal(err, testerr); - }); - test.done(); -}; - -exports['memoize multiple calls'] = function (test) { - test.expect(3); - var fn = function (arg1, arg2, callback) { - test.ok(true); - setTimeout(function(){ - callback(null, arg1, arg2); - }, 10); - }; - var fn2 = async.memoize(fn); - fn2(1, 2, function(err, result) { - test.equal(result, 1, 2); - }); - fn2(1, 2, function(err, result) { - test.equal(result, 1, 2); - test.done(); - }); -}; - -exports['memoize custom hash function'] = function (test) { - test.expect(2); - var testerr = new Error('test'); - - var fn = function (arg1, arg2, callback) { - callback(testerr, arg1 + arg2); - }; - var fn2 = async.memoize(fn, function () { - return 'custom hash'; - }); - fn2(1, 2, function (err, result) { - test.equal(result, 3); - }); - fn2(2, 2, function (err, result) { - test.equal(result, 3); - }); - test.done(); -}; - -// Issue 10 on github: https://github.com/caolan/async/issues#issue/10 -exports['falsy return values in series'] = function (test) { - function taskFalse(callback) { - async.nextTick(function() { - callback(null, false); - }); - }; - function taskUndefined(callback) { - async.nextTick(function() { - callback(null, undefined); - }); - }; - function taskEmpty(callback) { - async.nextTick(function() { - callback(null); - }); - }; - function taskNull(callback) { - async.nextTick(function() { - callback(null, null); - }); - }; - async.series( - [taskFalse, taskUndefined, taskEmpty, taskNull], - function(err, results) { - test.equal(results.length, 4); - test.strictEqual(results[0], false); - test.strictEqual(results[1], undefined); - test.strictEqual(results[2], undefined); - test.strictEqual(results[3], null); - test.done(); - } - ); -}; - -// Issue 10 on github: https://github.com/caolan/async/issues#issue/10 -exports['falsy return values in parallel'] = function (test) { - function taskFalse(callback) { - async.nextTick(function() { - callback(null, false); - }); - }; - function taskUndefined(callback) { - async.nextTick(function() { - callback(null, undefined); - }); - }; - function taskEmpty(callback) { - async.nextTick(function() { - callback(null); - }); - }; - function taskNull(callback) { - async.nextTick(function() { - callback(null, null); - }); - }; - async.parallel( - [taskFalse, taskUndefined, taskEmpty, taskNull], - function(err, results) { - test.equal(results.length, 4); - test.strictEqual(results[0], false); - test.strictEqual(results[1], undefined); - test.strictEqual(results[2], undefined); - test.strictEqual(results[3], null); - test.done(); - } - ); -}; - -exports['queue events'] = function(test) { - var calls = []; - var q = async.queue(function(task, cb) { - // nop - calls.push('process ' + task); - cb(); - }, 3); - - q.saturated = function() { - test.ok(q.length() == 3, 'queue should be saturated now'); - calls.push('saturated'); - }; - q.empty = function() { - test.ok(q.length() == 0, 'queue should be empty now'); - calls.push('empty'); - }; - q.drain = function() { - test.ok( - q.length() == 0 && q.running() == 0, - 'queue should be empty now and no more workers should be running' - ); - calls.push('drain'); - test.same(calls, [ - 'saturated', - 'process foo', - 'foo cb', - 'process bar', - 'bar cb', - 'process zoo', - 'zoo cb', - 'process poo', - 'poo cb', - 'empty', - 'process moo', - 'moo cb', - 'drain', - ]); - test.done(); - }; - q.push('foo', function () {calls.push('foo cb');}); - q.push('bar', function () {calls.push('bar cb');}); - q.push('zoo', function () {calls.push('zoo cb');}); - q.push('poo', function () {calls.push('poo cb');}); - q.push('moo', function () {calls.push('moo cb');}); -}; diff --git a/node_modules/bake/node_modules/async/test/test.html b/node_modules/bake/node_modules/async/test/test.html deleted file mode 100644 index 2450e2d..0000000 --- a/node_modules/bake/node_modules/async/test/test.html +++ /dev/null @@ -1,24 +0,0 @@ - - - Async.js Test Suite - - - - - - - - -

Async.js Test Suite

- - - diff --git a/node_modules/bake/package.json b/node_modules/bake/package.json index 32a1a29..ccdc311 100644 --- a/node_modules/bake/package.json +++ b/node_modules/bake/package.json @@ -5,7 +5,7 @@ "ejs", "template" ], - "version": "1.0.1", + "version": "1.0.3", "author": "Paul Vorbach (http://vorb.de)", "repository": { "type": "git", diff --git a/node_modules/mongodb/.npmignore b/node_modules/mongodb/.npmignore index 42ccab3..ed901d9 100644 --- a/node_modules/mongodb/.npmignore +++ b/node_modules/mongodb/.npmignore @@ -1,3 +1,12 @@ .git* +.buildinfo +.mongodb docs/ +docs/sphinx-docs data/ +dev/ +examples/ +test/ +.DS_Store + + diff --git a/node_modules/mongodb/HISTORY b/node_modules/mongodb/HISTORY index da42c33..adfb2fc 100644 --- a/node_modules/mongodb/HISTORY +++ b/node_modules/mongodb/HISTORY @@ -1,3 +1,8 @@ +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + 0.9.9 2012-02-13 ---------------- * Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. diff --git a/node_modules/mongodb/deps/gleak/.npmignore b/node_modules/mongodb/deps/gleak/.npmignore deleted file mode 100644 index f6ff43a..0000000 --- a/node_modules/mongodb/deps/gleak/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -*.swp -*.swo -*.swu -node_modules/ diff --git a/node_modules/mongodb/deps/gleak/History.md b/node_modules/mongodb/deps/gleak/History.md deleted file mode 100644 index d4f9d05..0000000 --- a/node_modules/mongodb/deps/gleak/History.md +++ /dev/null @@ -1,42 +0,0 @@ - -0.2.1 / 10-18-2011 -================== - - * fixed; package.json dependency versioning - -0.2.0 / 10-11-2011 -================== - - * added; node v0.5 / v0.6 support - -0.1.3 / 09-22-2011 -================== - - * use old school node engine format in package.json - -0.1.2 / 09-08-2011 -================== - - * changed; utilize detectNew in middleware - * updated; docs - -0.1.1 / 09-07-2011 -================== - - * added; #detectNew method - -0.1.0 / 09-06-2011 -================== - - * added; #ignore method - * added; multiple instance support - -0.0.2 / 09-06-2011 -================== - - * added; allow whitelisting by variable name - -0.0.1 / 09-03-2011 -================== - - * initial release diff --git a/node_modules/mongodb/deps/gleak/Makefile b/node_modules/mongodb/deps/gleak/Makefile deleted file mode 100644 index 532107e..0000000 --- a/node_modules/mongodb/deps/gleak/Makefile +++ /dev/null @@ -1,6 +0,0 @@ - -test: - @NODE_ENV=test ./node_modules/expresso/bin/expresso \ - test/index.js - -.PHONY: test diff --git a/node_modules/mongodb/deps/gleak/README.md b/node_modules/mongodb/deps/gleak/README.md deleted file mode 100644 index 901f22a..0000000 --- a/node_modules/mongodb/deps/gleak/README.md +++ /dev/null @@ -1,118 +0,0 @@ -# Gleak -Global variable leak detection for Node.js - - var detector = require('gleak')(); - - detector.detect().forEach(function (name) { - console.warn('found global leak: %s', name); - }); - -Global variable leaks in javascript can bite you when you least -expect it. Do something about it now and run this module after -your tests, after HTTP requests, and after you brush your teeth. - -## Detectable - -As demonstrated, gleak comes with the `detect` method which returns -an array of all found variable leaks. - -Often times we want to run the detector many times, progressively -checking for any new leaks that occurred since we last checked. In -this scenario we can utilize the `detectNew` method. - - var detector = require('gleak')(); - - x = 1; - detector.detectNew(); // ['x'] - detector.detectNew(); // [] - y = 3; - detector.detectNew(); // ['y'] - -## Configurable: - -Gleak comes configured for Node.js and will ignore built-ins by default -but you can configure it however your like: - - var gleak = require('gleak')(); - gleak.ignore(app, db); - -The `gleak.ignore` method allows us to add globals we want to ignore -while safely ignoring duplicates. - -`gleak.whitelist` is an array that holds all globals we are ignoring. -You can push to it or blow it away completely with your own list too. - - var gleak = require('gleak')(); - gleak.whitelist = [dnode, cluster]; - -Changes to your whitelists do not impact any global settings. For example: - - var gleak = require('gleak'); - var g1 = gleak(); - var g2 = gleak(); - - g1.ignore(myglobal); - g2.whitelist.indexOf(myglobal) === -1; - -`g2` does not inherit changes to `g1`s whitelist. - -## Printable - -If you don't want anything fancy and want to quickly dump all -global leaks to your console, just call `print()`. - - var gleak = require('gleak')(); - gleak.print(); // prints "Gleak!: leakedVarName" - -## Expressable - -We might want to print leaked variables to our console after each -HTTP request. This is especially helpful during development. -To accomplish this we can utilize the bundled [express](http://expressjs.com) middleware: - - var app = express.createServer(); - app.use(gleak.middleware()); - -What if we want to output to a different stream than stderr? - - app.use(gleak.middleware(stream)); - -How about customized logging formats? - - app.use(gleak.middleware('\x1b[31mLeak!\x1b[0m %s')); - -Combining formats and streams? - - app.use(gleak.middleware(stream, '\x1b[31mLeak!\x1b[0m %s')); - -## Installable - - npm install gleak - -### Node version -Compatible with Node >=v0.4 <0.5.0 - -## License - -(The MIT License) - -Copyright (c) 2011 [Aaron Heckmann](aaron.heckmann+github@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongodb/deps/gleak/index.js b/node_modules/mongodb/deps/gleak/index.js deleted file mode 100644 index 6597707..0000000 --- a/node_modules/mongodb/deps/gleak/index.js +++ /dev/null @@ -1,190 +0,0 @@ - -/** - * Gleak - detect global var leaks. - * @api public - */ - -module.exports = exports = function gleak () { - return new Gleak; -} - -/** - * Version. - * @api public - */ - -exports.version = '0.2.1'; - -/** - * Express middleware. - * @api public - */ - -exports.middleware = function gleakMiddleware (stream, format) { - var g = new Gleak; - - if (!format) { - switch (typeof stream) { - case 'string': - format = stream; - stream = process.stderr; - break; - case 'undefined': - format = g.format; - stream = process.stderr; - break; - default: - format = g.format; - } - } - - setTimeout(print, 1000); - - function print () { - g.detectNew().forEach(function (leak) { - stream.write(format.replace(/%s/, leak) + '\n'); - }); - } - - return function gleakMiddleware (req, res, next) { - if (res._gleak) return next(); - res._gleak = true; - - var send = res.send; - - res.send = function () { - res.send = send; - res.send.apply(res, arguments); - print(); - } - - next(); - } -} - -/** - * Gleak constructor - * @api private - */ - -function Gleak () { - this.whitelist = this.whitelist.slice(); -} - -/** - * Whitelisted globals. - * @api public - */ - -// v0.4.x -Gleak.prototype.whitelist = [ - setTimeout - , setInterval - , clearTimeout - , clearInterval - , console - , Buffer - , process - , global - , GLOBAL - , root -]; - -// check for new globals in >= v0.5x -var version = process.version.replace(/^v/, '').split('.'); -if ('0' === version[0] && version[1] > 4) { - Gleak.prototype.whitelist.push( - ArrayBuffer - , Int8Array - , Uint8Array - , Int16Array - , Uint16Array - , Int32Array - , Uint32Array - , Float32Array - , Float64Array - , DataView - , 'errno' // node >= v0.5.x hack - ) -} - -/** - * Default format. - * @api public - */ - -Gleak.prototype.format = '\x1b[31mGleak!:\x1b[0m %s'; - -/** - * Detects global variable leaks. - * @api public - */ - -Gleak.prototype.detect = function detect () { - var whitelist = this.whitelist - , ret = [] - - Object.keys(global).forEach(function (key) { - var w = whitelist.length - , bad = true - , white - - while (w--) { - white = whitelist[w]; - if (global[key] === white || 'string' === typeof white && key === white) { - bad = false; - break; - } - } - - if (bad) ret.push(key); - }); - - return ret; -}; - -/** - * Return only new leaks since the last time `detectNew` - * was run. - * @api public - */ - -Gleak.prototype.detectNew = function detectNew () { - var found = this.found || (this.found = []); - var ret = []; - - this.detect().forEach(function (leak) { - if (~found.indexOf(leak)) return; - found.push(leak); - ret.push(leak); - }); - - return ret; -} - -/** - * Prints all gleaks to stderr. - * @api public - */ - -Gleak.prototype.print = function print () { - var format = this.format; - this.detect().forEach(function (leak) { - console.error(format, leak); - }); -} - -/** - * Add items to the whitelist disallowing duplicates. - * @api public - */ - -Gleak.prototype.ignore = function ignore () { - var i = arguments.length; - while (i--) { - if (~this.whitelist.indexOf(arguments[i])) continue; - this.whitelist.push(arguments[i]); - } - return this; -} - diff --git a/node_modules/mongodb/deps/gleak/package.json b/node_modules/mongodb/deps/gleak/package.json deleted file mode 100644 index 374de40..0000000 --- a/node_modules/mongodb/deps/gleak/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "author": "Aaron Heckmann ", - "name": "gleak", - "description": "Node global variable leak detector", - "version": "0.2.1", - "repository": { - "type": "git" - , "url": "git://github.com/aheckmann/gleak.git" - }, - "main": "./index.js", - "scripts": { - "test": "make test" - }, - "engines": { - "node": ">=0.4.0" - }, - "dependencies": {}, - "devDependencies": { - "express": ">=2.0.0" - , "expresso": "0.7.5" - } -} diff --git a/node_modules/mongodb/deps/gleak/test/index.js b/node_modules/mongodb/deps/gleak/test/index.js deleted file mode 100644 index 9e0bdee..0000000 --- a/node_modules/mongodb/deps/gleak/test/index.js +++ /dev/null @@ -1,215 +0,0 @@ - -var assert = require('assert') -var express = require('express') -var gleak = require('../index') - -exports['version exists'] = function () { - assert.equal('string', typeof gleak.version); -} - -exports['middleware exists'] = function () { - assert.equal('function', typeof gleak.middleware); -} - -exports['gleak is a function'] = function () { - assert.equal('function', typeof gleak); -} - -exports['default format is correct'] = function () { - var g = gleak(); - assert.equal('\x1b[31mGleak!:\x1b[0m %s', g.format); -} - -exports['whitelist is an array'] = function () { - var g = gleak(); - assert.ok(Array.isArray(g.whitelist)); -} - -exports['setTimeout is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(setTimeout)); -}; - -exports['setInterval is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(setInterval)); -}; -exports['clearTimeout is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(clearTimeout)); -}; -exports['clearInterval is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(clearInterval)); -}; -exports['console is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(console)); -}; -exports['Buffer is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(Buffer)); -}; -exports['process is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(process)); -}; -exports['global is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(global)); -}; - -exports['whitelist is mutable'] = function () { - var g = gleak(); - var i = g.whitelist.push(assert); - assert.ok(~g.whitelist.indexOf(assert)); - g.whitelist.splice(i-1, 1); - assert.ok(!~g.whitelist.indexOf(assert)); -} - -exports['#detect is a function'] = function () { - var g = gleak(); - assert.ok('function' === typeof g.detect); -} - -exports['detect()'] = function () { - var g = gleak(); - var found = g.detect(); - assert.ok(Array.isArray(found)); - assert.ok(0 === found.length); - haha = "lol" - assert.ok(1 === g.detect().length); - assert.equal("haha", g.detect()[0]); -} - -exports['unknown values can be whitelisted by passing strings'] = function () { - var g = gleak(); - ignoreme = 1; - assert.ok(~g.detect().indexOf('ignoreme')); - g.whitelist.push('ignoreme'); - assert.ok(!~g.detect().indexOf('ignoreme')); - delete global.ignoreme; -} - -exports['#ignore'] = function () { - var g = gleak(); - assert.equal('function', typeof g.ignore); -} - -exports['ignore identical whitelisted values'] = function () { - var g = gleak(); - var len = g.whitelist.length; - var an = 'another'; - g.ignore('another', 'another', 'another', an); - assert.equal(len + 1, g.whitelist.length); -} - -exports['#print'] = function () { - var g = gleak(); - var write = console.error; - var times = 0; - haha = "heh"; - console.error = function (format, item) { - assert.equal(g.format, format); - assert.equal("haha", item); - ++times; - } - g.print(); - console.error = write; - assert.equal(1, times); -} - -exports['whitelists are seperate from other instances'] = function () { - var g1 = gleak() - , g2 = gleak(); - - g1.ignore('the', 'bad'); - assert.ok(~g1.whitelist.indexOf('the')); - assert.ok(!~g2.whitelist.indexOf('the')); -} - -exports['formats are seperate from other instances'] = function () { - var g1 = gleak() - , g2 = gleak(); - - g1.format = "different %s"; - assert.ok(~g1.format !== g1.format); -} - -exports['#detectNew'] = function () { - var g = gleak(); - assert.equal('function', typeof g.detectNew); - var found = g.detectNew(); - assert.equal(true, Array.isArray(found)); - assert.equal(found.length, 1); - assert.equal(g.detectNew().length, 0); - zombocom = 'welcome'; - found = g.detectNew(); - assert.equal(found.length, 1); - assert.equal(found[0], 'zombocom'); - assert.equal(g.detectNew().length, 0); - delete global.zombocom; -} - -exports['test middleware'] = function (beforeExit) { - var called = false; - var req = {}; - var res = { send: function (x) { assert.equal(x, 'yes'); called = true; }}; - var m = gleak.middleware(); - m(req, res, function(){}); - assert.equal(res._gleak, true); - res.send('yes'); - assert.equal(true, called); - - // another leak - meToo = 47; - - // mock stream - function makeStream (tests) { - return { - i: 0 - , write: function (data) { - assert.equal(tests[this.i], data); - ++this.i; - } - } - } - - var app = express.createServer(); - - var sout = [ - '\x1b[31mGleak!:\x1b[0m haha\n' - , '\x1b[31mGleak!:\x1b[0m meToo\n' - ]; - var stream1 = makeStream(sout); - - app.get('/stream', gleak.middleware(stream1), function (req, res, next) { - res.send('passed a stream'); - }); - - var both = [ - 'yes : haha\n' - , 'yes : meToo\n' - ]; - var stream2 = makeStream(both); - - app.get('/formatstream', gleak.middleware(stream2, 'yes : %s'), function (req, res, next) { - res.send('passed format and stream'); - }); - - assert.response(app, - { url: '/stream' } - , { status: 200 - , body: 'passed a stream' }) - - assert.response(app, - { url: '/formatstream' } - , { status: 200 - , body: 'passed format and stream' }) - - beforeExit(function () { - assert.equal(stream1.i, 2); - assert.equal(stream2.i, 2); - }); -} - diff --git a/node_modules/mongodb/deps/nodeunit/.npmignore b/node_modules/mongodb/deps/nodeunit/.npmignore deleted file mode 100644 index 1a82501..0000000 --- a/node_modules/mongodb/deps/nodeunit/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -dist -stamp-build -test/fixtures/dir2 diff --git a/node_modules/mongodb/deps/nodeunit/CONTRIBUTORS.md b/node_modules/mongodb/deps/nodeunit/CONTRIBUTORS.md deleted file mode 100644 index fba3609..0000000 --- a/node_modules/mongodb/deps/nodeunit/CONTRIBUTORS.md +++ /dev/null @@ -1,68 +0,0 @@ -Nodeunit contributors (sorted alphabeticaly) -============================================ - -* **[Alex Gorbatchev](https://github.com/alexgorbatchev)** - - * Deeper default object inspection - * Timeout to ensure flushing of console output (default reporter) - -* **[Alex Wolfe](https://github.com/alexkwolfe)** - - * HTML test reporter - -* **[Caolan McMahon](https://github.com/caolan)** - - * Author and maintainer - * Most features develpopment - -* **[Carl Fürstenberg](https://github.com/azatoth)** - - * Debian-friendly Makefile, supports both 'node' and 'nodejs' executables - * Sandbox utility - * Minimal test reporter - -* **[Gerad Suyderhoud](https://github.com/gerad)** - - * First comand-line tool - -* **[Kadir Pekel](https://github.com/kadirpekel)** - - * Improvements to default test reporter - * HTTP test utility - -* **[Λlisue](https://github.com/lambdalisue)** - - * Add machineout reporter - -* **[Matthias Lübken](https://github.com/luebken)** - - * Utility functions for tracking incomplete tests on exit - -* **[Oleg Efimov](https://github.com/Sannis)** - - * Adding 'make lint' and fixing nodelint errors - * Option parsing, --help text and config file support - * Reporters option for command-line tool - -* **[Orlando Vazquez](https://github.com/orlandov)** - - * Added jUnit XML reporter - -* **[Ryan Dahl](https://github.com/ry)** - - * Add package.json - -* **[Sam Stephenson](https://github.com/sstephenson)** - - * Coffee-script support - -* **[Thomas Mayfield](https://github.com/thegreatape)** - - * Async setUp and tearDown support for testCase - -* **[Maciej Małecki](https://github.com/mmalecki)** - - * Removal of `testCase` - -**[Full contributors list](https://github.com/caolan/nodeunit/contributors).** - diff --git a/node_modules/mongodb/deps/nodeunit/LICENSE b/node_modules/mongodb/deps/nodeunit/LICENSE deleted file mode 100644 index b7f9d50..0000000 --- a/node_modules/mongodb/deps/nodeunit/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Caolan McMahon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/mongodb/deps/nodeunit/Makefile b/node_modules/mongodb/deps/nodeunit/Makefile deleted file mode 100644 index 31fdb0e..0000000 --- a/node_modules/mongodb/deps/nodeunit/Makefile +++ /dev/null @@ -1,176 +0,0 @@ -PACKAGE = nodeunit -NODEJS = $(if $(shell test -f /usr/bin/nodejs && echo "true"),nodejs,node) - -PREFIX ?= /usr/local -BINDIR ?= $(PREFIX)/bin -DATADIR ?= $(PREFIX)/share -MANDIR ?= $(PREFIX)/share/man -LIBDIR ?= $(PREFIX)/lib -NODEJSLIBDIR ?= $(LIBDIR)/$(NODEJS) - -BUILDDIR = dist - -DOCS = $(shell find doc -name '*.md' \ - |sed 's|.md|.1|g' \ - |sed 's|doc/|man1/|g' \ - ) - - -$(shell if [ ! -d $(BUILDDIR) ]; then mkdir $(BUILDDIR); fi) - -all: build doc - -browser: - # super hacky build script for browser version! - mkdir -p $(BUILDDIR)/browser - rm -rf $(BUILDDIR)/browser/* - # build browser version of nodeunit.js - cat share/license.js >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit = (function(){" >> $(BUILDDIR)/browser/nodeunit.js - cat deps/json2.js >> $(BUILDDIR)/browser/nodeunit.js - # make assert global - echo "var assert = this.assert = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var types = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var core = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var nodeunit = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var reporter = {};" >> $(BUILDDIR)/browser/nodeunit.js - cat deps/async.js >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/assert.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(assert);" >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/types.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(types);" >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/core.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(core);" >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/reporters/browser.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(reporter);" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit = core;" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit.assert = assert;" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit.reporter = reporter;" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit.run = reporter.run;" >> $(BUILDDIR)/browser/nodeunit.js - echo "return nodeunit; })();" >> $(BUILDDIR)/browser/nodeunit.js - cp $(BUILDDIR)/browser/nodeunit.js $(BUILDDIR)/browser/.nodeunit.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.nodeunit.js > $(BUILDDIR)/browser/nodeunit.js - rm $(BUILDDIR)/browser/.nodeunit.js - # copy nodeunit.css - cp share/nodeunit.css $(BUILDDIR)/browser/nodeunit.css - # create nodeunit.min.js - node_modules/uglify-js/bin/uglifyjs $(BUILDDIR)/browser/nodeunit.js > $(BUILDDIR)/browser/nodeunit.min.js - # create test scripts - mkdir -p $(BUILDDIR)/browser/test - cp test/test.html $(BUILDDIR)/browser/test/test.html - # test-base.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-base.js - cat test/test-base.js >> $(BUILDDIR)/browser/test/test-base.js - echo "})(this.test_base = {});" >> $(BUILDDIR)/browser/test/test-base.js - cp $(BUILDDIR)/browser/test/test-base.js $(BUILDDIR)/browser/.test-base.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-base.js > $(BUILDDIR)/browser/test/test-base.js - rm $(BUILDDIR)/browser/.test-base.js - # test-runmodule.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-runmodule.js - cat test/test-runmodule.js >> $(BUILDDIR)/browser/test/test-runmodule.js - echo "})(this.test_runmodule = {});" >> $(BUILDDIR)/browser/test/test-runmodule.js - cp $(BUILDDIR)/browser/test/test-runmodule.js $(BUILDDIR)/browser/.test-runmodule.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-runmodule.js > $(BUILDDIR)/browser/test/test-runmodule.js - rm $(BUILDDIR)/browser/.test-runmodule.js - # test-runtest.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-runtest.js - cat test/test-runtest.js >> $(BUILDDIR)/browser/test/test-runtest.js - echo "})(this.test_runtest = {});" >> $(BUILDDIR)/browser/test/test-runtest.js - cp $(BUILDDIR)/browser/test/test-runtest.js $(BUILDDIR)/browser/.test-runtest.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-runtest.js > $(BUILDDIR)/browser/test/test-runtest.js - rm $(BUILDDIR)/browser/.test-runtest.js - # test-testcase.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-testcase.js - cat test/test-testcase.js >> $(BUILDDIR)/browser/test/test-testcase.js - echo "})(this.test_testcase = {});" >> $(BUILDDIR)/browser/test/test-testcase.js - cp $(BUILDDIR)/browser/test/test-testcase.js $(BUILDDIR)/browser/.test-testcase.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-testcase.js > $(BUILDDIR)/browser/test/test-testcase.js - rm $(BUILDDIR)/browser/.test-testcase.js - # test-testcase-legacy.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-testcase-legacy.js - cat test/test-testcase-legacy.js >> $(BUILDDIR)/browser/test/test-testcase-legacy.js - echo "})(this.test_testcase_legacy = {});" >> $(BUILDDIR)/browser/test/test-testcase-legacy.js - cp $(BUILDDIR)/browser/test/test-testcase-legacy.js $(BUILDDIR)/browser/.test-testcase-legacy.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-testcase-legacy.js > $(BUILDDIR)/browser/test/test-testcase-legacy.js - rm $(BUILDDIR)/browser/.test-testcase-legacy.js - # copy nodeunit.js to dist/browser/test to make it easier for me to host and - # run on windows VMs with IE - cp $(BUILDDIR)/browser/nodeunit.js $(BUILDDIR)/browser/test/nodeunit.js - cp $(BUILDDIR)/browser/nodeunit.css $(BUILDDIR)/browser/test/nodeunit.css - -commonjs: - # super hacky build script for browser commonjs version! - ##### make commonjs browser module ###### - mkdir -p $(BUILDDIR)/commonjs - mkdir -p $(BUILDDIR)/commonjs/deps - cp deps/json2.js $(BUILDDIR)/commonjs/deps - cp deps/async.js $(BUILDDIR)/commonjs/deps - echo "var async = require('async');" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var assert = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var types = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var core = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var nodeunit = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var reporter = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/assert.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(assert);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/types.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(types);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/core.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(core);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports = core;" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports, nodeunit){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/reporters/browser.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(reporter, module.exports);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports.assert = assert;" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports.reporter = reporter;" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports.run = reporter.run;" >> $(BUILDDIR)/commonjs/nodeunit.js - sed -i "/\@REMOVE_LINE_FOR_BROWSER/d" $(BUILDDIR)/commonjs/nodeunit.js - sed -i "/\@REMOVE_LINE_FOR_COMMONJS/d" $(BUILDDIR)/commonjs/nodeunit.js - ##### end of commonjs browser module ##### - -build: stamp-build - -stamp-build: $(wildcard deps/* lib/*.js) - touch $@; - mkdir -p $(BUILDDIR)/nodeunit - cp -R bin node_modules deps index.js lib package.json share $(BUILDDIR)/nodeunit - printf '#!/bin/sh\n$(NODEJS) $(NODEJSLIBDIR)/$(PACKAGE)/bin/nodeunit $$@' > $(BUILDDIR)/nodeunit.sh - -test: - $(NODEJS) ./bin/nodeunit test - -install: build - install -d $(NODEJSLIBDIR) - cp -a $(BUILDDIR)/nodeunit $(NODEJSLIBDIR) - install -m 0755 $(BUILDDIR)/nodeunit.sh $(BINDIR)/nodeunit - install -d $(MANDIR)/man1/ - cp -a man1/nodeunit.1 $(MANDIR)/man1/ - -uninstall: - rm -rf $(NODEJSLIBDIR)/nodeunit $(NODEJSLIBDIR)/nodeunit.js $(BINDIR)/nodeunit - rm -rf $(MANDIR)/man1/nodeunit.1 - -clean: - rm -rf $(BUILDDIR) stamp-build - -lint: - nodelint --config nodelint.cfg ./index.js ./bin/nodeunit ./bin/nodeunit.json ./lib/*.js ./lib/reporters/*.js ./test/*.js - -doc: man1 $(DOCS) - @true - -man1: - @if ! test -d man1 ; then mkdir -p man1 ; fi - -# use `npm install ronn` for this to work. -man1/%.1: doc/%.md - ronn --roff $< > $@ - -.PHONY: browser test install uninstall build all diff --git a/node_modules/mongodb/deps/nodeunit/README.md b/node_modules/mongodb/deps/nodeunit/README.md deleted file mode 100644 index 359a9c7..0000000 --- a/node_modules/mongodb/deps/nodeunit/README.md +++ /dev/null @@ -1,443 +0,0 @@ -Nodeunit -======== - -Simple syntax, powerful tools. Nodeunit provides easy async unit testing for -node.js and the browser. - -* Simple to use -* Just export the tests from a module -* Works with node.js and in the browser. -* Helps you avoid common pitfalls when testing asynchronous code -* Easy to add test cases with setUp and tearDown functions if you wish -* Flexible reporters for custom output, built-in support for HTML and jUnit XML -* Allows the use of mocks and stubs - -__Contributors__ - -* [alexgorbatchev](https://github.com/alexgorbatchev) -* [alexkwolfe](https://github.com/alexkwolfe) -* [azatoth](https://github.com/azatoth) -* [kadirpekel](https://github.com/kadirpekel) -* [lambdalisue](https://github.com/lambdalisue) -* [luebken](https://github.com/luebken) -* [orlandov](https://github.com/orlandov) -* [Sannis](https://github.com/Sannis) -* [sstephenson](https://github.com/sstephenson) -* [thegreatape](https://github.com/thegreatape) -* [mmalecki](https://github.com/mmalecki) -* and thanks to [cjohansen](https://github.com/cjohansen) for input and advice - on implementing setUp and tearDown functions. See - [cjohansen's fork](https://github.com/cjohansen/nodeunit). - -Also, check out gerad's [nodeunit-dsl](https://github.com/gerad/nodeunit-dsl) -project, which implements a 'pretty dsl on top of nodeunit'. - -More contributor information can be found in the -[CONTRIBUTORS.md](https://github.com/caolan/nodeunit/blob/master/CONTRIBUTORS.md) -file. - -Usage ------ - -Here is an example unit test module: - - exports.testSomething = function(test){ - test.expect(1); - test.ok(true, "this assertion should pass"); - test.done(); - }; - - exports.testSomethingElse = function(test){ - test.ok(false, "this assertion should fail"); - test.done(); - }; - -When run using the included test runner, this will output the following: - - - -Installation ------------- - -There are two options for installing nodeunit: - -1. Clone / download nodeunit from [github](https://github.com/caolan/nodeunit), - then: - - make && sudo make install - -2. Install via npm: - - npm install nodeunit - -API Documentation ------------------ - -Nodeunit uses the functions available in the node.js -[assert module](http://nodejs.org/docs/v0.4.2/api/assert.html): - -* __ok(value, [message])__ - Tests if value is a true value. -* __equal(actual, expected, [message])__ - Tests shallow, coercive equality - with the equal comparison operator ( == ). -* __notEqual(actual, expected, [message])__ - Tests shallow, coercive - non-equality with the not equal comparison operator ( != ). -* __deepEqual(actual, expected, [message])__ - Tests for deep equality. -* __notDeepEqual(actual, expected, [message])__ - Tests for any deep - inequality. -* __strictEqual(actual, expected, [message])__ - Tests strict equality, as - determined by the strict equality operator ( === ) -* __notStrictEqual(actual, expected, [message])__ - Tests strict non-equality, - as determined by the strict not equal operator ( !== ) -* __throws(block, [error], [message])__ - Expects block to throw an error. -* __doesNotThrow(block, [error], [message])__ - Expects block not to throw an - error. -* __ifError(value)__ - Tests if value is not a false value, throws if it is a - true value. Useful when testing the first argument, error in callbacks. - -Nodeunit also provides the following functions within tests: - -* __expect(amount)__ - Specify how many assertions are expected to run within a - test. Very useful for ensuring that all your callbacks and assertions are - run. -* __done()__ - Finish the current test function, and move on to the next. ALL - tests should call this! - -Nodeunit aims to be simple and easy to learn. This is achieved through using -existing structures (such as node.js modules) to maximum effect, and reducing -the API where possible, to make it easier to digest. - -Tests are simply exported from a module, but they are still run in the order -they are defined. - -__Note:__ Users of old nodeunit versions may remember using ok, equals and same -in the style of qunit, instead of the assert functions above. These functions -still exist for backwards compatibility, and are simply aliases to their assert -module counterparts. - - -Asynchronous Testing --------------------- - -When testing asynchronous code, there are a number of sharp edges to watch out -for. Thankfully, nodeunit is designed to help you avoid as many of these -pitfalls as possible. For the most part, testing asynchronous code in nodeunit -_just works_. - - -### Tests run in series - -While running tests in parallel seems like a good idea for speeding up your -test suite, in practice I've found it means writing much more complicated -tests. Because of node's module cache, running tests in parallel means mocking -and stubbing is pretty much impossible. One of the nicest things about testing -in javascript is the ease of doing stubs: - - var _readFile = fs.readFile; - fs.readFile = function(path, callback){ - // its a stub! - }; - // test function that uses fs.readFile - - // we're done - fs.readFile = _readFile; - -You cannot do this when running tests in parallel. In order to keep testing as -simple as possible, nodeunit avoids it. Thankfully, most unit-test suites run -fast anyway. - - -### Explicit ending of tests - -When testing async code its important that tests end at the correct point, not -just after a given number of assertions. Otherwise your tests can run short, -ending before all assertions have completed. Its important to detect too -many assertions as well as too few. Combining explicit ending of tests with -an expected number of assertions helps to avoid false test passes, so be sure -to use the test.expect() method at the start of your test functions, and -test.done() when finished. - - -Groups, setUp and tearDown --------------------------- - -Nodeunit allows the nesting of test functions: - - exports.test1 = function (test) { - ... - } - - exports.group = { - test2: function (test) { - ... - }, - test3: function (test) { - ... - } - } - -This would be run as: - - test1 - group - test2 - group - test3 - -Using these groups, Nodeunit allows you to define a `setUp` function, which is -run before each test, and a `tearDown` function, which is run after each test -calls `test.done()`: - - module.exports = { - setUp: function (callback) { - this.foo = 'bar'; - callback(); - }, - tearDown: function (callback) { - // clean up - callback(); - }, - test1: function (test) { - test.equals(this.foo, 'bar'); - test.done(); - } - }; - -In this way, its possible to have multiple groups of tests in a module, each -group with its own setUp and tearDown functions. - - -Running Tests -------------- - -Nodeunit comes with a basic command-line test runner, which can be installed -using 'sudo make install'. Example usage: - - nodeunit testmodule1.js testfolder [...] - -The default test reporter uses color output, because I think that's more fun :) I -intend to add a no-color option in future. To give you a feeling of the fun you'll -be having writing tests, lets fix the example at the start of the README: - - - -Ahhh, Doesn't that feel better? - -When using the included test runner, it will exit using the failed number of -assertions as the exit code. Exiting with 0 when all tests pass. - - -### Command-line Options - -* __--reporter FILE__ - you can set the test reporter to a custom module or -on of the modules in nodeunit/lib/reporters, when omitted, the default test runner -is used. -* __--list-reporters__ - list available build-in reporters. -* __--config FILE__ - load config options from a JSON file, allows -the customisation of color schemes for the default test reporter etc. See -bin/nodeunit.json for current available options. -* __--version__ or __-v__ - report nodeunit version -* __--help__ - show nodeunit help - - -Running tests in the browser ----------------------------- - -Nodeunit tests can also be run inside the browser. For example usage, see -the examples/browser folder. The basic syntax is as follows: - -__test.html__ - - - - Example Test Suite - - - - - - -

- - -nodeunit with vim -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -There is [nodeunit.vim](https://github.com/lambdalisue/nodeunit.vim) so you can use nodeunit with VIM. -That compiler use __machineout__ reporter and it is useful to use with [vim-makegreen](https://github.com/reinh/vim-makegreen) - - - -Contributing ------------- - -Contributions to the project are most welcome, so feel free to fork and improve. -When submitting a pull request, please run 'make lint' first to ensure -we're following a consistent coding style. diff --git a/node_modules/mongodb/deps/nodeunit/bin/nodeunit b/node_modules/mongodb/deps/nodeunit/bin/nodeunit deleted file mode 100644 index b11cfb1..0000000 --- a/node_modules/mongodb/deps/nodeunit/bin/nodeunit +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env node - -var - fs = require('fs'), - path = require('path'); - -// TODO: remove this when https://github.com/joyent/node/pull/1312 -// lands in core. -// -// Until then, use console.log from npm (https://gist.github.com/1077544) -require('../deps/console.log'); - -//require.paths.push(process.cwd()); -var args = (process.ARGV || process.argv).slice(2); - -var files = []; - -var testrunner, - config_file, - config_param_found = false, - output_param_found = false, - reporter_file = 'default', - reporter_param_found = false, - testspec_param_found = false; - -var usage = "Usage: nodeunit [options] testmodule1.js testfolder [...] \n" + - "Options:\n\n" + - " --config FILE the path to a JSON file with options\n" + - " --reporter FILE optional path to a reporter file to customize the output\n" + - " --list-reporters list available build-in reporters\n" + - " -t name, specify a test to run\n" + - " -h, --help display this help and exit\n" + - " -v, --version output version information and exit"; - - -// load default options -var content = fs.readFileSync(__dirname + '/nodeunit.json', 'utf8'); -var options = JSON.parse(content); - -// a very basic pseudo --options parser -args.forEach(function (arg) { - if (arg.slice(0, 9) === "--config=") { - config_file = arg.slice(9); - } else if (arg === '--config') { - config_param_found = true; - } else if (config_param_found) { - config_file = arg; - config_param_found = false; - } else if (arg.slice(0, 9) === "--output=") { - options.output = arg.slice(9); - } else if (arg === '--output') { - output_param_found = true; - } else if (output_param_found) { - options.output = arg; - output_param_found = false; - } else if (arg.slice(0, 11) === "--reporter=") { - reporter_file = arg.slice(11); - } else if (arg === '--reporter') { - reporter_param_found = true; - } else if (reporter_param_found) { - reporter_file = arg; - reporter_param_found = false; - } else if (arg === '-t') { - testspec_param_found = true; - } else if (testspec_param_found) { - options.testspec = arg; - testspec_param_found = false; - } else if (arg === '--list-reporters') { - var reporters = fs.readdirSync(__dirname + '/../lib/reporters'); - reporters = reporters.filter(function (reporter_file) { - return (/\.js$/).test(reporter_file); - }).map(function (reporter_file) { - return reporter_file.replace(/\.js$/, ''); - }).filter(function (reporter_file) { - return reporter_file !== 'index'; - }); - console.log('Build-in reporters: '); - reporters.forEach(function (reporter_file) { - var reporter = require('../lib/reporters/' + reporter_file); - console.log(' * ' + reporter_file + (reporter.info ? ': ' + reporter.info : '')); - }); - process.exit(0); - } else if ((arg === '-v') || (arg === '--version')) { - var content = fs.readFileSync(__dirname + '/../package.json', 'utf8'); - var pkg = JSON.parse(content); - console.log(pkg.version); - process.exit(0); - } else if ((arg === '-h') || (arg === '--help')) { - console.log(usage); - process.exit(0); - } else { - files.push(arg); - } -}); - -if (files.length === 0) { - console.log('Files required.'); - console.log(usage); - process.exit(1); -} - -if (config_file) { - content = fs.readFileSync(config_file, 'utf8'); - var custom_options = JSON.parse(content); - - for (var option in custom_options) { - if (typeof option === 'string') { - options[option] = custom_options[option]; - } - } -} - -var builtin_reporters = require(__dirname + '/../lib/reporters'); -if (reporter_file in builtin_reporters) { - testrunner = builtin_reporters[reporter_file]; -} -else { - testrunner = require(reporter_file); -} - -testrunner.run(files, options, function(err) { - if (err) { - process.exit(1); - } -}); diff --git a/node_modules/mongodb/deps/nodeunit/bin/nodeunit.json b/node_modules/mongodb/deps/nodeunit/bin/nodeunit.json deleted file mode 100644 index 5c7778f..0000000 --- a/node_modules/mongodb/deps/nodeunit/bin/nodeunit.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "error_prefix": "\u001B[31m", - "error_suffix": "\u001B[39m", - "ok_prefix": "\u001B[32m", - "ok_suffix": "\u001B[39m", - "bold_prefix": "\u001B[1m", - "bold_suffix": "\u001B[22m", - "assertion_prefix": "\u001B[35m", - "assertion_suffix": "\u001B[39m" -} diff --git a/node_modules/mongodb/deps/nodeunit/deps/async.js b/node_modules/mongodb/deps/nodeunit/deps/async.js deleted file mode 100644 index d81255f..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/async.js +++ /dev/null @@ -1,623 +0,0 @@ -/*global setTimeout: false, console: false */ -(function () { - - var async = {}; - - // global on the server, window in the browser - var root = this, - previous_async = root.async; - - if (typeof module !== 'undefined' && module.exports) { - module.exports = async; - } - else { - root.async = async; - } - - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - //// cross-browser compatiblity functions //// - - var _forEach = function (arr, iterator) { - if (arr.forEach) { - return arr.forEach(iterator); - } - for (var i = 0; i < arr.length; i += 1) { - iterator(arr[i], i, arr); - } - }; - - var _map = function (arr, iterator) { - if (arr.map) { - return arr.map(iterator); - } - var results = []; - _forEach(arr, function (x, i, a) { - results.push(iterator(x, i, a)); - }); - return results; - }; - - var _reduce = function (arr, iterator, memo) { - if (arr.reduce) { - return arr.reduce(iterator, memo); - } - _forEach(arr, function (x, i, a) { - memo = iterator(memo, x, i, a); - }); - return memo; - }; - - var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; - }; - - var _indexOf = function (arr, item) { - if (arr.indexOf) { - return arr.indexOf(item); - } - for (var i = 0; i < arr.length; i += 1) { - if (arr[i] === item) { - return i; - } - } - return -1; - }; - - //// exported async module functions //// - - //// nextTick implementation with browser-compatible fallback //// - if (typeof process === 'undefined' || !(process.nextTick)) { - async.nextTick = function (fn) { - setTimeout(fn, 0); - }; - } - else { - async.nextTick = process.nextTick; - } - - async.forEach = function (arr, iterator, callback) { - if (!arr.length) { - return callback(); - } - var completed = 0; - _forEach(arr, function (x) { - iterator(x, function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed === arr.length) { - callback(); - } - } - }); - }); - }; - - async.forEachSeries = function (arr, iterator, callback) { - if (!arr.length) { - return callback(); - } - var completed = 0; - var iterate = function () { - iterator(arr[completed], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed === arr.length) { - callback(); - } - else { - iterate(); - } - } - }); - }; - iterate(); - }; - - - var doParallel = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.forEach].concat(args)); - }; - }; - var doSeries = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.forEachSeries].concat(args)); - }; - }; - - - var _asyncMap = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (err, v) { - results[x.index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - }; - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_asyncMap); - - - // reduce only has a series version, as doing reduce in parallel won't - // work in many situations. - async.reduce = function (arr, memo, iterator, callback) { - async.forEachSeries(arr, function (x, callback) { - iterator(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); - }; - // inject alias - async.inject = async.reduce; - // foldl alias - async.foldl = async.reduce; - - async.reduceRight = function (arr, memo, iterator, callback) { - var reversed = _map(arr, function (x) { - return x; - }).reverse(); - async.reduce(reversed, memo, iterator, callback); - }; - // foldr alias - async.foldr = async.reduceRight; - - var _filter = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.filter = doParallel(_filter); - async.filterSeries = doSeries(_filter); - // select alias - async.select = async.filter; - async.selectSeries = async.filterSeries; - - var _reject = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (!v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.reject = doParallel(_reject); - async.rejectSeries = doSeries(_reject); - - var _detect = function (eachfn, arr, iterator, main_callback) { - eachfn(arr, function (x, callback) { - iterator(x, function (result) { - if (result) { - main_callback(x); - } - else { - callback(); - } - }); - }, function (err) { - main_callback(); - }); - }; - async.detect = doParallel(_detect); - async.detectSeries = doSeries(_detect); - - async.some = function (arr, iterator, main_callback) { - async.forEach(arr, function (x, callback) { - iterator(x, function (v) { - if (v) { - main_callback(true); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(false); - }); - }; - // any alias - async.any = async.some; - - async.every = function (arr, iterator, main_callback) { - async.forEach(arr, function (x, callback) { - iterator(x, function (v) { - if (!v) { - main_callback(false); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(true); - }); - }; - // all alias - async.all = async.every; - - async.sortBy = function (arr, iterator, callback) { - async.map(arr, function (x, callback) { - iterator(x, function (err, criteria) { - if (err) { - callback(err); - } - else { - callback(null, {value: x, criteria: criteria}); - } - }); - }, function (err, results) { - if (err) { - return callback(err); - } - else { - var fn = function (left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - if (!keys.length) { - return callback(null); - } - - var completed = []; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - _forEach(listeners, function (fn) { - fn(); - }); - }; - - addListener(function () { - if (completed.length === keys.length) { - callback(null); - } - }); - - _forEach(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - if (err) { - callback(err); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - completed.push(k); - taskComplete(); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && _indexOf(completed, x) !== -1); - }, true); - }; - if (ready()) { - task[task.length - 1](taskCallback); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - if (!tasks.length) { - return callback(); - } - callback = callback || function () {}; - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.nextTick(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - async.parallel = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args || null); - }); - } - }, callback); - } - else { - var results = {}; - async.forEach(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args || null); - }); - } - }, callback); - } - else { - var results = {}; - async.forEachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.queue = function (worker, concurrency) { - var workers = 0; - var tasks = []; - var q = { - concurrency: concurrency, - push: function (data, callback) { - tasks.push({data: data, callback: callback}); - async.nextTick(q.process); - }, - process: function () { - if (workers < q.concurrency && tasks.length) { - var task = tasks.splice(0, 1)[0]; - workers += 1; - worker(task.data, function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - q.process(); - }); - } - }, - length: function () { - return tasks.length; - } - }; - return q; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _forEach(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - - async.memoize = function (fn, hasher) { - var memo = {}; - hasher = hasher || function (x) { - return x; - }; - return function () { - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - var key = hasher.apply(null, args); - if (key in memo) { - callback.apply(null, memo[key]); - } - else { - fn.apply(null, args.concat([function () { - memo[key] = arguments; - callback.apply(null, arguments); - }])); - } - }; - }; - -}()); diff --git a/node_modules/mongodb/deps/nodeunit/deps/console.log.js b/node_modules/mongodb/deps/nodeunit/deps/console.log.js deleted file mode 100644 index fe146c1..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/console.log.js +++ /dev/null @@ -1,55 +0,0 @@ -/* - A console.log that won't leave you hanging when node exits - 90% of this file was ripped from node.js - - License: see: https://github.com/joyent/node/blob/master/lib/console.js - */ - - // console object -var formatRegExp = /%[sdj]/g; -function format(f) { - var util = require('util'); - - if (typeof f !== 'string') { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(util.inspect(arguments[i])); - } - return objects.join(' '); - } - - - var i = 1; - var args = arguments; - var str = String(f).replace(formatRegExp, function(x) { - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': return JSON.stringify(args[i++]); - default: - return x; - } - }); - for (var len = args.length, x = args[i]; i < len; x = args[++i]) { - if (x === null || typeof x !== 'object') { - str += ' ' + x; - } else { - str += ' ' + util.inspect(x); - } - } - return str; -} - -console.log = function() { - var res = process.stdout.write(format.apply(this, arguments) + '\n'); - - // this is the first time stdout got backed up - if (!res && !process.stdout.pendingWrite) { - process.stdout.pendingWrite = true; - - // magic sauce: keep node alive until stdout has flushed - process.stdout.once('drain', function () { - process.stdout.draining = false; - }); - } -}; diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/History.md b/node_modules/mongodb/deps/nodeunit/deps/ejs/History.md deleted file mode 100644 index 00d2b5b..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/History.md +++ /dev/null @@ -1,70 +0,0 @@ - -0.4.3 / 2011-06-20 -================== - - * Fixed stacktraces line number when used multiline js expressions [Octave] - -0.4.2 / 2011-05-11 -================== - - * Added client side support - -0.4.1 / 2011-04-21 -================== - - * Fixed error context - -0.4.0 / 2011-04-21 -================== - - * Added; ported jade's error reporting to ejs. [slaskis] - -0.3.1 / 2011-02-23 -================== - - * Fixed optional `compile()` options - -0.3.0 / 2011-02-14 -================== - - * Added 'json' filter [Yuriy Bogdanov] - * Use exported version of parse function to allow monkey-patching [Anatoliy Chakkaev] - -0.2.1 / 2010-10-07 -================== - - * Added filter support - * Fixed _cache_ option. ~4x performance increase - -0.2.0 / 2010-08-05 -================== - - * Added support for global tag config - * Added custom tag support. Closes #5 - * Fixed whitespace bug. Closes #4 - -0.1.0 / 2010-08-04 -================== - - * Faster implementation [ashleydev] - -0.0.4 / 2010-08-02 -================== - - * Fixed single quotes for content outside of template tags. [aniero] - * Changed; `exports.compile()` now expects only "locals" - -0.0.3 / 2010-07-15 -================== - - * Fixed single quotes - -0.0.2 / 2010-07-09 -================== - - * Fixed newline preservation - -0.0.1 / 2010-07-09 -================== - - * Initial release diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/Makefile b/node_modules/mongodb/deps/nodeunit/deps/ejs/Makefile deleted file mode 100644 index a8b00d9..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ - -SRC = $(shell find lib -name "*.js" -type f) -UGLIFY_FLAGS = --no-mangle - -test: - @./node_modules/.bin/expresso test/*.test.js - -ejs.js: $(SRC) - @node support/compile.js $^ - -ejs.min.js: ejs.js - @uglifyjs $(UGLIFY_FLAGS) $< > $@ \ - && du ejs.min.js \ - && du ejs.js - -clean: - rm -f ejs.js - rm -f ejs.min.js - -.PHONY: test \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/Readme.md b/node_modules/mongodb/deps/nodeunit/deps/ejs/Readme.md deleted file mode 100644 index 58cb10a..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/Readme.md +++ /dev/null @@ -1,152 +0,0 @@ - -# EJS - -Embedded JavaScript templates. - -## Installation - - $ npm install ejs - -## Features - - * Complies with the [Express](http://expressjs.com) view system - * Static caching of intermediate JavaScript - * Unbuffered code for conditionals etc `<% code %>` - * Escapes html by default with `<%= code %>` - * Unescaped buffering with `<%- code %>` - * Supports tag customization - * Filter support for designer-friendly templates - * Client-side support - -## Example - - <% if (user) { %> -

<%= user.name %>

- <% } %> - -## Usage - - ejs.compile(str, options); - // => Function - - ejs.render(str, options); - // => str - -## Options - - - `locals` Local variables object - - `cache` Compiled functions are cached, requires `filename` - - `filename` Used by `cache` to key caches - - `scope` Function execution context - - `debug` Output generated function body - - `open` Open tag, defaulting to "<%" - - `close` Closing tag, defaulting to "%>" - -## Custom tags - -Custom tags can also be applied globally: - - var ejs = require('ejs'); - ejs.open = '{{'; - ejs.close = '}}'; - -Which would make the following a valid template: - -

{{= title }}

- -## Filters - -EJS conditionally supports the concept of "filters". A "filter chain" -is a designer friendly api for manipulating data, without writing JavaScript. - -Filters can be applied by supplying the _:_ modifier, so for example if we wish to take the array `[{ name: 'tj' }, { name: 'mape' }, { name: 'guillermo' }]` and output a list of names we can do this simply with filters: - -Template: - -

<%=: users | map:'name' | join %>

- -Output: - -

Tj, Mape, Guillermo

- -Render call: - - ejs.render(str, { - locals: { - users: [ - { name: 'tj' }, - { name: 'mape' }, - { name: 'guillermo' } - ] - } - }); - -Or perhaps capitalize the first user's name for display: - -

<%=: users | first | capitalize %>

- -## Filter list - -Currently these filters are available: - - - first - - last - - capitalize - - downcase - - upcase - - sort - - sort_by:'prop' - - size - - length - - plus:n - - minus:n - - times:n - - divided_by:n - - join:'val' - - truncate:n - - truncate_words:n - - replace:pattern,substitution - - prepend:val - - append:val - - map:'prop' - - reverse - - get:'prop' - -## Adding filters - - To add a filter simply add a method to the `.filters` object: - -```js -ejs.filters.last = function(obj) { - return obj[obj.length - 1]; -}; -``` - -## client-side support - - include `./ejs.js` or `./ejs.min.js` and `require("ejs").compile(str)`. - -## License - -(The MIT License) - -Copyright (c) 2009-2010 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/benchmark.js b/node_modules/mongodb/deps/nodeunit/deps/ejs/benchmark.js deleted file mode 100644 index 7b267e1..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/benchmark.js +++ /dev/null @@ -1,14 +0,0 @@ - - -var ejs = require('./lib/ejs'), - str = '<% if (foo) { %>

<%= foo %>

<% } %>', - times = 50000; - -console.log('rendering ' + times + ' times'); - -var start = new Date; -while (times--) { - ejs.render(str, { cache: true, filename: 'test', locals: { foo: 'bar' }}); -} - -console.log('took ' + (new Date - start) + 'ms'); \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.js b/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.js deleted file mode 100644 index b8c6aa1..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.js +++ /dev/null @@ -1,531 +0,0 @@ - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p[0]) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("ejs.js", function(module, exports, require){ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./utils'); - -/** - * Library version. - */ - -exports.version = '0.4.2'; - -/** - * Filters. - * - * @type Object - */ - -var filters = exports.filters = require('./filters'); - -/** - * Intermediate js cache. - * - * @type Object - */ - -var cache = {}; - -/** - * Clear intermediate js cache. - * - * @api public - */ - -exports.clearCache = function(){ - cache = {}; -}; - -/** - * Translate filtered code into function calls. - * - * @param {String} js - * @return {String} - * @api private - */ - -function filtered(js) { - return js.substr(1).split('|').reduce(function(js, filter){ - var parts = filter.split(':') - , name = parts.shift() - , args = parts.shift() || ''; - if (args) args = ', ' + args; - return 'filters.' + name + '(' + js + args + ')'; - }); -}; - -/** - * Re-throw the given `err` in context to the - * `str` of ejs, `filename`, and `lineno`. - * - * @param {Error} err - * @param {String} str - * @param {String} filename - * @param {String} lineno - * @api private - */ - -function rethrow(err, str, filename, lineno){ - var lines = str.split('\n') - , start = Math.max(lineno - 3, 0) - , end = Math.min(lines.length, lineno + 3); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' >> ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'ejs') + ':' - + lineno + '\n' - + context + '\n\n' - + err.message; - - throw err; -} - -/** - * Parse the given `str` of ejs, returning the function body. - * - * @param {String} str - * @return {String} - * @api public - */ - -var parse = exports.parse = function(str, options){ - var options = options || {} - , open = options.open || exports.open || '<%' - , close = options.close || exports.close || '%>'; - - var buf = [ - "var buf = [];" - , "\nwith (locals) {" - , "\n buf.push('" - ]; - - var lineno = 1; - - for (var i = 0, len = str.length; i < len; ++i) { - if (str.slice(i, open.length + i) == open) { - i += open.length - - var prefix, postfix, line = '__stack.lineno=' + lineno; - switch (str[i]) { - case '=': - prefix = "', escape((" + line + ', '; - postfix = ")), '"; - ++i; - break; - case '-': - prefix = "', (" + line + ', '; - postfix = "), '"; - ++i; - break; - default: - prefix = "');" + line + ';'; - postfix = "; buf.push('"; - } - - var start = i; - var end = str.indexOf(close, i); - var js = str.substring(i, end); - var n = 0; - while ((n = js.indexOf("\n", n)) > -1) { - n++; - lineno++; - } - if (js[0] == ':') js = filtered(js); - buf.push(prefix, js, postfix); - i += end - start + close.length - 1; - - } else if (str[i] == "\\") { - buf.push("\\\\"); - } else if (str[i] == "'") { - buf.push("\\'"); - } else if (str[i] == "\r") { - buf.push(" "); - } else if (str[i] == "\n") { - buf.push("\\n"); - lineno++; - } else { - buf.push(str[i]); - } - } - - buf.push("');\n}\nreturn buf.join('');"); - return buf.join(''); -}; - -/** - * Compile the given `str` of ejs into a `Function`. - * - * @param {String} str - * @param {Object} options - * @return {Function} - * @api public - */ - -var compile = exports.compile = function(str, options){ - options = options || {}; - - var input = JSON.stringify(str) - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined'; - - // Adds the fancy stack trace meta info - str = [ - 'var __stack = { lineno: 1, input: ' + input + ', filename: ' + filename + ' };', - rethrow.toString(), - 'try {', - exports.parse(str, options), - '} catch (err) {', - ' rethrow(err, __stack.input, __stack.filename, __stack.lineno);', - '}' - ].join("\n"); - - if (options.debug) console.log(str); - var fn = new Function('locals, filters, escape', str); - return function(locals){ - return fn.call(this, locals, filters, utils.escape); - } -}; - -/** - * Render the given `str` of ejs. - * - * Options: - * - * - `locals` Local variables object - * - `cache` Compiled functions are cached, requires `filename` - * - `filename` Used by `cache` to key caches - * - `scope` Function execution context - * - `debug` Output generated function body - * - `open` Open tag, defaulting to "<%" - * - `close` Closing tag, defaulting to "%>" - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api public - */ - -exports.render = function(str, options){ - var fn - , options = options || {}; - if (options.cache) { - if (options.filename) { - fn = cache[options.filename] || (cache[options.filename] = compile(str, options)); - } else { - throw new Error('"cache" option requires "filename".'); - } - } else { - fn = compile(str, options); - } - return fn.call(options.scope, options.locals || {}); -}; - -/** - * Expose to require(). - */ - -if (require.extensions) { - require.extensions['.ejs'] = function(module, filename) { - source = require('fs').readFileSync(filename, 'utf-8'); - module._compile(compile(source, {}), filename); - }; -} else if (require.registerExtension) { - require.registerExtension('.ejs', function(src) { - return compile(src, {}); - }); -} - -}); // module: ejs.js - -require.register("filters.js", function(module, exports, require){ - -/*! - * EJS - Filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * First element of the target `obj`. - */ - -exports.first = function(obj) { - return obj[0]; -}; - -/** - * Last element of the target `obj`. - */ - -exports.last = function(obj) { - return obj[obj.length - 1]; -}; - -/** - * Capitalize the first letter of the target `str`. - */ - -exports.capitalize = function(str){ - str = String(str); - return str[0].toUpperCase() + str.substr(1, str.length); -}; - -/** - * Downcase the target `str`. - */ - -exports.downcase = function(str){ - return String(str).toLowerCase(); -}; - -/** - * Uppercase the target `str`. - */ - -exports.upcase = function(str){ - return String(str).toUpperCase(); -}; - -/** - * Sort the target `obj`. - */ - -exports.sort = function(obj){ - return Object.create(obj).sort(); -}; - -/** - * Sort the target `obj` by the given `prop` ascending. - */ - -exports.sort_by = function(obj, prop){ - return Object.create(obj).sort(function(a, b){ - a = a[prop], b = b[prop]; - if (a > b) return 1; - if (a < b) return -1; - return 0; - }); -}; - -/** - * Size or length of the target `obj`. - */ - -exports.size = exports.length = function(obj) { - return obj.length; -}; - -/** - * Add `a` and `b`. - */ - -exports.plus = function(a, b){ - return Number(a) + Number(b); -}; - -/** - * Subtract `b` from `a`. - */ - -exports.minus = function(a, b){ - return Number(a) - Number(b); -}; - -/** - * Multiply `a` by `b`. - */ - -exports.times = function(a, b){ - return Number(a) * Number(b); -}; - -/** - * Divide `a` by `b`. - */ - -exports.divided_by = function(a, b){ - return Number(a) / Number(b); -}; - -/** - * Join `obj` with the given `str`. - */ - -exports.join = function(obj, str){ - return obj.join(str || ', '); -}; - -/** - * Truncate `str` to `len`. - */ - -exports.truncate = function(str, len){ - str = String(str); - return str.substr(0, len); -}; - -/** - * Truncate `str` to `n` words. - */ - -exports.truncate_words = function(str, n){ - var str = String(str) - , words = str.split(/ +/); - return words.slice(0, n).join(' '); -}; - -/** - * Replace `pattern` with `substitution` in `str`. - */ - -exports.replace = function(str, pattern, substitution){ - return String(str).replace(pattern, substitution || ''); -}; - -/** - * Prepend `val` to `obj`. - */ - -exports.prepend = function(obj, val){ - return Array.isArray(obj) - ? [val].concat(obj) - : val + obj; -}; - -/** - * Append `val` to `obj`. - */ - -exports.append = function(obj, val){ - return Array.isArray(obj) - ? obj.concat(val) - : obj + val; -}; - -/** - * Map the given `prop`. - */ - -exports.map = function(arr, prop){ - return arr.map(function(obj){ - return obj[prop]; - }); -}; - -/** - * Reverse the given `obj`. - */ - -exports.reverse = function(obj){ - return Array.isArray(obj) - ? obj.reverse() - : String(obj).split('').reverse().join(''); -}; - -/** - * Get `prop` of the given `obj`. - */ - -exports.get = function(obj, prop){ - return obj[prop]; -}; - -/** - * Packs the given `obj` into json string - */ -exports.json = function(obj){ - return JSON.stringify(obj); -}; -}); // module: filters.js - -require.register("utils.js", function(module, exports, require){ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -}); // module: utils.js diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.min.js b/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.min.js deleted file mode 100644 index 6b72d94..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.min.js +++ /dev/null @@ -1,2 +0,0 @@ -// CommonJS require() -function require(p){var path=require.resolve(p),mod=require.modules[path];if(!mod)throw new Error('failed to require "'+p+'"');mod.exports||(mod.exports={},mod.call(mod.exports,mod,mod.exports,require.relative(path)));return mod.exports}require.modules={},require.resolve=function(path){var orig=path,reg=path+".js",index=path+"/index.js";return require.modules[reg]&®||require.modules[index]&&index||orig},require.register=function(path,fn){require.modules[path]=fn},require.relative=function(parent){return function(p){if("."!=p[0])return require(p);var path=parent.split("/"),segs=p.split("/");path.pop();for(var i=0;i> ":" ")+curr+"| "+line}).join("\n");err.path=filename,err.message=(filename||"ejs")+":"+lineno+"\n"+context+"\n\n"+err.message;throw err}var parse=exports.parse=function(str,options){var options=options||{},open=options.open||exports.open||"<%",close=options.close||exports.close||"%>",buf=["var buf = [];","\nwith (locals) {","\n buf.push('"],lineno=1;for(var i=0,len=str.length;ib)return 1;if(a/g,">").replace(/"/g,""")}}) \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/client.html b/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/client.html deleted file mode 100644 index 7081a04..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/client.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.ejs b/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.ejs deleted file mode 100644 index d571330..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.ejs +++ /dev/null @@ -1,7 +0,0 @@ -<% if (names.length) { %> -
    - <% names.forEach(function(name){ %> -
  • <%= name %>
  • - <% }) %> -
-<% } %> \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.js b/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.js deleted file mode 100644 index 9cd7168..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.js +++ /dev/null @@ -1,16 +0,0 @@ - -/** - * Module dependencies. - */ - -var ejs = require('../') - , fs = require('fs') - , str = fs.readFileSync(__dirname + '/list.ejs', 'utf8'); - -var ret = ejs.render(str, { - locals: { - names: ['foo', 'bar', 'baz'] - } -}); - -console.log(ret); \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/index.js b/node_modules/mongodb/deps/nodeunit/deps/ejs/index.js deleted file mode 100644 index 20bf71a..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/ejs'); \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/ejs.js b/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/ejs.js deleted file mode 100644 index 46afa74..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/ejs.js +++ /dev/null @@ -1,251 +0,0 @@ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./utils'); - -/** - * Library version. - */ - -exports.version = '0.4.3'; - -/** - * Filters. - * - * @type Object - */ - -var filters = exports.filters = require('./filters'); - -/** - * Intermediate js cache. - * - * @type Object - */ - -var cache = {}; - -/** - * Clear intermediate js cache. - * - * @api public - */ - -exports.clearCache = function(){ - cache = {}; -}; - -/** - * Translate filtered code into function calls. - * - * @param {String} js - * @return {String} - * @api private - */ - -function filtered(js) { - return js.substr(1).split('|').reduce(function(js, filter){ - var parts = filter.split(':') - , name = parts.shift() - , args = parts.shift() || ''; - if (args) args = ', ' + args; - return 'filters.' + name + '(' + js + args + ')'; - }); -}; - -/** - * Re-throw the given `err` in context to the - * `str` of ejs, `filename`, and `lineno`. - * - * @param {Error} err - * @param {String} str - * @param {String} filename - * @param {String} lineno - * @api private - */ - -function rethrow(err, str, filename, lineno){ - var lines = str.split('\n') - , start = Math.max(lineno - 3, 0) - , end = Math.min(lines.length, lineno + 3); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' >> ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'ejs') + ':' - + lineno + '\n' - + context + '\n\n' - + err.message; - - throw err; -} - -/** - * Parse the given `str` of ejs, returning the function body. - * - * @param {String} str - * @return {String} - * @api public - */ - -var parse = exports.parse = function(str, options){ - var options = options || {} - , open = options.open || exports.open || '<%' - , close = options.close || exports.close || '%>'; - - var buf = [ - "var buf = [];" - , "\nwith (locals) {" - , "\n buf.push('" - ]; - - var lineno = 1; - - for (var i = 0, len = str.length; i < len; ++i) { - if (str.slice(i, open.length + i) == open) { - i += open.length - - var prefix, postfix, line = '__stack.lineno=' + lineno; - switch (str.substr(i, 1)) { - case '=': - prefix = "', escape((" + line + ', '; - postfix = ")), '"; - ++i; - break; - case '-': - prefix = "', (" + line + ', '; - postfix = "), '"; - ++i; - break; - default: - prefix = "');" + line + ';'; - postfix = "; buf.push('"; - } - - var end = str.indexOf(close, i) - , js = str.substring(i, end) - , start = i - , n = 0; - - while (~(n = js.indexOf("\n", n))) n++, lineno++; - if (js.substr(0, 1) == ':') js = filtered(js); - buf.push(prefix, js, postfix); - i += end - start + close.length - 1; - - } else if (str.substr(i, 1) == "\\") { - buf.push("\\\\"); - } else if (str.substr(i, 1) == "'") { - buf.push("\\'"); - } else if (str.substr(i, 1) == "\r") { - buf.push(" "); - } else if (str.substr(i, 1) == "\n") { - buf.push("\\n"); - lineno++; - } else { - buf.push(str.substr(i, 1)); - } - } - - buf.push("');\n}\nreturn buf.join('');"); - return buf.join(''); -}; - -/** - * Compile the given `str` of ejs into a `Function`. - * - * @param {String} str - * @param {Object} options - * @return {Function} - * @api public - */ - -var compile = exports.compile = function(str, options){ - options = options || {}; - - var input = JSON.stringify(str) - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined'; - - // Adds the fancy stack trace meta info - str = [ - 'var __stack = { lineno: 1, input: ' + input + ', filename: ' + filename + ' };', - rethrow.toString(), - 'try {', - exports.parse(str, options), - '} catch (err) {', - ' rethrow(err, __stack.input, __stack.filename, __stack.lineno);', - '}' - ].join("\n"); - - if (options.debug) console.log(str); - var fn = new Function('locals, filters, escape', str); - return function(locals){ - return fn.call(this, locals, filters, utils.escape); - } -}; - -/** - * Render the given `str` of ejs. - * - * Options: - * - * - `locals` Local variables object - * - `cache` Compiled functions are cached, requires `filename` - * - `filename` Used by `cache` to key caches - * - `scope` Function execution context - * - `debug` Output generated function body - * - `open` Open tag, defaulting to "<%" - * - `close` Closing tag, defaulting to "%>" - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api public - */ - -exports.render = function(str, options){ - var fn - , options = options || {}; - if (options.cache) { - if (options.filename) { - fn = cache[options.filename] || (cache[options.filename] = compile(str, options)); - } else { - throw new Error('"cache" option requires "filename".'); - } - } else { - fn = compile(str, options); - } - return fn.call(options.scope, options.locals || {}); -}; - -/** - * Expose to require(). - */ - -if (require.extensions) { - require.extensions['.ejs'] = function(module, filename) { - source = require('fs').readFileSync(filename, 'utf-8'); - module._compile(compile(source, {}), filename); - }; -} else if (require.registerExtension) { - require.registerExtension('.ejs', function(src) { - return compile(src, {}); - }); -} diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/filters.js b/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/filters.js deleted file mode 100644 index d425c8d..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/filters.js +++ /dev/null @@ -1,198 +0,0 @@ - -/*! - * EJS - Filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * First element of the target `obj`. - */ - -exports.first = function(obj) { - return obj[0]; -}; - -/** - * Last element of the target `obj`. - */ - -exports.last = function(obj) { - return obj[obj.length - 1]; -}; - -/** - * Capitalize the first letter of the target `str`. - */ - -exports.capitalize = function(str){ - str = String(str); - return str[0].toUpperCase() + str.substr(1, str.length); -}; - -/** - * Downcase the target `str`. - */ - -exports.downcase = function(str){ - return String(str).toLowerCase(); -}; - -/** - * Uppercase the target `str`. - */ - -exports.upcase = function(str){ - return String(str).toUpperCase(); -}; - -/** - * Sort the target `obj`. - */ - -exports.sort = function(obj){ - return Object.create(obj).sort(); -}; - -/** - * Sort the target `obj` by the given `prop` ascending. - */ - -exports.sort_by = function(obj, prop){ - return Object.create(obj).sort(function(a, b){ - a = a[prop], b = b[prop]; - if (a > b) return 1; - if (a < b) return -1; - return 0; - }); -}; - -/** - * Size or length of the target `obj`. - */ - -exports.size = exports.length = function(obj) { - return obj.length; -}; - -/** - * Add `a` and `b`. - */ - -exports.plus = function(a, b){ - return Number(a) + Number(b); -}; - -/** - * Subtract `b` from `a`. - */ - -exports.minus = function(a, b){ - return Number(a) - Number(b); -}; - -/** - * Multiply `a` by `b`. - */ - -exports.times = function(a, b){ - return Number(a) * Number(b); -}; - -/** - * Divide `a` by `b`. - */ - -exports.divided_by = function(a, b){ - return Number(a) / Number(b); -}; - -/** - * Join `obj` with the given `str`. - */ - -exports.join = function(obj, str){ - return obj.join(str || ', '); -}; - -/** - * Truncate `str` to `len`. - */ - -exports.truncate = function(str, len){ - str = String(str); - return str.substr(0, len); -}; - -/** - * Truncate `str` to `n` words. - */ - -exports.truncate_words = function(str, n){ - var str = String(str) - , words = str.split(/ +/); - return words.slice(0, n).join(' '); -}; - -/** - * Replace `pattern` with `substitution` in `str`. - */ - -exports.replace = function(str, pattern, substitution){ - return String(str).replace(pattern, substitution || ''); -}; - -/** - * Prepend `val` to `obj`. - */ - -exports.prepend = function(obj, val){ - return Array.isArray(obj) - ? [val].concat(obj) - : val + obj; -}; - -/** - * Append `val` to `obj`. - */ - -exports.append = function(obj, val){ - return Array.isArray(obj) - ? obj.concat(val) - : obj + val; -}; - -/** - * Map the given `prop`. - */ - -exports.map = function(arr, prop){ - return arr.map(function(obj){ - return obj[prop]; - }); -}; - -/** - * Reverse the given `obj`. - */ - -exports.reverse = function(obj){ - return Array.isArray(obj) - ? obj.reverse() - : String(obj).split('').reverse().join(''); -}; - -/** - * Get `prop` of the given `obj`. - */ - -exports.get = function(obj, prop){ - return obj[prop]; -}; - -/** - * Packs the given `obj` into json string - */ -exports.json = function(obj){ - return JSON.stringify(obj); -}; \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/utils.js b/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/utils.js deleted file mode 100644 index 8d569d6..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/utils.js +++ /dev/null @@ -1,23 +0,0 @@ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/package.json b/node_modules/mongodb/deps/nodeunit/deps/ejs/package.json deleted file mode 100644 index 224b4ff..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "ejs", - "description": "Embedded JavaScript templates", - "version": "0.4.3", - "author": "TJ Holowaychuk ", - "keywords": ["template", "engine", "ejs"], - "devDependencies": { - "expresso": "0.9.2" - }, - "main": "./lib/ejs.js" -} \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/support/compile.js b/node_modules/mongodb/deps/nodeunit/deps/ejs/support/compile.js deleted file mode 100644 index edd3815..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/support/compile.js +++ /dev/null @@ -1,173 +0,0 @@ - -/** - * Module dependencies. - */ - -var fs = require('fs'); - -/** - * Arguments. - */ - -var args = process.argv.slice(2) - , pending = args.length - , files = {}; - -console.log(''); - -// parse arguments - -args.forEach(function(file){ - var mod = file.replace('lib/', ''); - fs.readFile(file, 'utf8', function(err, js){ - if (err) throw err; - console.log(' \033[90mcompile : \033[0m\033[36m%s\033[0m', file); - files[file] = parse(js); - --pending || compile(); - }); -}); - -/** - * Parse the given `js`. - */ - -function parse(js) { - return parseInheritance(parseConditionals(js)); -} - -/** - * Parse __proto__. - */ - -function parseInheritance(js) { - return js - .replace(/^ *(\w+)\.prototype\.__proto__ * = *(\w+)\.prototype *;?/gm, function(_, child, parent){ - return child + '.prototype = new ' + parent + ';\n' - + child + '.prototype.constructor = '+ child + ';\n'; - }); -} - -/** - * Parse the given `js`, currently supporting: - * - * 'if' ['node' | 'browser'] - * 'end' - * - */ - -function parseConditionals(js) { - var lines = js.split('\n') - , len = lines.length - , buffer = true - , browser = false - , buf = [] - , line - , cond; - - for (var i = 0; i < len; ++i) { - line = lines[i]; - if (/^ *\/\/ *if *(node|browser)/gm.exec(line)) { - cond = RegExp.$1; - buffer = browser = 'browser' == cond; - } else if (/^ *\/\/ *end/.test(line)) { - buffer = true; - browser = false; - } else if (browser) { - buf.push(line.replace(/^( *)\/\//, '$1')); - } else if (buffer) { - buf.push(line); - } - } - - return buf.join('\n'); -} - -/** - * Compile the files. - */ - -function compile() { - var buf = ''; - buf += '\n// CommonJS require()\n\n'; - buf += browser.require + '\n\n'; - buf += 'require.modules = {};\n\n'; - buf += 'require.resolve = ' + browser.resolve + ';\n\n'; - buf += 'require.register = ' + browser.register + ';\n\n'; - buf += 'require.relative = ' + browser.relative + ';\n\n'; - args.forEach(function(file){ - var js = files[file]; - file = file.replace('lib/', ''); - buf += '\nrequire.register("' + file + '", function(module, exports, require){\n'; - buf += js; - buf += '\n}); // module: ' + file + '\n'; - }); - fs.writeFile('ejs.js', buf, function(err){ - if (err) throw err; - console.log(' \033[90m create : \033[0m\033[36m%s\033[0m', 'ejs.js'); - console.log(); - }); -} - -// refactored version of weepy's -// https://github.com/weepy/brequire/blob/master/browser/brequire.js - -var browser = { - - /** - * Require a module. - */ - - require: function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - }, - - /** - * Resolve module path. - */ - - resolve: function(path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }, - - /** - * Return relative require(). - */ - - relative: function(parent) { - return function(p){ - if ('.' != p.substr(0, 1)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }, - - /** - * Register a module. - */ - - register: function(path, fn){ - require.modules[path] = fn; - } -}; \ No newline at end of file diff --git a/node_modules/mongodb/deps/nodeunit/deps/ejs/test/ejs.test.js b/node_modules/mongodb/deps/nodeunit/deps/ejs/test/ejs.test.js deleted file mode 100644 index 624157d..0000000 --- a/node_modules/mongodb/deps/nodeunit/deps/ejs/test/ejs.test.js +++ /dev/null @@ -1,269 +0,0 @@ - -/** - * Module dependencies. - */ - -var ejs = require('../') - , assert = require('assert'); - -module.exports = { - 'test .version': function(){ - assert.ok(/^\d+\.\d+\.\d+$/.test(ejs.version), 'Test .version format'); - }, - - 'test html': function(){ - assert.equal('

yay

', ejs.render('

yay

')); - }, - - 'test buffered code': function(){ - var html = '

tj

', - str = '

<%= name %>

', - locals = { name: 'tj' }; - assert.equal(html, ejs.render(str, { locals: locals })); - }, - - 'test unbuffered code': function(){ - var html = '

tj

', - str = '<% if (name) { %>

<%= name %>

<% } %>', - locals = { name: 'tj' }; - assert.equal(html, ejs.render(str, { locals: locals })); - }, - - 'test `scope` option': function(){ - var html = '

tj

', - str = '

<%= this %>

'; - assert.equal(html, ejs.render(str, { scope: 'tj' })); - }, - - 'test escaping': function(){ - assert.equal('<script>', ejs.render('<%= " - - - - - - - - diff --git a/node_modules/mongodb/deps/nodeunit/examples/nested/nested_reporter_test.unit.js b/node_modules/mongodb/deps/nodeunit/examples/nested/nested_reporter_test.unit.js deleted file mode 100644 index 612adcd..0000000 --- a/node_modules/mongodb/deps/nodeunit/examples/nested/nested_reporter_test.unit.js +++ /dev/null @@ -1,94 +0,0 @@ -var testCase = require('nodeunit').testCase; -/* - This is an example test suite to demonstrate the nested test reporter. - Run with --reporter nested, e.g., - nodeunit --reporter nested nested_reporter_test.unit.js - - The test output should be something like: - - nested_reporter_test.unit.js - Test 0.1 (pass) - TC 1 - TC 1.1 - Test 1.1.1 (pass) - TC 2 - TC 2.1 - TC 2.1.1 - Test 2.1.1.1 (pass) - Test 2.1.1.2 (pass) - TC 2.2.1 - Test 2.2.1.1 (pass) - TC 2.2.1.1 - Test 2.2.1.1.1 (pass) - Test 2.2.1.2 (pass) - TC 3 - TC 3.1 - TC 3.1.1 - Test 3.1.1.1 (should fail) (fail) ✖ - AssertionError: false == true - // stack trace here. - - FAILURES: 1/8 assertions failed (6ms) -*/ - -module.exports = testCase({ - "Test 0.1": function(test) { - test.ok(true); - test.done(); - }, - - "TC 1": testCase({ - "TC 1.1": testCase({ - "Test 1.1.1": function(test) { - test.ok(true); - test.done(); - } - }) - }), - - "TC 2": testCase({ - "TC 2.1": testCase({ - "TC 2.1.1": testCase({ - "Test 2.1.1.1": function(test) { - test.ok(true); - test.done(); - }, - - "Test 2.1.1.2": function(test) { - test.ok(true); - test.done(); - } - }), - - "TC 2.2.1": testCase({ - "Test 2.2.1.1": function(test) { - test.ok(true); - test.done(); - }, - - "TC 2.2.1.1": testCase({ - "Test 2.2.1.1.1": function(test) { - test.ok(true); - test.done(); - }, - }), - - "Test 2.2.1.2": function(test) { - test.ok(true); - test.done(); - } - }) - }) - }), - - "TC 3": testCase({ - "TC 3.1": testCase({ - "TC 3.1.1": testCase({ - "Test 3.1.1.1 (should fail)": function(test) { - test.ok(false); - test.done(); - } - }) - }) - }) -}); diff --git a/node_modules/mongodb/deps/nodeunit/img/example_fail.png b/node_modules/mongodb/deps/nodeunit/img/example_fail.png deleted file mode 100644 index 78ff425..0000000 Binary files a/node_modules/mongodb/deps/nodeunit/img/example_fail.png and /dev/null differ diff --git a/node_modules/mongodb/deps/nodeunit/img/example_machineout.png b/node_modules/mongodb/deps/nodeunit/img/example_machineout.png deleted file mode 100644 index c6bfa27..0000000 Binary files a/node_modules/mongodb/deps/nodeunit/img/example_machineout.png and /dev/null differ diff --git a/node_modules/mongodb/deps/nodeunit/img/example_pass.png b/node_modules/mongodb/deps/nodeunit/img/example_pass.png deleted file mode 100644 index 069d716..0000000 Binary files a/node_modules/mongodb/deps/nodeunit/img/example_pass.png and /dev/null differ diff --git a/node_modules/mongodb/deps/nodeunit/index.js b/node_modules/mongodb/deps/nodeunit/index.js deleted file mode 100644 index 07867d0..0000000 --- a/node_modules/mongodb/deps/nodeunit/index.js +++ /dev/null @@ -1,3 +0,0 @@ -// This file is just added for convenience so this repository can be -// directly checked out into a project's deps folder -module.exports = require('./lib/nodeunit'); diff --git a/node_modules/mongodb/deps/nodeunit/lib/assert.js b/node_modules/mongodb/deps/nodeunit/lib/assert.js deleted file mode 100644 index 6f5f07e..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/assert.js +++ /dev/null @@ -1,327 +0,0 @@ -/** - * This file is based on the node.js assert module, but with some small - * changes for browser-compatibility - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - */ - - -/** - * Added for browser compatibility - */ - -var _keys = function(obj){ - if(Object.keys) return Object.keys(obj); - if (typeof obj != 'object' && typeof obj != 'function') { - throw new TypeError('-'); - } - var keys = []; - for(var k in obj){ - if(obj.hasOwnProperty(k)) keys.push(k); - } - return keys; -}; - - - -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var pSlice = Array.prototype.slice; - -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = exports; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({message: message, actual: actual, expected: expected}) - -assert.AssertionError = function AssertionError (options) { - this.name = "AssertionError"; - this.message = options.message; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } -}; -// code from util.inherits in node -assert.AssertionError.super_ = Error; - - -// EDITED FOR BROWSER COMPATIBILITY: replaced Object.create call -// TODO: test what effect this may have -var ctor = function () { this.constructor = assert.AssertionError; }; -ctor.prototype = Error.prototype; -assert.AssertionError.prototype = new ctor(); - - -assert.AssertionError.prototype.toString = function() { - if (this.message) { - return [this.name+":", this.message].join(' '); - } else { - return [ this.name+":" - , JSON.stringify(this.expected ) - , this.operator - , JSON.stringify(this.actual) - ].join(" "); - } -}; - -// assert.AssertionError instanceof Error - -assert.AssertionError.__proto__ = Error.prototype; - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -assert.ok = function ok(value, message) { - if (!!!value) fail(value, true, message, "==", assert.ok); -}; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, "==", assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, "!=", assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, "deepEqual", assert.deepEqual); - } -}; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - // 7.2.1 If the expcted value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object that refers to the same source and options - } else if (actual instanceof RegExp && expected instanceof RegExp) { - return actual.source === expected.source && - actual.global === expected.global && - actual.ignoreCase === expected.ignoreCase && - actual.multiline === expected.multiline; - - // 7.3. Other pairs that do not both pass typeof value == "object", - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; - - // 7.4. For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical "prototype" property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isUndefinedOrNull (value) { - return value === null || value === undefined; -} - -function isArguments (object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv (a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) - return false; - // an identical "prototype" property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try{ - var ka = _keys(a), - kb = _keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key] )) - return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, "notDeepEqual", assert.notDeepEqual); - } -}; - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, "===", assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as determined by !==. -// assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, "!==", assert.notStrictEqual); - } -}; - -function _throws (shouldThrow, block, err, message) { - var exception = null, - threw = false, - typematters = true; - - message = message || ""; - - //handle optional arguments - if (arguments.length == 3) { - if (typeof(err) == "string") { - message = err; - typematters = false; - } - } else if (arguments.length == 2) { - typematters = false; - } - - try { - block(); - } catch (e) { - threw = true; - exception = e; - } - - if (shouldThrow && !threw) { - fail( "Missing expected exception" - + (err && err.name ? " ("+err.name+")." : '.') - + (message ? " " + message : "") - ); - } - if (!shouldThrow && threw && typematters && exception instanceof err) { - fail( "Got unwanted exception" - + (err && err.name ? " ("+err.name+")." : '.') - + (message ? " " + message : "") - ); - } - if ((shouldThrow && threw && typematters && !(exception instanceof err)) || - (!shouldThrow && threw)) { - throw exception; - } -}; - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function (err) { if (err) {throw err;}}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/core.js b/node_modules/mongodb/deps/nodeunit/lib/core.js deleted file mode 100644 index 028745e..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/core.js +++ /dev/null @@ -1,316 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, it's mostly to avoid requiring code - * that is node specific - */ - -/** - * Module dependencies - */ - -var async = require('../deps/async'), //@REMOVE_LINE_FOR_BROWSER - nodeunit = require('./nodeunit'), //@REMOVE_LINE_FOR_BROWSER - types = require('./types'); //@REMOVE_LINE_FOR_BROWSER - - -/** - * Added for browser compatibility - */ - -var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; -}; - - -var _copy = function (obj) { - var nobj = {}; - var keys = _keys(obj); - for (var i = 0; i < keys.length; i += 1) { - nobj[keys[i]] = obj[keys[i]]; - } - return nobj; -}; - - -/** - * Runs a test function (fn) from a loaded module. After the test function - * calls test.done(), the callback is executed with an assertionList as its - * second argument. - * - * @param {String} name - * @param {Function} fn - * @param {Object} opt - * @param {Function} callback - * @api public - */ - -exports.runTest = function (name, fn, opt, callback) { - var options = types.options(opt); - - options.testStart(name); - var start = new Date().getTime(); - var test = types.test(name, start, options, callback); - - try { - fn(test); - } - catch (e) { - test.done(e); - } -}; - -/** - * Takes an object containing test functions or other test suites as properties - * and runs each in series. After all tests have completed, the callback is - * called with a list of all assertions as the second argument. - * - * If a name is passed to this function it is prepended to all test and suite - * names that run within it. - * - * @param {String} name - * @param {Object} suite - * @param {Object} opt - * @param {Function} callback - * @api public - */ - -exports.runSuite = function (name, suite, opt, callback) { - suite = wrapGroup(suite); - var keys = _keys(suite); - - async.concatSeries(keys, function (k, cb) { - var prop = suite[k], _name; - - _name = name ? [].concat(name, k) : [k]; - _name.toString = function () { - // fallback for old one - return this.join(' - '); - }; - - if (typeof prop === 'function') { - var in_name = false; - for (var i = 0; i < _name.length; i += 1) { - if (_name[i] === opt.testspec) { - in_name = true; - } - } - if (!opt.testspec || in_name) { - if (opt.moduleStart) { - opt.moduleStart(); - } - exports.runTest(_name, suite[k], opt, cb); - } - else { - return cb(); - } - } - else { - exports.runSuite(_name, suite[k], opt, cb); - } - }, callback); -}; - -/** - * Run each exported test function or test suite from a loaded module. - * - * @param {String} name - * @param {Object} mod - * @param {Object} opt - * @param {Function} callback - * @api public - */ - -exports.runModule = function (name, mod, opt, callback) { - var options = _copy(types.options(opt)); - - var _run = false; - var _moduleStart = options.moduleStart; - - mod = wrapGroup(mod); - - function run_once() { - if (!_run) { - _run = true; - _moduleStart(name); - } - } - options.moduleStart = run_once; - - var start = new Date().getTime(); - - exports.runSuite(null, mod, options, function (err, a_list) { - var end = new Date().getTime(); - var assertion_list = types.assertionList(a_list, end - start); - options.moduleDone(name, assertion_list); - if (nodeunit.complete) { - nodeunit.complete(name, assertion_list); - } - callback(null, a_list); - }); -}; - -/** - * Treats an object literal as a list of modules keyed by name. Runs each - * module and finished with calling 'done'. You can think of this as a browser - * safe alternative to runFiles in the nodeunit module. - * - * @param {Object} modules - * @param {Object} opt - * @api public - */ - -// TODO: add proper unit tests for this function -exports.runModules = function (modules, opt) { - var all_assertions = []; - var options = types.options(opt); - var start = new Date().getTime(); - - async.concatSeries(_keys(modules), function (k, cb) { - exports.runModule(k, modules[k], options, cb); - }, - function (err, all_assertions) { - var end = new Date().getTime(); - options.done(types.assertionList(all_assertions, end - start)); - }); -}; - - -/** - * Wraps a test function with setUp and tearDown functions. - * Used by testCase. - * - * @param {Function} setUp - * @param {Function} tearDown - * @param {Function} fn - * @api private - */ - -var wrapTest = function (setUp, tearDown, fn) { - return function (test) { - var context = {}; - if (tearDown) { - var done = test.done; - test.done = function (err) { - try { - tearDown.call(context, function (err2) { - if (err && err2) { - test._assertion_list.push( - types.assertion({error: err}) - ); - return done(err2); - } - done(err || err2); - }); - } - catch (e) { - done(e); - } - }; - } - if (setUp) { - setUp.call(context, function (err) { - if (err) { - return test.done(err); - } - fn.call(context, test); - }); - } - else { - fn.call(context, test); - } - }; -}; - - -/** - * Returns a serial callback from two functions. - * - * @param {Function} funcFirst - * @param {Function} funcSecond - * @api private - */ - -var getSerialCallback = function (fns) { - if (!fns.length) { - return null; - } - return function (callback) { - var that = this; - var bound_fns = []; - for (var i = 0, len = fns.length; i < len; i++) { - (function (j) { - bound_fns.push(function () { - return fns[j].apply(that, arguments); - }); - })(i); - } - return async.series(bound_fns, callback); - }; -}; - - -/** - * Wraps a group of tests with setUp and tearDown functions. - * Used by testCase. - * - * @param {Object} group - * @param {Array} setUps - parent setUp functions - * @param {Array} tearDowns - parent tearDown functions - * @api private - */ - -var wrapGroup = function (group, setUps, tearDowns) { - var tests = {}; - - var setUps = setUps ? setUps.slice(): []; - var tearDowns = tearDowns ? tearDowns.slice(): []; - - if (group.setUp) { - setUps.push(group.setUp); - delete group.setUp; - } - if (group.tearDown) { - tearDowns.unshift(group.tearDown); - delete group.tearDown; - } - - var keys = _keys(group); - - for (var i = 0; i < keys.length; i += 1) { - var k = keys[i]; - if (typeof group[k] === 'function') { - tests[k] = wrapTest( - getSerialCallback(setUps), - getSerialCallback(tearDowns), - group[k] - ); - } - else if (typeof group[k] === 'object') { - tests[k] = wrapGroup(group[k], setUps, tearDowns); - } - } - return tests; -}; - - -/** - * Backwards compatibility for test suites using old testCase API - */ - -exports.testCase = function (suite) { - return suite; -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/nodeunit.js b/node_modules/mongodb/deps/nodeunit/lib/nodeunit.js deleted file mode 100644 index c7164ca..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/nodeunit.js +++ /dev/null @@ -1,103 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var async = require('../deps/async'), - types = require('./types'), - utils = require('./utils'), - core = require('./core'), - reporters = require('./reporters'), - assert = require('./assert'), - path = require('path'), - events = require('events'); - -/** - * Export sub-modules. - */ - -exports.types = types; -exports.utils = utils; -exports.reporters = reporters; -exports.assert = assert; - -// backwards compatibility -exports.testrunner = { - run: function () { - console.log( - 'WARNING: nodeunit.testrunner is going to be deprecated, please ' + - 'use nodeunit.reporters.default instead!' - ); - return reporters['default'].run.apply(this, arguments); - } -}; - - -/** - * Export all core functions - */ - -for (var k in core) { - exports[k] = core[k]; -}; - - -/** - * Load modules from paths array and run all exported tests in series. If a path - * is a directory, load all supported file types inside it as modules. This only - * reads 1 level deep in the directory and does not recurse through - * sub-directories. - * - * @param {Array} paths - * @param {Object} opt - * @api public - */ - -exports.runFiles = function (paths, opt) { - var all_assertions = []; - var options = types.options(opt); - var start = new Date().getTime(); - - if (!paths.length) { - return options.done(types.assertionList(all_assertions)); - } - - utils.modulePaths(paths, function (err, files) { - if (err) throw err; - async.concatSeries(files, function (file, cb) { - var name = path.basename(file); - exports.runModule(name, require(file), options, cb); - }, - function (err, all_assertions) { - var end = new Date().getTime(); - exports.done() - options.done(types.assertionList(all_assertions, end - start)); - }); - }); - -}; - -/* Export all prototypes from events.EventEmitter */ -var label; -for (label in events.EventEmitter.prototype) { - exports[label] = events.EventEmitter.prototype[label]; -} - -/* Emit event 'complete' on completion of a test suite. */ -exports.complete = function(name, assertions) -{ - exports.emit('complete', name, assertions); -}; - -/* Emit event 'complete' on completion of all tests. */ -exports.done = function() -{ - exports.emit('done'); -}; - -module.exports = exports; diff --git a/node_modules/mongodb/deps/nodeunit/lib/reporters/browser.js b/node_modules/mongodb/deps/nodeunit/lib/reporters/browser.js deleted file mode 100644 index 9836c90..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/reporters/browser.js +++ /dev/null @@ -1,121 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - - -/** - * NOTE: this test runner is not listed in index.js because it cannot be - * used with the command-line tool, only inside the browser. - */ - - -/** - * Reporter info string - */ - -exports.info = "Browser-based test reporter"; - - -/** - * Run all tests within each module, reporting the results - * - * @param {Array} files - * @api public - */ - -exports.run = function (modules, options) { - var start = new Date().getTime(), div; - options = options || {}; - div = options.div || document.body; - - function setText(el, txt) { - if ('innerText' in el) { - el.innerText = txt; - } - else if ('textContent' in el){ - el.textContent = txt; - } - } - - function getOrCreate(tag, id) { - var el = document.getElementById(id); - if (!el) { - el = document.createElement(tag); - el.id = id; - div.appendChild(el); - } - return el; - }; - - var header = getOrCreate('h1', 'nodeunit-header'); - var banner = getOrCreate('h2', 'nodeunit-banner'); - var userAgent = getOrCreate('h2', 'nodeunit-userAgent'); - var tests = getOrCreate('ol', 'nodeunit-tests'); - var result = getOrCreate('p', 'nodeunit-testresult'); - - setText(userAgent, navigator.userAgent); - - nodeunit.runModules(modules, { - moduleStart: function (name) { - /*var mheading = document.createElement('h2'); - mheading.innerText = name; - results.appendChild(mheading); - module = document.createElement('ol'); - results.appendChild(module);*/ - }, - testDone: function (name, assertions) { - var test = document.createElement('li'); - var strong = document.createElement('strong'); - strong.innerHTML = name + ' (' + - '' + assertions.failures() + ', ' + - '' + assertions.passes() + ', ' + - assertions.length + - ')'; - test.className = assertions.failures() ? 'fail': 'pass'; - test.appendChild(strong); - - var aList = document.createElement('ol'); - aList.style.display = 'none'; - test.onclick = function () { - var d = aList.style.display; - aList.style.display = (d == 'none') ? 'block': 'none'; - }; - for (var i=0; i' + (a.error.stack || a.error) + ''; - li.className = 'fail'; - } - else { - li.innerHTML = a.message || a.method || 'no message'; - li.className = 'pass'; - } - aList.appendChild(li); - } - test.appendChild(aList); - tests.appendChild(test); - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - - var failures = assertions.failures(); - banner.className = failures ? 'fail': 'pass'; - - result.innerHTML = 'Tests completed in ' + duration + - ' milliseconds.
' + - assertions.passes() + ' assertions of ' + - '' + assertions.length + ' passed, ' + - assertions.failures() + ' failed.'; - } - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/reporters/default.js b/node_modules/mongodb/deps/nodeunit/lib/reporters/default.js deleted file mode 100644 index a72a42e..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/reporters/default.js +++ /dev/null @@ -1,130 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - track = require('../track'), - path = require('path'), - AssertionError = require('../assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Default tests reporter"; - - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var error = function (str) { - return options.error_prefix + str + options.error_suffix; - }; - var ok = function (str) { - return options.ok_prefix + str + options.ok_suffix; - }; - var bold = function (str) { - return options.bold_prefix + str + options.bold_suffix; - }; - var assertion_message = function (str) { - return options.assertion_prefix + str + options.assertion_suffix; - }; - - var start = new Date().getTime(); - var tracker = track.createTracker(function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log(error(bold( - 'FAILURES: Undone tests (or their setups/teardowns): ' - ))); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log('- ' + names[i]); - } - console.log(''); - console.log('To fix this, make sure all tests call test.done()'); - process.reallyExit(tracker.unfinished()); - } - }); - - var opts = { - testspec: options.testspec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - console.log('✔ ' + name); - } - else { - console.log(error('✖ ' + name) + '\n'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + - assertion_message(a.message) - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - done: function (assertions, end) { - var end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - }, - testStart: function(name) { - tracker.put(name); - } - }; - if (files && files.length) { - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - nodeunit.runFiles(paths, opts); - } else { - nodeunit.runModules(files,opts); - } -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/reporters/eclipse.js b/node_modules/mongodb/deps/nodeunit/lib/reporters/eclipse.js deleted file mode 100644 index 6775ff1..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/reporters/eclipse.js +++ /dev/null @@ -1,104 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - track = require('../track'), - path = require('path'), - AssertionError = require('../assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Reporter for eclipse plugin"; - - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - var start = new Date().getTime(); - var paths = files.map(function (p) { - if (p.indexOf('/') === 0) { - return p; - } - return path.join(process.cwd(), p); - }); - var tracker = track.createTracker(function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log('FAILURES: Undone tests (or their setups/teardowns): '); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log('- ' + names[i]); - } - console.log(''); - console.log('To fix this, make sure all tests call test.done()'); - process.reallyExit(tracker.unfinished()); - } - }); - - nodeunit.runFiles(paths, { - testspec: undefined, - moduleStart: function (name) { - console.log('\n' + name); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - console.log('✔ ' + name); - } - else { - console.log('✖ ' + name + '\n'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + a.message - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - done: function (assertions, end) { - var end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + 'FAILURES: ' + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + 'OK: ' + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - }, - testStart: function (name) { - tracker.put(name); - } - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/reporters/html.js b/node_modules/mongodb/deps/nodeunit/lib/reporters/html.js deleted file mode 100644 index 2790b58..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/reporters/html.js +++ /dev/null @@ -1,109 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - path = require('path'), - AssertionError = require('assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Report tests result as HTML"; - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - - console.log(''); - console.log(''); - console.log(''); - console.log(''); - console.log(''); - console.log(''); - nodeunit.runFiles(paths, { - testspec: options.testspec, - moduleStart: function (name) { - console.log('

' + name + '

'); - console.log('
    '); - }, - testDone: function (name, assertions) { - if (!assertions.failures()) { - console.log('
  1. ' + name + '
  2. '); - } - else { - console.log('
  3. ' + name); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log('
    ' + - 'Assertion Message: ' + a.message + - '
    '); - } - console.log('
    ');
    -                        console.log(a.error.stack);
    -                        console.log('
    '); - } - }); - console.log('
  4. '); - } - }, - moduleDone: function () { - console.log('
'); - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '

FAILURES: ' + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)

' - ); - } - else { - console.log( - '

OK: ' + assertions.length + - ' assertions (' + assertions.duration + 'ms)

' - ); - } - console.log(''); - console.log(''); - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - } - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/reporters/index.js b/node_modules/mongodb/deps/nodeunit/lib/reporters/index.js deleted file mode 100644 index b3989c0..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/reporters/index.js +++ /dev/null @@ -1,14 +0,0 @@ -module.exports = { - 'junit': require('./junit'), - 'default': require('./default'), - 'skip_passed': require('./skip_passed'), - 'minimal': require('./minimal'), - 'html': require('./html'), - 'eclipse': require('./eclipse'), - 'machineout': require('./machineout'), - 'tap': require('./tap'), - 'nested': require('./nested'), - 'verbose' : require('./verbose') - // browser test reporter is not listed because it cannot be used - // with the command line tool, only inside a browser. -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/reporters/junit.js b/node_modules/mongodb/deps/nodeunit/lib/reporters/junit.js deleted file mode 100644 index ea12280..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/reporters/junit.js +++ /dev/null @@ -1,179 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - path = require('path'), - async = require('../../deps/async'), - AssertionError = require('assert').AssertionError, - child_process = require('child_process'), - ejs = require('../../deps/ejs'); - - -/** - * Reporter info string - */ - -exports.info = "jUnit XML test reports"; - - -/** - * Ensures a directory exists using mkdir -p. - * - * @param {String} path - * @param {Function} callback - * @api private - */ - -var ensureDir = function (path, callback) { - var mkdir = child_process.spawn('mkdir', ['-p', path]); - mkdir.on('error', function (err) { - callback(err); - callback = function(){}; - }); - mkdir.on('exit', function (code) { - if (code === 0) callback(); - else callback(new Error('mkdir exited with code: ' + code)); - }); -}; - - -/** - * Returns absolute version of a path. Relative paths are interpreted - * relative to process.cwd() or the cwd parameter. Paths that are already - * absolute are returned unaltered. - * - * @param {String} p - * @param {String} cwd - * @return {String} - * @api public - */ - -var abspath = function (p, /*optional*/cwd) { - if (p[0] === '/') return p; - cwd = cwd || process.cwd(); - return path.normalize(path.join(cwd, p)); -}; - - -/** - * Run all tests within each module, reporting the results to the command-line, - * then writes out junit-compatible xml documents. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, opts, callback) { - if (!opts.output) { - console.error( - 'Error: No output directory defined.\n' + - '\tEither add an "output" property to your nodeunit.json config ' + - 'file, or\n\tuse the --output command line option.' - ); - return; - } - opts.output = abspath(opts.output); - var error = function (str) { - return opts.error_prefix + str + opts.error_suffix; - }; - var ok = function (str) { - return opts.ok_prefix + str + opts.ok_suffix; - }; - var bold = function (str) { - return opts.bold_prefix + str + opts.bold_suffix; - }; - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - - var modules = {} - var curModule; - - nodeunit.runFiles(paths, { - testspec: opts.testspec, - moduleStart: function (name) { - curModule = { - errorCount: 0, - failureCount: 0, - tests: 0, - testcases: [], - name: name - }; - modules[name] = curModule; - }, - testDone: function (name, assertions) { - var testcase = {name: name}; - for (var i=0; i name_slice(['TC1', 'TC1.1', 'mytest'], 1); - * "TC1,TC1.1" - */ - var name_slice = function (name_arr, end_index) { - return name_arr.slice(0, end_index + 1).join(","); - }; - - var indent = (function () { - var txt = ''; - var i; - for (i = 0; i < spaces_per_indent; i++) { - txt += ' '; - } - return txt; - }()); - - // Indent once for each indent_level - var add_indent = function (txt, indent_level) { - var k; - for (k = 0; k < indent_level; k++) { - txt += indent; - } - return txt; - }; - - // If it's not the last element of the name_arr, it's a testCase. - var is_testCase = function (name_arr, index) { - return index === name_arr.length - 1 ? false : true; - }; - - var testCase_line = function (txt) { - return txt + "\n"; - }; - - /** - * Prints (console.log) the nested test status line(s). - * - * @param {Array} name_arr - Array of name elements. - * @param {String} status - either 'pass' or 'fail'. - * @example - * > print_status(['TC1', 'TC1.1', 'mytest'], 'pass'); - * TC1 - * TC1.1 - * mytest (pass) - */ - var print_status = function (name_arr, status) { - var txt = ''; - var _name_slice, part, i; - for (i = 0; i < name_arr.length; i++) { - _name_slice = name_slice(name_arr, i); - part = name_arr[i]; - if (!tracker.already_printed[_name_slice]) { - txt = add_indent(txt, i); - if (is_testCase(name_arr, i)) { - txt += testCase_line(part); - } else { - txt += status_text(part, status); - } - tracker.already_printed[_name_slice] = true; - } - } - console.log(txt); - }; - - nodeunit.runFiles(paths, { - testspec: options.testspec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - print_status(name, 'pass'); - } else { - print_status(name, 'fail'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + - assertion_message(a.message) - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - done: function (assertions, end) { - end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - }, - testStart: function (name) { - tracker.put(name); - } - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/reporters/skip_passed.js b/node_modules/mongodb/deps/nodeunit/lib/reporters/skip_passed.js deleted file mode 100644 index b39de41..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/reporters/skip_passed.js +++ /dev/null @@ -1,107 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - path = require('path'), - AssertionError = require('assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Skip passed tests output"; - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var error = function (str) { - return options.error_prefix + str + options.error_suffix; - }; - var ok = function (str) { - return options.ok_prefix + str + options.ok_suffix; - }; - var bold = function (str) { - return options.bold_prefix + str + options.bold_suffix; - }; - var assertion_message = function (str) { - return options.assertion_prefix + str + options.assertion_suffix; - }; - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - - nodeunit.runFiles(paths, { - testspec: options.testspec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - if (assertions.failures()) { - console.log(error('✖ ' + name) + '\n'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + assertion_message(a.message) - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - moduleDone: function (name, assertions) { - if (!assertions.failures()) { - console.log('✔ all tests passed'); - } - else { - console.log(error('✖ some tests failed')); - } - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - } - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/reporters/tap.js b/node_modules/mongodb/deps/nodeunit/lib/reporters/tap.js deleted file mode 100644 index b057460..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/reporters/tap.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - path = require('path'), - assert = require('tap-assert'), - TapProducer = require('tap-producer'); - -/** - * Reporter info string - */ - -exports.info = "TAP output"; - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - var output = new TapProducer(); - output.pipe(process.stdout); - - nodeunit.runFiles(paths, { - testStart: function (name) { - output.write(name.toString()); - }, - testDone: function (name, assertions) { - assertions.forEach(function (e) { - var extra = {}; - if (e.error) { - extra.error = { - name: e.error.name, - message: e.error.message, - stack: e.error.stack.split(/\n/).filter(function (line) { - // exclude line of "types.js" - return ! RegExp(/types.js:83:39/).test(line); - }).join('\n') - }; - extra.wanted = e.error.expected; - extra.found = e.error.actual; - } - output.write(assert(e.passed(), e.message, extra)); - }); - }, - done: function (assertions) { - output.end(); - } - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/reporters/verbose.js b/node_modules/mongodb/deps/nodeunit/lib/reporters/verbose.js deleted file mode 100644 index 6ccb617..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/reporters/verbose.js +++ /dev/null @@ -1,122 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - track = require('../track'), - path = require('path'); - AssertionError = require('../assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Verbose tests reporter" - - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var error = function (str) { - return options.error_prefix + str + options.error_suffix; - }; - var ok = function (str) { - return options.ok_prefix + str + options.ok_suffix; - }; - var bold = function (str) { - return options.bold_prefix + str + options.bold_suffix; - }; - var assertion_message = function (str) { - return options.assertion_prefix + str + options.assertion_suffix; - }; - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - var tracker = track.createTracker(function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log(error(bold( - 'FAILURES: Undone tests (or their setups/teardowns): ' - ))); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log('- ' + names[i]); - } - console.log(''); - console.log('To fix this, make sure all tests call test.done()'); - process.reallyExit(tracker.unfinished()); - } - }); - - nodeunit.runFiles(paths, { - testspec: options.testspec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - console.log('✔ ' + name); - } - else { - console.log(error('✖ ' + name)); - } - // verbose so print everything - assertions.forEach(function (a) { - if (a.failed()) { - console.log(error(' ✖ ' + a.message)); - a = utils.betterErrors(a); - console.log(' ' + a.error.stack); - } - else { - console.log(' ✔ ' + a.message); - } - }); - }, - done: function (assertions, end) { - var end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - }, - testStart: function(name) { - tracker.put(name); - } - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/track.js b/node_modules/mongodb/deps/nodeunit/lib/track.js deleted file mode 100644 index 5af98ad..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/track.js +++ /dev/null @@ -1,48 +0,0 @@ -/*! - * Simple util module to track tests. Adds a process.exit hook to print - * the undone tests. - */ - - -exports.createTracker = function (on_exit) { - var names = {}; - var tracker = { - names: function () { - var arr = []; - for (var k in names) { - if (names.hasOwnProperty(k)) { - arr.push(k); - } - } - return arr; - }, - unfinished: function () { - return tracker.names().length; - }, - put: function (testname) { - names[testname] = testname; - }, - remove: function (testname) { - delete names[testname]; - } - }; - - process.on('exit', function() { - on_exit = on_exit || exports.default_on_exit; - on_exit(tracker); - }); - - return tracker; -}; - -exports.default_on_exit = function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log('Undone tests (or their setups/teardowns): '); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log(names[i]); - } - process.reallyExit(tracker.unfinished()); - } -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/types.js b/node_modules/mongodb/deps/nodeunit/lib/types.js deleted file mode 100644 index 2cdd1ef..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/types.js +++ /dev/null @@ -1,189 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, it's mostly to avoid requiring code - * that is node specific - */ - -/** - * Module dependencies - */ - -var assert = require('./assert'), //@REMOVE_LINE_FOR_BROWSER - async = require('../deps/async'); //@REMOVE_LINE_FOR_BROWSER - - -/** - * Creates assertion objects representing the result of an assert call. - * Accepts an object or AssertionError as its argument. - * - * @param {object} obj - * @api public - */ - -exports.assertion = function (obj) { - return { - method: obj.method || '', - message: obj.message || (obj.error && obj.error.message) || '', - error: obj.error, - passed: function () { - return !this.error; - }, - failed: function () { - return Boolean(this.error); - } - }; -}; - -/** - * Creates an assertion list object representing a group of assertions. - * Accepts an array of assertion objects. - * - * @param {Array} arr - * @param {Number} duration - * @api public - */ - -exports.assertionList = function (arr, duration) { - var that = arr || []; - that.failures = function () { - var failures = 0; - for (var i = 0; i < this.length; i += 1) { - if (this[i].failed()) { - failures += 1; - } - } - return failures; - }; - that.passes = function () { - return that.length - that.failures(); - }; - that.duration = duration || 0; - return that; -}; - -/** - * Create a wrapper function for assert module methods. Executes a callback - * after it's complete with an assertion object representing the result. - * - * @param {Function} callback - * @api private - */ - -var assertWrapper = function (callback) { - return function (new_method, assert_method, arity) { - return function () { - var message = arguments[arity - 1]; - var a = exports.assertion({method: new_method, message: message}); - try { - assert[assert_method].apply(null, arguments); - } - catch (e) { - a.error = e; - } - callback(a); - }; - }; -}; - -/** - * Creates the 'test' object that gets passed to every test function. - * Accepts the name of the test function as its first argument, followed by - * the start time in ms, the options object and a callback function. - * - * @param {String} name - * @param {Number} start - * @param {Object} options - * @param {Function} callback - * @api public - */ - -exports.test = function (name, start, options, callback) { - var expecting; - var a_list = []; - - var wrapAssert = assertWrapper(function (a) { - a_list.push(a); - if (options.log) { - async.nextTick(function () { - options.log(a); - }); - } - }); - - var test = { - done: function (err) { - if (expecting !== undefined && expecting !== a_list.length) { - var e = new Error( - 'Expected ' + expecting + ' assertions, ' + - a_list.length + ' ran' - ); - var a1 = exports.assertion({method: 'expect', error: e}); - a_list.push(a1); - if (options.log) { - async.nextTick(function () { - options.log(a1); - }); - } - } - if (err) { - var a2 = exports.assertion({error: err}); - a_list.push(a2); - if (options.log) { - async.nextTick(function () { - options.log(a2); - }); - } - } - var end = new Date().getTime(); - async.nextTick(function () { - var assertion_list = exports.assertionList(a_list, end - start); - options.testDone(name, assertion_list); - callback(null, a_list); - }); - }, - ok: wrapAssert('ok', 'ok', 2), - same: wrapAssert('same', 'deepEqual', 3), - equals: wrapAssert('equals', 'equal', 3), - expect: function (num) { - expecting = num; - }, - _assertion_list: a_list - }; - // add all functions from the assert module - for (var k in assert) { - if (assert.hasOwnProperty(k)) { - test[k] = wrapAssert(k, k, assert[k].length); - } - } - return test; -}; - -/** - * Ensures an options object has all callbacks, adding empty callback functions - * if any are missing. - * - * @param {Object} opt - * @return {Object} - * @api public - */ - -exports.options = function (opt) { - var optionalCallback = function (name) { - opt[name] = opt[name] || function () {}; - }; - - optionalCallback('moduleStart'); - optionalCallback('moduleDone'); - optionalCallback('testStart'); - optionalCallback('testDone'); - //optionalCallback('log'); - - // 'done' callback is not optional. - - return opt; -}; diff --git a/node_modules/mongodb/deps/nodeunit/lib/utils.js b/node_modules/mongodb/deps/nodeunit/lib/utils.js deleted file mode 100644 index 8f49e46..0000000 --- a/node_modules/mongodb/deps/nodeunit/lib/utils.js +++ /dev/null @@ -1,209 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var async = require('../deps/async'), - fs = require('fs'), - util = require('util'), - Script = process.binding('evals').Script || process.binding('evals').NodeScript, - http = require('http'); - - -/** - * Detect if coffee-script is available and search for .coffee as an - * extension in modulePaths if it is. - */ - -var extensionPattern; -try { - require('coffee-script'); - extensionPattern = /\.(?:js|coffee)$/; -} -catch (e) { - extensionPattern = /\.js$/; -} - - -/** - * Finds all modules at each path in an array, If a path is a directory, it - * returns all supported file types inside it. This only reads 1 level deep in - * the directory and does not recurse through sub-directories. - * - * The extension (.js, .coffee etc) is stripped from the filenames so they can - * simply be require()'ed. - * - * @param {Array} paths - * @param {Function} callback - * @api public - */ - -exports.modulePaths = function (paths, callback) { - async.concat(paths, function (p, cb) { - fs.stat(p, function (err, stats) { - if (err) { - return cb(err); - } - if (stats.isFile()) { - return cb(null, [p]); - } - if (stats.isDirectory()) { - fs.readdir(p, function (err, files) { - if (err) { - return cb(err); - } - - // filter out any filenames with unsupported extensions - var modules = files.filter(function (filename) { - return extensionPattern.exec(filename); - }); - - // remove extension from module name and prepend the - // directory path - var fullpaths = modules.map(function (filename) { - var mod_name = filename.replace(extensionPattern, ''); - return [p, mod_name].join('/'); - }); - - // sort filenames here, because Array.map changes order - fullpaths.sort(); - - cb(null, fullpaths); - }); - } - }); - }, callback); -}; - -/** - * Evaluates JavaScript files in a sandbox, returning the context. The first - * argument can either be a single filename or an array of filenames. If - * multiple filenames are given their contents are concatenated before - * evalution. The second argument is an optional context to use for the sandbox. - * - * @param files - * @param {Object} sandbox - * @return {Object} - * @api public - */ - -exports.sandbox = function (files, /*optional*/sandbox) { - var source, script, result; - if (!(files instanceof Array)) { - files = [files]; - } - source = files.map(function (file) { - return fs.readFileSync(file, 'utf8'); - }).join(''); - - if (!sandbox) { - sandbox = {}; - } - script = new Script(source); - result = script.runInNewContext(sandbox); - return sandbox; -}; - -/** - * Provides a http request, response testing environment. - * - * Example: - * - * var httputil = require('nodeunit').utils.httputil - * exports.testSomething = function(test) { - * httputil(function (req, resp) { - * resp.writeHead(200, {}); - * resp.end('test data'); - * }, - * function(server, client) { - * client.fetch('GET', '/', {}, function(resp) { - * test.equal('test data', resp.body); - * server.close(); - * test.done(); - * }) - * }); - * }; - * - * @param {Function} cgi - * @param {Function} envReady - * @api public - */ -exports.httputil = function (cgi, envReady) { - var hostname = process.env.HOSTNAME || 'localhost'; - var port = process.env.PORT || 3000; - - var server = http.createServer(cgi); - server.listen(port, hostname); - - var client = http.createClient(port, hostname); - client.fetch = function (method, path, headers, respReady) { - var request = this.request(method, path, headers); - request.end(); - request.on('response', function (response) { - response.setEncoding('utf8'); - response.on('data', function (chunk) { - if (response.body) { - response.body += chunk; - } else { - response.body = chunk; - } - }); - response.on('end', function () { - if (response.headers['content-type'] === 'application/json') { - response.bodyAsObject = JSON.parse(response.body); - } - respReady(response); - }); - }); - }; - - process.nextTick(function () { - if (envReady && typeof envReady === 'function') { - envReady(server, client); - } - }); -}; - - -/** - * Improves formatting of AssertionError messages to make deepEqual etc more - * readable. - * - * @param {Object} assertion - * @return {Object} - * @api public - */ - -exports.betterErrors = function (assertion) { - if (!assertion.error) return; - - var e = assertion.error; - // deepEqual error message is a bit sucky, lets improve it! - // e.actual and e.expected could be null or undefined, so - // using getOwnPropertyDescriptor to see if they exist: - if (Object.getOwnPropertyDescriptor(e, 'actual') && - Object.getOwnPropertyDescriptor(e, 'expected')) { - - // alexgorbatchev 2010-10-22 :: Added a bit of depth to inspection - var actual = util.inspect(e.actual, false, 10).replace(/\n$/, ''); - var expected = util.inspect(e.expected, false, 10).replace(/\n$/, ''); - var multiline = ( - actual.indexOf('\n') !== -1 || - expected.indexOf('\n') !== -1 - ); - var spacing = (multiline ? '\n' : ' '); - e._message = e.message; - e.stack = ( - e.name + ':' + spacing + - actual + spacing + e.operator + spacing + - expected + '\n' + - e.stack.split('\n').slice(1).join('\n') - ); - } - return assertion; -}; diff --git a/node_modules/mongodb/deps/nodeunit/man1/nodeunit.1 b/node_modules/mongodb/deps/nodeunit/man1/nodeunit.1 deleted file mode 100644 index 450772d..0000000 --- a/node_modules/mongodb/deps/nodeunit/man1/nodeunit.1 +++ /dev/null @@ -1,95 +0,0 @@ -.\" Generated with Ronnjs/v0.1 -.\" http://github.com/kapouer/ronnjs/ -. -.TH "NODEUNIT" "1" "October 2010" "" "" -. -.SH "NAME" -\fBnodeunit\fR \-\- simple node\.js unit testing tool -. -.SH "SYNOPSIS" -. -.nf -nodeunit [options] [ \.\.\.] -. -.fi -. -.SH "DESCRIPTION" -Nodeunit is a simple unit testing tool based on the node\.js assert module\. -. -.IP "\(bu" 4 -Simple to use -. -.IP "\(bu" 4 -Just export the tests from a module -. -.IP "\(bu" 4 -Helps you avoid common pitfalls when testing asynchronous code -. -.IP "\(bu" 4 -Easy to add test cases with setUp and tearDown functions if you wish -. -.IP "\(bu" 4 -Allows the use of mocks and stubs -. -.IP "" 0 -. -.SH "OPTIONS" - \fB\-\-config FILE\fR: -. -.br - Load config options from a JSON file, allows the customisation - of color schemes for the default test reporter etc\. - See bin/nodeunit\.json for current available options\. -. -.P - \fB\-\-reporter FILE\fR: -. -.br - You can set the test reporter to a custom module or on of the modules - in nodeunit/lib/reporters, when omitted, the default test runner is used\. -. -.P - \fB\-\-list\-reporters\fR: -. -.br - List available build\-in reporters\. -. -.P - \fB\-h\fR, \fB\-\-help\fR: -. -.br - Display the help and exit\. -. -.P - \fB\-v\fR, \fB\-\-version\fR: -. -.br - Output version information and exit\. -. -.P - \fB\fR: - You can run nodeunit on specific files or on all \fI*\.js\fR files inside -. -.br - a directory\. -. -.SH "AUTHORS" -Written by Caolan McMahon and other nodeunit contributors\. -. -.br -Contributors list: \fIhttp://github\.com/caolan/nodeunit/contributors\fR\|\. -. -.SH "REPORTING BUGS" -Report nodeunit bugs to \fIhttp://github\.com/caolan/nodeunit/issues\fR\|\. -. -.SH "COPYRIGHT" -Copyright © 2010 Caolan McMahon\. -. -.br -Nodeunit has been released under the MIT license: -. -.br -\fIhttp://github\.com/caolan/nodeunit/raw/master/LICENSE\fR\|\. -. -.SH "SEE ALSO" -node(1) diff --git a/node_modules/mongodb/deps/nodeunit/nodelint.cfg b/node_modules/mongodb/deps/nodeunit/nodelint.cfg deleted file mode 100644 index d6a3aad..0000000 --- a/node_modules/mongodb/deps/nodeunit/nodelint.cfg +++ /dev/null @@ -1,7 +0,0 @@ -//See: http://www.jslint.com/lint.html#options -var options = { - //white: false, // if false, strict whitespace rules should be enforced. - indent: 4, - onevar: false, - vars: true // allow multiple var statement per function. -}; diff --git a/node_modules/mongodb/deps/nodeunit/package.json b/node_modules/mongodb/deps/nodeunit/package.json deleted file mode 100644 index 6a5d86e..0000000 --- a/node_modules/mongodb/deps/nodeunit/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ "name": "nodeunit" -, "description": "Easy unit testing for node.js and the browser." -, "maintainers": - [ { "name": "Caolan McMahon" - , "web": "https://github.com/caolan" - } - ] -, "contributors" : - [ { "name": "Romain Beauxis" - , "web": "https://github.com/toots" - } - , { "name": "Alex Gorbatchev" - , "web": "https://github.com/alexgorbatchev" - } - , { "name": "Alex Wolfe" - , "web": "https://github.com/alexkwolfe" - } - , { "name": "Carl Fürstenberg" - , "web": "https://github.com/azatoth" - } - , { "name": "Gerad Suyderhoud" - , "web": "https://github.com/gerad" - } - , { "name": "Kadir Pekel" - , "web": "https://github.com/coffeemate" - } - , { "name": "Oleg Efimov" - , "web": "https://github.com/Sannis" - } - , { "name": "Orlando Vazquez" - , "web": "https://github.com/orlandov" - } - , { "name": "Ryan Dahl" - , "web": "https://github.com/ry" - } - , { "name": "Sam Stephenson" - , "web": "https://github.com/sstephenson" - } - , { "name": "Thomas Mayfield" - , "web": "https://github.com/thegreatape" - } - , { "name": "Elijah Insua ", - "web": "http://tmpvar.com" - } - ] -, "version": "0.6.4" -, "repository" : - { "type" : "git" - , "url" : "http://github.com/caolan/nodeunit.git" - } -, "devDependencies": - { "uglify-js": ">=1.1.0" } -, "bugs" : { "url" : "http://github.com/caolan/nodeunit/issues" } -, "licenses" : - [ { "type" : "MIT" - , "url" : "http://github.com/caolan/nodeunit/raw/master/LICENSE" - } - ] -, "directories" : { "lib": "./lib", "doc" : "./doc", "man" : "./man1" } -, "bin" : { "nodeunit" : "./bin/nodeunit" } -, "dependencies" : - { "tap-assert": ">=0.0.9" - , "tap-producer": ">=0.0.1" - } -} diff --git a/node_modules/mongodb/deps/nodeunit/share/junit.xml.ejs b/node_modules/mongodb/deps/nodeunit/share/junit.xml.ejs deleted file mode 100644 index c1db5bb..0000000 --- a/node_modules/mongodb/deps/nodeunit/share/junit.xml.ejs +++ /dev/null @@ -1,19 +0,0 @@ - -<% for (var i=0; i < suites.length; i++) { %> - <% var suite=suites[i]; %> - - <% for (var j=0; j < suite.testcases.length; j++) { %> - <% var testcase=suites[i].testcases[j]; %> - - <% if (testcase.failure) { %> - - <% if (testcase.failure.backtrace) { %><%= testcase.failure.backtrace %><% } %> - - <% } %> - - <% } %> - -<% } %> diff --git a/node_modules/mongodb/deps/nodeunit/share/license.js b/node_modules/mongodb/deps/nodeunit/share/license.js deleted file mode 100644 index f0f326f..0000000 --- a/node_modules/mongodb/deps/nodeunit/share/license.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * Nodeunit - * https://github.com/caolan/nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * json2.js - * http://www.JSON.org/json2.js - * Public Domain. - * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - */ diff --git a/node_modules/mongodb/deps/nodeunit/share/nodeunit.css b/node_modules/mongodb/deps/nodeunit/share/nodeunit.css deleted file mode 100644 index 274434a..0000000 --- a/node_modules/mongodb/deps/nodeunit/share/nodeunit.css +++ /dev/null @@ -1,70 +0,0 @@ -/*! - * Styles taken from qunit.css - */ - -h1#nodeunit-header, h1.nodeunit-header { - padding: 15px; - font-size: large; - background-color: #06b; - color: white; - font-family: 'trebuchet ms', verdana, arial; - margin: 0; -} - -h1#nodeunit-header a { - color: white; -} - -h2#nodeunit-banner { - height: 2em; - border-bottom: 1px solid white; - background-color: #eee; - margin: 0; - font-family: 'trebuchet ms', verdana, arial; -} -h2#nodeunit-banner.pass { - background-color: green; -} -h2#nodeunit-banner.fail { - background-color: red; -} - -h2#nodeunit-userAgent, h2.nodeunit-userAgent { - padding: 10px; - background-color: #eee; - color: black; - margin: 0; - font-size: small; - font-weight: normal; - font-family: 'trebuchet ms', verdana, arial; - font-size: 10pt; -} - -div#nodeunit-testrunner-toolbar { - background: #eee; - border-top: 1px solid black; - padding: 10px; - font-family: 'trebuchet ms', verdana, arial; - margin: 0; - font-size: 10pt; -} - -ol#nodeunit-tests { - font-family: 'trebuchet ms', verdana, arial; - font-size: 10pt; -} -ol#nodeunit-tests li strong { - cursor:pointer; -} -ol#nodeunit-tests .pass { - color: green; -} -ol#nodeunit-tests .fail { - color: red; -} - -p#nodeunit-testresult { - margin-left: 1em; - font-size: 10pt; - font-family: 'trebuchet ms', verdana, arial; -} diff --git a/node_modules/mongodb/deps/nodeunit/test/fixtures/coffee/mock_coffee_module.coffee b/node_modules/mongodb/deps/nodeunit/test/fixtures/coffee/mock_coffee_module.coffee deleted file mode 100644 index a1c069b..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/fixtures/coffee/mock_coffee_module.coffee +++ /dev/null @@ -1,4 +0,0 @@ -j = 0 -j += i for i in [0..5] - -exports.name = "mock_coffee_#{j}" diff --git a/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module3.js b/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module3.js deleted file mode 100644 index 3021776..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module3.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module3'; diff --git a/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module4.js b/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module4.js deleted file mode 100644 index 876f9ca..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module4.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module4'; diff --git a/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module1.js b/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module1.js deleted file mode 100644 index 4c093ad..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module1.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module1'; diff --git a/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module2.js b/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module2.js deleted file mode 100644 index a63d012..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module2.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module2'; diff --git a/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode1.js b/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode1.js deleted file mode 100644 index 2ef7115..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode1.js +++ /dev/null @@ -1,3 +0,0 @@ -function hello_world(arg) { - return "_" + arg + "_"; -} diff --git a/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode2.js b/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode2.js deleted file mode 100644 index 55a764e..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode2.js +++ /dev/null @@ -1,3 +0,0 @@ -function get_a_variable() { - return typeof a_variable; -} diff --git a/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode3.js b/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode3.js deleted file mode 100644 index 1fd1e78..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode3.js +++ /dev/null @@ -1 +0,0 @@ -var t=t?t+1:1; diff --git a/node_modules/mongodb/deps/nodeunit/test/test-base.js b/node_modules/mongodb/deps/nodeunit/test/test-base.js deleted file mode 100644 index 64b8c8b..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/test-base.js +++ /dev/null @@ -1,219 +0,0 @@ -/* - * This module is not a plain nodeunit test suite, but instead uses the - * assert module to ensure a basic level of functionality is present, - * allowing the rest of the tests to be written using nodeunit itself. - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var assert = require('assert'), // @REMOVE_LINE_FOR_BROWSER - async = require('../deps/async'), // @REMOVE_LINE_FOR_BROWSER - nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - - -// NOT A TEST - util function to make testing faster. -// retries the assertion until it passes or the timeout is reached, -// at which point it throws the assertion error -var waitFor = function (fn, timeout, callback, start) { - start = start || new Date().getTime(); - callback = callback || function () {}; - try { - fn(); - callback(); - } - catch (e) { - if (e instanceof assert.AssertionError) { - var now = new Date().getTime(); - if (now - start >= timeout) { - throw e; - } - else { - async.nextTick(function () { - waitFor(fn, timeout, callback, start); - }); - } - } - else { - throw e; - } - } -}; - - -// TESTS: - -// Are exported tests actually run? - store completed tests in this variable -// for checking later -var tests_called = {}; - -// most basic test that should run, the tests_called object is tested -// at the end of this module to ensure the tests were actually run by nodeunit -exports.testCalled = function (test) { - tests_called.testCalled = true; - test.done(); -}; - -// generates test functions for nodeunit assertions -var makeTest = function (method, args_pass, args_fail) { - return function (test) { - var test1_called = false; - var test2_called = false; - - // test pass - nodeunit.runTest( - 'testname', - function (test) { - test[method].apply(test, args_pass); - test.done(); - }, - {testDone: function (name, assertions) { - assert.equal(assertions.length, 1); - assert.equal(assertions.failures(), 0); - }}, - function () { - test1_called = true; - } - ); - - // test failure - nodeunit.runTest( - 'testname', - function (test) { - test[method].apply(test, args_fail); - test.done(); - }, - {testDone: function (name, assertions) { - assert.equal(assertions.length, 1); - assert.equal(assertions.failures(), 1); - }}, - function () { - test2_called = true; - } - ); - - // ensure tests were run - waitFor(function () { - assert.ok(test1_called); - assert.ok(test2_called); - tests_called[method] = true; - }, 500, test.done); - }; -}; - -// ensure basic assertions are working: -exports.testOk = makeTest('ok', [true], [false]); -exports.testEquals = makeTest('equals', [1, 1], [1, 2]); -exports.testSame = makeTest('same', - [{test: 'test'}, {test: 'test'}], - [{test: 'test'}, {monkey: 'penguin'}] -); - -// from the assert module: -exports.testEqual = makeTest('equal', [1, 1], [1, 2]); -exports.testNotEqual = makeTest('notEqual', [1, 2], [1, 1]); -exports.testDeepEqual = makeTest('deepEqual', - [{one: 1}, {one: 1}], [{one: 1}, {two: 2}] -); -exports.testNotDeepEqual = makeTest('notDeepEqual', - [{one: 1}, {two: 2}], [{one: 1}, {one: 1}] -); -exports.testStrictEqual = makeTest('strictEqual', [1, 1], [1, true]); -exports.testNotStrictEqual = makeTest('notStrictEqual', [true, 1], [1, 1]); -exports.testThrows = makeTest('throws', - [function () { - throw new Error('test'); - }], - [function () { - return; - }] -); -exports.testDoesNotThrows = makeTest('doesNotThrow', - [function () { - return; - }], - [function () { - throw new Error('test'); - }] -); -exports.testIfError = makeTest('ifError', [false], [new Error('test')]); - - -exports.testExpect = function (test) { - var test1_called = false, - test2_called = false, - test3_called = false; - - // correct number of tests run - nodeunit.runTest( - 'testname', - function (test) { - test.expect(2); - test.ok(true); - test.ok(true); - test.done(); - }, - {testDone: function (name, assertions) { - test.equals(assertions.length, 2); - test.equals(assertions.failures(), 0); - }}, - function () { - test1_called = true; - } - ); - - // no tests run - nodeunit.runTest( - 'testname', - function (test) { - test.expect(2); - test.done(); - }, - {testDone: function (name, assertions) { - test.equals(assertions.length, 1); - test.equals(assertions.failures(), 1); - }}, - function () { - test2_called = true; - } - ); - - // incorrect number of tests run - nodeunit.runTest( - 'testname', - function (test) { - test.expect(2); - test.ok(true); - test.ok(true); - test.ok(true); - test.done(); - }, - {testDone: function (name, assertions) { - test.equals(assertions.length, 4); - test.equals(assertions.failures(), 1); - }}, - function () { - test3_called = true; - } - ); - - // ensure callbacks fired - waitFor(function () { - assert.ok(test1_called); - assert.ok(test2_called); - assert.ok(test3_called); - tests_called.expect = true; - }, 500, test.done); -}; - - -// tests are async, so wait for them to be called -waitFor(function () { - assert.ok(tests_called.testCalled); - assert.ok(tests_called.ok); - assert.ok(tests_called.equals); - assert.ok(tests_called.same); - assert.ok(tests_called.expect); -}, 10000); diff --git a/node_modules/mongodb/deps/nodeunit/test/test-failing-callbacks.js b/node_modules/mongodb/deps/nodeunit/test/test-failing-callbacks.js deleted file mode 100644 index 08f7eb5..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/test-failing-callbacks.js +++ /dev/null @@ -1,114 +0,0 @@ -var nodeunit = require('../lib/nodeunit'); - - -exports.testFailingLog = function (test) { - test.expect(3); - - // this is meant to bubble to the top, and will be ignored for the purposes - // of testing: - var ignored_error = new Error('ignore this callback error'); - var err_handler = function (err) { - if (err && err.message !== ignored_error.message) { - throw err; - } - }; - process.addListener('uncaughtException', err_handler); - - // A failing callback should not affect the test outcome - var testfn = function (test) { - test.ok(true, 'test.ok'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.ok(true, 'log called'); - throw ignored_error; - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'total'); - process.removeListener('uncaughtException', err_handler); - } - }, test.done); -}; - -exports.testFailingTestDone = function (test) { - test.expect(2); - - var ignored_error = new Error('ignore this callback error'); - var err_handler = function (err) { - if (err && err.message !== ignored_error.message) { - throw err; - } - }; - process.addListener('uncaughtException', err_handler); - - // A failing callback should not affect the test outcome - var testfn = function (test) { - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.ok(false, 'log should not be called'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 0, 'total'); - process.nextTick(function () { - process.removeListener('uncaughtException', err_handler); - test.done(); - }); - throw ignored_error; - } - }, function () {}); -}; - -exports.testAssertionObj = function (test) { - test.expect(4); - var testfn = function (test) { - test.ok(true, 'ok true'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.ok(assertion.passed() === true, 'assertion.passed'); - test.ok(assertion.failed() === false, 'assertion.failed'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'total'); - } - }, test.done); -}; - -exports.testLogOptional = function (test) { - test.expect(2); - var testfn = function (test) { - test.ok(true, 'ok true'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'total'); - } - }, test.done); -}; - -exports.testExpectWithFailure = function (test) { - test.expect(3); - var testfn = function (test) { - test.expect(1); - test.ok(false, 'test.ok'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.equals(assertion.method, 'ok', 'assertion.method'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 1, 'failures'); - test.equals(assertions.length, 1, 'total'); - } - }, test.done); -}; diff --git a/node_modules/mongodb/deps/nodeunit/test/test-httputil.js b/node_modules/mongodb/deps/nodeunit/test/test-httputil.js deleted file mode 100644 index e5ee25c..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/test-httputil.js +++ /dev/null @@ -1,55 +0,0 @@ -var nodeunit = require('../lib/nodeunit'); -var httputil = require('../lib/utils').httputil; - -exports.testHttpUtilBasics = function (test) { - - test.expect(6); - - httputil(function (req, resp) { - test.equal(req.method, 'PUT'); - test.equal(req.url, '/newpair'); - test.equal(req.headers.foo, 'bar'); - - resp.writeHead(500, {'content-type': 'text/plain'}); - resp.end('failed'); - }, function (server, client) { - client.fetch('PUT', '/newpair', {'foo': 'bar'}, function (resp) { - test.equal(resp.statusCode, 500); - test.equal(resp.headers['content-type'], 'text/plain'); - test.equal(resp.body, 'failed'); - - server.close(); - test.done(); - }); - }); -}; - -exports.testHttpUtilJsonHandling = function (test) { - - test.expect(9); - - httputil(function (req, resp) { - test.equal(req.method, 'GET'); - test.equal(req.url, '/'); - test.equal(req.headers.foo, 'bar'); - - var testdata = {foo1: 'bar', foo2: 'baz'}; - - resp.writeHead(200, {'content-type': 'application/json'}); - resp.end(JSON.stringify(testdata)); - - }, function (server, client) { - client.fetch('GET', '/', {'foo': 'bar'}, function (resp) { - test.equal(resp.statusCode, 200); - test.equal(resp.headers['content-type'], 'application/json'); - - test.ok(resp.bodyAsObject); - test.equal(typeof resp.bodyAsObject, 'object'); - test.equal(resp.bodyAsObject.foo1, 'bar'); - test.equal(resp.bodyAsObject.foo2, 'baz'); - - server.close(); - test.done(); - }); - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/test/test-runfiles.js b/node_modules/mongodb/deps/nodeunit/test/test-runfiles.js deleted file mode 100644 index ce1a4cd..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/test-runfiles.js +++ /dev/null @@ -1,214 +0,0 @@ -var assert = require('assert'), - fs = require('fs'), - path = require('path'), - nodeunit = require('../lib/nodeunit'); - - -var setup = function (fn) { - return function (test) { - process.chdir(__dirname); - var env = { - mock_module1: require(__dirname + '/fixtures/mock_module1'), - mock_module2: require(__dirname + '/fixtures/mock_module2'), - mock_module3: require(__dirname + '/fixtures/dir/mock_module3'), - mock_module4: require(__dirname + '/fixtures/dir/mock_module4') - }; - fn.call(env, test); - }; -}; - - -exports.testRunFiles = setup(function (test) { - test.expect(24); - var runModule_copy = nodeunit.runModule; - - var runModule_calls = []; - var modules = []; - - var opts = { - moduleStart: function () { - return 'moduleStart'; - }, - testDone: function () { - return 'testDone'; - }, - testStart: function () { - return 'testStart'; - }, - log: function () { - return 'log'; - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 4, 'length'); - test.ok(typeof assertions.duration === "number"); - - var called_with = function (name) { - return runModule_calls.some(function (m) { - return m.name === name; - }); - }; - test.ok(called_with('mock_module1'), 'mock_module1 ran'); - test.ok(called_with('mock_module2'), 'mock_module2 ran'); - test.ok(called_with('mock_module3'), 'mock_module3 ran'); - test.ok(called_with('mock_module4'), 'mock_module4 ran'); - test.equals(runModule_calls.length, 4); - - nodeunit.runModule = runModule_copy; - test.done(); - } - }; - - nodeunit.runModule = function (name, mod, options, callback) { - test.equals(options.testDone, opts.testDone); - test.equals(options.testStart, opts.testStart); - test.equals(options.log, opts.log); - test.ok(typeof name === "string"); - runModule_calls.push(mod); - var m = [{failed: function () { - return false; - }}]; - modules.push(m); - callback(null, m); - }; - - nodeunit.runFiles( - [__dirname + '/fixtures/mock_module1.js', - __dirname + '/fixtures/mock_module2.js', - __dirname + '/fixtures/dir'], - opts - ); -}); - -exports.testRunFilesEmpty = function (test) { - test.expect(3); - nodeunit.runFiles([], { - moduleStart: function () { - test.ok(false, 'should not be called'); - }, - testDone: function () { - test.ok(false, 'should not be called'); - }, - testStart: function () { - test.ok(false, 'should not be called'); - }, - log: function () { - test.ok(false, 'should not be called'); - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 0, 'length'); - test.ok(typeof assertions.duration === "number"); - test.done(); - } - }); -}; - - -exports.testEmptyDir = function (test) { - var dir2 = __dirname + '/fixtures/dir2'; - - // git doesn't like empty directories, so we have to create one - path.exists(dir2, function (exists) { - if (!exists) { - fs.mkdirSync(dir2, 0777); - } - - // runFiles on empty directory: - nodeunit.runFiles([dir2], { - moduleStart: function () { - test.ok(false, 'should not be called'); - }, - testDone: function () { - test.ok(false, 'should not be called'); - }, - testStart: function () { - test.ok(false, 'should not be called'); - }, - log: function () { - test.ok(false, 'should not be called'); - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 0, 'length'); - test.ok(typeof assertions.duration === "number"); - test.done(); - } - }); - }); -}; - - -var CoffeeScript; -try { - CoffeeScript = require('coffee-script'); -} catch (e) { -} - -if (CoffeeScript) { - exports.testCoffeeScript = function (test) { - process.chdir(__dirname); - var env = { - mock_coffee_module: require(__dirname + - '/fixtures/coffee/mock_coffee_module') - }; - - test.expect(9); - var runModule_copy = nodeunit.runModule; - - var runModule_calls = []; - var modules = []; - - var opts = { - moduleStart: function () { - return 'moduleStart'; - }, - testDone: function () { - return 'testDone'; - }, - testStart: function () { - return 'testStart'; - }, - log: function () { - return 'log'; - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'length'); - test.ok(typeof assertions.duration === "number"); - - var called_with = function (name) { - return runModule_calls.some(function (m) { - return m.name === name; - }); - }; - test.ok( - called_with('mock_coffee_15'), - 'mock_coffee_module ran' - ); - test.equals(runModule_calls.length, 1); - - nodeunit.runModule = runModule_copy; - test.done(); - } - }; - - nodeunit.runModule = function (name, mod, options, callback) { - test.equals(options.testDone, opts.testDone); - test.equals(options.testStart, opts.testStart); - test.equals(options.log, opts.log); - test.ok(typeof name === "string"); - runModule_calls.push(mod); - var m = [{failed: function () { - return false; - }}]; - modules.push(m); - callback(null, m); - }; - - nodeunit.runFiles( - [__dirname + 'fixtures/coffee/mock_coffee_module.coffee'], - opts - ); - }; -} diff --git a/node_modules/mongodb/deps/nodeunit/test/test-runmodule.js b/node_modules/mongodb/deps/nodeunit/test/test-runmodule.js deleted file mode 100644 index d07b47c..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/test-runmodule.js +++ /dev/null @@ -1,177 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - - -exports.testRunModule = function (test) { - test.expect(11); - var call_order = []; - var testmodule = { - test1: function (test) { - call_order.push('test1'); - test.ok(true, 'ok true'); - test.done(); - }, - test2: function (test) { - call_order.push('test2'); - test.ok(false, 'ok false'); - test.ok(false, 'ok false'); - test.done(); - }, - test3: function (test) { - call_order.push('test3'); - test.done(); - } - }; - nodeunit.runModule('testmodule', testmodule, { - log: function (assertion) { - call_order.push('log'); - }, - testStart: function (name) { - call_order.push('testStart'); - test.ok( - name.toString() === 'test1' || - name.toString() === 'test2' || - name.toString() === 'test3', - 'testStart called with test name ' - ); - }, - testDone: function (name, assertions) { - call_order.push('testDone'); - test.ok( - name.toString() === 'test1' || - name.toString() === 'test2' || - name.toString() === 'test3', - 'testDone called with test name' - ); - }, - moduleDone: function (name, assertions) { - call_order.push('moduleDone'); - test.equals(assertions.length, 3); - test.equals(assertions.failures(), 2); - test.equals(name, 'testmodule'); - test.ok(typeof assertions.duration === "number"); - test.same(call_order, [ - 'testStart', 'test1', 'log', 'testDone', - 'testStart', 'test2', 'log', 'log', 'testDone', - 'testStart', 'test3', 'testDone', - 'moduleDone' - ]); - } - }, test.done); -}; - - -exports.testRunModuleTestSpec = function (test) { - test.expect(6); - var call_order = []; - var testmodule = { - test1: function (test) { - test.ok(true, 'ok true'); - test.done(); - }, - test2: function (test) { - call_order.push('test2'); - test.ok(false, 'ok false'); - test.ok(false, 'ok false'); - test.done(); - }, - test3: function (test) { - test.done(); - } - }; - nodeunit.runModule('testmodule', testmodule, { - testspec: "test2", - log: function (assertion) { - call_order.push('log'); - }, - testStart: function (name) { - call_order.push('testStart'); - test.ok( - name.toString() === 'test2', - 'testStart called with test name ' - ); - }, - testDone: function (name, assertions) { - call_order.push('testDone'); - test.ok( - name.toString() === 'test2', - 'testDone called with test name' - ); - }, - moduleDone: function (name, assertions) { - call_order.push('moduleDone'); - test.equals(assertions.length, 2); - test.equals(name, 'testmodule'); - test.ok(typeof assertions.duration === "number"); - test.same(call_order, [ - 'testStart', 'test2', 'log', 'log', 'testDone', - 'moduleDone' - ]); - } - }, test.done); -}; - -exports.testRunModuleEmpty = function (test) { - nodeunit.runModule('module with no exports', {}, { - log: function (assertion) { - test.ok(false, 'log should not be called'); - }, - testStart: function (name) { - test.ok(false, 'testStart should not be called'); - }, - testDone: function (name, assertions) { - test.ok(false, 'testDone should not be called'); - }, - moduleDone: function (name, assertions) { - test.equals(assertions.length, 0); - test.equals(assertions.failures(), 0); - test.equals(name, 'module with no exports'); - test.ok(typeof assertions.duration === "number"); - } - }, test.done); -}; - - -exports.testNestedTests = function (test) { - var call_order = []; - var m = { - test1: function (test) { - test.done(); - }, - suite: { - t1: function (test) { - test.done(); - }, - t2: function (test) { - test.done(); - }, - another_suite: { - t3: function (test) { - test.done(); - } - } - } - }; - nodeunit.runModule('modulename', m, { - testStart: function (name) { - call_order.push(['testStart'].concat(name)); - }, - testDone: function (name, assertions) { - call_order.push(['testDone'].concat(name)); - } - }, function () { - test.same(call_order, [ - ['testStart', 'test1'], ['testDone', 'test1'], - ['testStart', 'suite', 't1'], ['testDone', 'suite', 't1'], - ['testStart', 'suite', 't2'], ['testDone', 'suite', 't2'], - ['testStart', 'suite', 'another_suite', 't3'], - ['testDone', 'suite', 'another_suite', 't3'] - ]); - test.done(); - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/test/test-runtest.js b/node_modules/mongodb/deps/nodeunit/test/test-runtest.js deleted file mode 100644 index 8fc3d52..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/test-runtest.js +++ /dev/null @@ -1,46 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - - -exports.testArgs = function (test) { - test.ok(test.expect instanceof Function, 'test.expect'); - test.ok(test.done instanceof Function, 'test.done'); - test.ok(test.ok instanceof Function, 'test.ok'); - test.ok(test.same instanceof Function, 'test.same'); - test.ok(test.equals instanceof Function, 'test.equals'); - test.done(); -}; - -exports.testDoneCallback = function (test) { - test.expect(4); - nodeunit.runTest('testname', exports.testArgs, { - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 5, 'length'); - test.ok(typeof assertions.duration === "number"); - test.equals(name, 'testname'); - } - }, test.done); -}; - -exports.testThrowError = function (test) { - test.expect(3); - var err = new Error('test'); - var testfn = function (test) { - throw err; - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.same(assertion.error, err, 'assertion.error'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 1); - test.equals(assertions.length, 1); - } - }, test.done); -}; diff --git a/node_modules/mongodb/deps/nodeunit/test/test-sandbox.js b/node_modules/mongodb/deps/nodeunit/test/test-sandbox.js deleted file mode 100644 index 1b249d7..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/test-sandbox.js +++ /dev/null @@ -1,31 +0,0 @@ -var nodeunit = require('../lib/nodeunit'); -var sandbox = require('../lib/utils').sandbox; -var testCase = nodeunit.testCase; - -exports.testSimpleSandbox = function (test) { - var raw_jscode1 = sandbox(__dirname + '/fixtures/raw_jscode1.js'); - test.equal(raw_jscode1.hello_world('foo'), '_foo_', 'evaluation ok'); - test.done(); -}; - -exports.testSandboxContext = function (test) { - var a_variable = 42; // should not be visible in the sandbox - var raw_jscode2 = sandbox(__dirname + '/fixtures/raw_jscode2.js'); - a_variable = 42; // again for the win - test.equal( - raw_jscode2.get_a_variable(), - 'undefined', - 'the variable should not be defined' - ); - test.done(); -}; - -exports.testSandboxMultiple = function (test) { - var raw_jscode3 = sandbox([ - __dirname + '/fixtures/raw_jscode3.js', - __dirname + '/fixtures/raw_jscode3.js', - __dirname + '/fixtures/raw_jscode3.js' - ]); - test.equal(raw_jscode3.t, 3, 'two files loaded'); - test.done(); -}; diff --git a/node_modules/mongodb/deps/nodeunit/test/test-testcase-legacy.js b/node_modules/mongodb/deps/nodeunit/test/test-testcase-legacy.js deleted file mode 100644 index 1dfd9a7..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/test-testcase-legacy.js +++ /dev/null @@ -1,257 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER -var testCase = nodeunit.testCase; - -exports.testTestCase = function (test) { - test.expect(7); - var call_order = []; - var s = testCase({ - setUp: function (callback) { - call_order.push('setUp'); - test.equals(this.one, undefined); - this.one = 1; - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - test.ok(true, 'tearDown called'); - callback(); - }, - test1: function (t) { - call_order.push('test1'); - test.equals(this.one, 1); - this.one = 2; - t.done(); - }, - test2: function (t) { - call_order.push('test2'); - test.equals(this.one, 1); - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function () { - test.same(call_order, [ - 'setUp', 'test1', 'tearDown', - 'setUp', 'test2', 'tearDown' - ]); - test.done(); - }); -}; - -exports.tearDownAfterError = function (test) { - test.expect(1); - var s = testCase({ - tearDown: function (callback) { - test.ok(true, 'tearDown called'); - callback(); - }, - test: function (t) { - throw new Error('some error'); - } - }); - nodeunit.runSuite(null, s, {}, function () { - test.done(); - }); -}; - -exports.catchSetUpError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - setUp: function (callback) { - throw test_error; - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.setUpErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - setUp: function (callback) { - callback(test_error); - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.catchTearDownError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - tearDown: function (callback) { - throw test_error; - }, - test: function (t) { - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.tearDownErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - tearDown: function (callback) { - callback(test_error); - }, - test: function (t) { - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.testErrorAndtearDownError = function (test) { - test.expect(3); - var error1 = new Error('test error one'); - var error2 = new Error('test error two'); - var s = testCase({ - tearDown: function (callback) { - callback(error2); - }, - test: function (t) { - t.done(error1); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 2); - test.equal(assertions[0].error, error1); - test.equal(assertions[1].error, error2); - test.done(); - }); -}; - -exports.testCaseGroups = function (test) { - var call_order = []; - var s = testCase({ - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: { - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.test2', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.nestedTestCases = function (test) { - var call_order = []; - var s = testCase({ - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: testCase({ - setUp: function (callback) { - call_order.push('group1.setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('group1.tearDown'); - callback(); - }, - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - }) - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.setUp', - 'group1.test2', - 'group1.tearDown', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.deepNestedTestCases = function (test) { - var val = 'foo'; - var s = testCase({ - setUp: function (callback) { - val = 'bar'; - callback(); - }, - group1: testCase({ - test: testCase({ - test2: function (test) { - test.equal(val, 'bar'); - test.done(); - } - }) - }) - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.ok(!assertions[0].failed()); - test.equal(assertions.length, 1); - test.done(); - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/test/test-testcase.js b/node_modules/mongodb/deps/nodeunit/test/test-testcase.js deleted file mode 100644 index 5d33b0b..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/test-testcase.js +++ /dev/null @@ -1,256 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - -exports.testTestCase = function (test) { - test.expect(7); - var call_order = []; - var s = { - setUp: function (callback) { - call_order.push('setUp'); - test.equals(this.one, undefined, 'in setUp, this.one not set'); - this.one = 1; - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - test.ok(true, 'tearDown called'); - callback(); - }, - test1: function (t) { - call_order.push('test1'); - test.equals(this.one, 1, 'in test1, this.one is 1'); - this.one = 2; - t.done(); - }, - test2: function (t) { - call_order.push('test2'); - test.equals(this.one, 1, 'in test2, this.one is still 1'); - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function () { - test.same(call_order, [ - 'setUp', 'test1', 'tearDown', - 'setUp', 'test2', 'tearDown' - ]); - test.done(); - }); -}; - -exports.tearDownAfterError = function (test) { - test.expect(1); - var s = { - tearDown: function (callback) { - test.ok(true, 'tearDown called'); - callback(); - }, - test: function (t) { - throw new Error('some error'); - } - }; - nodeunit.runSuite(null, s, {}, function () { - test.done(); - }); -}; - -exports.catchSetUpError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - setUp: function (callback) { - throw test_error; - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.setUpErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - setUp: function (callback) { - callback(test_error); - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.catchTearDownError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - tearDown: function (callback) { - throw test_error; - }, - test: function (t) { - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.tearDownErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - tearDown: function (callback) { - callback(test_error); - }, - test: function (t) { - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.testErrorAndtearDownError = function (test) { - test.expect(3); - var error1 = new Error('test error one'); - var error2 = new Error('test error two'); - var s = { - tearDown: function (callback) { - callback(error2); - }, - test: function (t) { - t.done(error1); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 2); - test.equal(assertions[0].error, error1); - test.equal(assertions[1].error, error2); - test.done(); - }); -}; - -exports.testCaseGroups = function (test) { - var call_order = []; - var s = { - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: { - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.test2', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.nestedTestCases = function (test) { - var call_order = []; - var s = { - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: { - setUp: function (callback) { - call_order.push('group1.setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('group1.tearDown'); - callback(); - }, - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.setUp', - 'group1.test2', - 'group1.tearDown', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.deepNestedTestCases = function (test) { - var val = 'foo'; - var s = { - setUp: function (callback) { - val = 'bar'; - callback(); - }, - group1: { - test: { - test2: function (test) { - test.equal(val, 'bar'); - test.done(); - } - } - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.ok(!assertions[0].failed()); - test.equal(assertions.length, 1); - test.done(); - }); -}; diff --git a/node_modules/mongodb/deps/nodeunit/test/test.html b/node_modules/mongodb/deps/nodeunit/test/test.html deleted file mode 100644 index e0826de..0000000 --- a/node_modules/mongodb/deps/nodeunit/test/test.html +++ /dev/null @@ -1,28 +0,0 @@ - - - Nodeunit Test Suite - - - - - - - - - - -

Nodeunit Test Suite

- - - diff --git a/node_modules/mongodb/deps/step/README.markdown b/node_modules/mongodb/deps/step/README.markdown deleted file mode 100644 index abf1f2b..0000000 --- a/node_modules/mongodb/deps/step/README.markdown +++ /dev/null @@ -1,71 +0,0 @@ -# Step - -A simple control-flow library for node.JS that makes parallel execution, serial execution, and error handling painless. - -## How to install - -Simply copy or link the lib/step.js file into your `$HOME/.node_libraries` folder. - -## How to use - -The step library exports a single function I call `Step`. It accepts any number of functions as arguments and runs them in serial order using the passed in `this` context as the callback to the next step. - - Step( - function readSelf() { - fs.readFile(__filename, this); - }, - function capitalize(err, text) { - if (err) throw err; - return text.toUpperCase(); - }, - function showIt(err, newText) { - if (err) throw err; - console.log(newText); - } - ); - -Notice that we pass in `this` as the callback to `fs.readFile`. When the file read completes, step will send the result as the arguments to the next function in the chain. Then in the `capitalize` function we're doing synchronous work so we can simple return the new value and Step will route it as if we called the callback. - -The first parameter is reserved for errors since this is the node standard. Also any exceptions thrown are caught and passed as the first argument to the next function. As long as you don't nest callback functions inline your main functions this prevents there from ever being any uncaught exceptions. This is very important for long running node.JS servers since a single uncaught exception can bring the whole server down. - -Also there is support for parallel actions: - - Step( - // Loads two files in parallel - function loadStuff() { - fs.readFile(__filename, this.parallel()); - fs.readFile("/etc/passwd", this.parallel()); - }, - // Show the result when done - function showStuff(err, code, users) { - if (err) throw err; - sys.puts(code); - sys.puts(users); - } - ) - -Here we pass `this.parallel()` instead of `this` as the callback. It internally keeps track of the number of callbacks issued and preserves their order then giving the result to the next step after all have finished. If there is an error in any of the parallel actions, it will be passed as the first argument to the next step. - -Also you can use group with a dynamic number of common tasks. - - Step( - function readDir() { - fs.readdir(__dirname, this); - }, - function readFiles(err, results) { - if (err) throw err; - // Create a new group - var group = this.group(); - results.forEach(function (filename) { - if (/\.js$/.test(filename)) { - fs.readFile(__dirname + "/" + filename, 'utf8', group()); - } - }); - }, - function showAll(err , files) { - if (err) throw err; - sys.p(files); - } - ); - -*Note* that we both call `this.group()` and `group()`. The first reserves a slot in the parameters of the next step, then calling `group()` generates the individual callbacks and increments the internal counter. diff --git a/node_modules/mongodb/deps/step/lib/step.js b/node_modules/mongodb/deps/step/lib/step.js deleted file mode 100644 index 546c14d..0000000 --- a/node_modules/mongodb/deps/step/lib/step.js +++ /dev/null @@ -1,154 +0,0 @@ -/* -Copyright (c) 2011 Tim Caswell - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -// Inspired by http://github.com/willconant/flow-js, but reimplemented and -// modified to fit my taste and the node.JS error handling system. -function Step() { - var steps = Array.prototype.slice.call(arguments), - pending, counter, results, lock; - - // Define the main callback that's given as `this` to the steps. - function next() { - - // Check if there are no steps left - if (steps.length === 0) { - // Throw uncaught errors - if (arguments[0]) { - throw arguments[0]; - } - return; - } - - // Get the next step to execute - var fn = steps.shift(); - counter = pending = 0; - results = []; - - // Run the step in a try..catch block so exceptions don't get out of hand. - try { - lock = true; - var result = fn.apply(next, arguments); - } catch (e) { - // Pass any exceptions on through the next callback - next(e); - } - - - // If a syncronous return is used, pass it to the callback - if (result !== undefined) { - next(undefined, result); - } - lock = false; - } - - // Add a special callback generator `this.parallel()` that groups stuff. - next.parallel = function () { - var index = 1 + counter++; - pending++; - - function check() { - if (pending === 0) { - // When they're all done, call the callback - next.apply(null, results); - } - } - process.nextTick(check); // Ensures that check is called at least once - - return function () { - pending--; - // Compress the error from any result to the first argument - if (arguments[0]) { - results[0] = arguments[0]; - } - // Send the other results as arguments - results[index] = arguments[1]; - if (!lock) { check(); } - }; - }; - - // Generates a callback generator for grouped results - next.group = function () { - var localCallback = next.parallel(); - var counter = 0; - var pending = 0; - var result = []; - var error = undefined; - - function check() { - if (pending === 0) { - // When group is done, call the callback - localCallback(error, result); - } - } - process.nextTick(check); // Ensures that check is called at least once - - // Generates a callback for the group - return function () { - var index = counter++; - pending++; - return function () { - pending--; - // Compress the error from any result to the first argument - if (arguments[0]) { - error = arguments[0]; - } - // Send the other results as arguments - result[index] = arguments[1]; - if (!lock) { check(); } - }; - }; - }; - - // Start the engine an pass nothing to the first step. - next(); -} - -// Tack on leading and tailing steps for input and output and return -// the whole thing as a function. Basically turns step calls into function -// factories. -Step.fn = function StepFn() { - var steps = Array.prototype.slice.call(arguments); - return function () { - var args = Array.prototype.slice.call(arguments); - - // Insert a first step that primes the data stream - var toRun = [function () { - this.apply(null, args); - }].concat(steps); - - // If the last arg is a function add it as a last step - if (typeof args[args.length-1] === 'function') { - toRun.push(args.pop()); - } - - - Step.apply(null, toRun); - } -} - - -// Hook into commonJS module systems -if (typeof module !== 'undefined' && "exports" in module) { - module.exports = Step; -} diff --git a/node_modules/mongodb/deps/step/package.json b/node_modules/mongodb/deps/step/package.json deleted file mode 100644 index 062ace0..0000000 --- a/node_modules/mongodb/deps/step/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ "name": "step", - "version": "0.0.4", - "description": "A simple control-flow library for node.JS that makes parallel execution, serial execution, and error handling painless.", - "engine": [ "node >=0.2.0" ], - "author": "Tim Caswell ", - "repository": - { "type" : "git", - "url" : "http://github.com/creationix/step.git" - }, - "main": "lib/step" -} diff --git a/node_modules/mongodb/deps/step/test/callbackTest.js b/node_modules/mongodb/deps/step/test/callbackTest.js deleted file mode 100644 index 2fc2351..0000000 --- a/node_modules/mongodb/deps/step/test/callbackTest.js +++ /dev/null @@ -1,26 +0,0 @@ -require('./helper'); - -var selfText = fs.readFileSync(__filename, 'utf8'); - -// This example tests passing async results and sync results to the next layer - -expect('one'); -expect('two'); -expect('three'); -Step( - function readSelf() { - fulfill("one"); - fs.readFile(__filename, 'utf8', this); - }, - function capitalize(err, text) { - fulfill("two"); - if (err) throw err; - assert.equal(selfText, text, "Text Loaded"); - return text.toUpperCase(); - }, - function showIt(err, newText) { - fulfill("three"); - if (err) throw err; - assert.equal(selfText.toUpperCase(), newText, "Text Uppercased"); - } -); diff --git a/node_modules/mongodb/deps/step/test/errorTest.js b/node_modules/mongodb/deps/step/test/errorTest.js deleted file mode 100644 index 30af683..0000000 --- a/node_modules/mongodb/deps/step/test/errorTest.js +++ /dev/null @@ -1,27 +0,0 @@ -require('./helper'); - -var exception = new Error('Catch me!'); - -expect('one'); -expect('timeout'); -expect('two'); -expect('three'); -Step( - function () { - fulfill('one'); - var callback = this; - setTimeout(function () { - fulfill('timeout'); - callback(exception); - }, 0); - }, - function (err) { - fulfill('two'); - assert.equal(exception, err, "error should passed through"); - throw exception; - }, - function (err) { - fulfill('three'); - assert.equal(exception, err, "error should be caught"); - } -); diff --git a/node_modules/mongodb/deps/step/test/fnTest.js b/node_modules/mongodb/deps/step/test/fnTest.js deleted file mode 100644 index 1964a35..0000000 --- a/node_modules/mongodb/deps/step/test/fnTest.js +++ /dev/null @@ -1,21 +0,0 @@ -require('./helper'); - - -var myfn = Step.fn( - function (name) { - fs.readFile(name, 'utf8', this); - }, - function capitalize(err, text) { - if (err) throw err; - return text.toUpperCase(); - } -); - -var selfText = fs.readFileSync(__filename, 'utf8'); - -expect('result'); -myfn(__filename, function (err, result) { - fulfill('result'); - if (err) throw err; - assert.equal(selfText.toUpperCase(), result, "It should work"); -}); diff --git a/node_modules/mongodb/deps/step/test/groupTest.js b/node_modules/mongodb/deps/step/test/groupTest.js deleted file mode 100644 index c1124ab..0000000 --- a/node_modules/mongodb/deps/step/test/groupTest.js +++ /dev/null @@ -1,102 +0,0 @@ -require('./helper'); - -var dirListing = fs.readdirSync(__dirname), - dirResults = dirListing.map(function (filename) { - return fs.readFileSync(__dirname + "/" + filename, 'utf8'); - }); - -expect('one'); -expect('two'); -expect('three'); -Step( - function readDir() { - fulfill('one'); - fs.readdir(__dirname, this); - }, - function readFiles(err, results) { - fulfill('two'); - if (err) throw err; - // Create a new group - assert.deepEqual(dirListing, results); - var group = this.group(); - results.forEach(function (filename) { - if (/\.js$/.test(filename)) { - fs.readFile(__dirname + "/" + filename, 'utf8', group()); - } - }); - }, - function showAll(err , files) { - fulfill('three'); - if (err) throw err; - assert.deepEqual(dirResults, files); - } -); - -expect('four'); -expect('five'); -// When the group is empty, it should fire with an empty array -Step( - function start() { - var group = this.group(); - fulfill('four'); - }, - function readFiles(err, results) { - if (err) throw err; - fulfill('five'); - assert.deepEqual(results, []); - } -); - -// Test lock functionality with N sized groups -expect("test3: 1"); -expect("test3: 1,2,3"); -expect("test3: 2"); -Step( - function() { - return 1; - }, - function makeGroup(err, num) { - if(err) throw err; - fulfill("test3: " + num); - var group = this.group(); - - setTimeout((function(callback) { return function() { callback(null, 1); } })(group()), 100); - group()(null, 2); - setTimeout((function(callback) { return function() { callback(null, 3); } })(group()), 0); - }, - function groupResults(err, results) { - if(err) throw err; - fulfill("test3: " + results); - return 2 - }, - function terminate(err, num) { - if(err) throw err; - fulfill("test3: " + num); - } -); - -// Test lock functionality with zero sized groups -expect("test4: 1"); -expect("test4: empty array"); -expect("test4: group of zero terminated"); -expect("test4: 2"); -Step( - function() { - return 1; - }, - function makeGroup(err, num) { - if(err) throw err; - fulfill("test4: " + num); - this.group(); - }, - function groupResults(err, results) { - if(err) throw err; - if(results.length === 0) { fulfill("test4: empty array"); } - fulfill('test4: group of zero terminated'); - return 2 - }, - function terminate(err, num) { - if(err) throw err; - fulfill("test4: " + num); - } -); \ No newline at end of file diff --git a/node_modules/mongodb/deps/step/test/helper.js b/node_modules/mongodb/deps/step/test/helper.js deleted file mode 100644 index bd4ca8e..0000000 --- a/node_modules/mongodb/deps/step/test/helper.js +++ /dev/null @@ -1,17 +0,0 @@ -global.assert = require('assert'); -global.fs = require('fs'); -global.Step = require('../lib/step'); - -// A mini expectations module to ensure expected callback fire at all. -var expectations = {}; -global.expect = function expect(message) { - expectations[message] = new Error("Missing expectation: " + message); -} -global.fulfill = function fulfill(message) { - delete expectations[message]; -} -process.addListener('exit', function () { - Object.keys(expectations).forEach(function (message) { - throw expectations[message]; - }); -}); diff --git a/node_modules/mongodb/deps/step/test/parallelTest.js b/node_modules/mongodb/deps/step/test/parallelTest.js deleted file mode 100644 index baba74e..0000000 --- a/node_modules/mongodb/deps/step/test/parallelTest.js +++ /dev/null @@ -1,49 +0,0 @@ -require('./helper'); - -var selfText = fs.readFileSync(__filename, 'utf8'), - etcText = fs.readFileSync('/etc/passwd', 'utf8'); - -expect('one'); -expect('two'); -Step( - // Loads two files in parallel - function loadStuff() { - fulfill('one'); - fs.readFile(__filename, this.parallel()); - fs.readFile("/etc/passwd", this.parallel()); - }, - // Show the result when done - function showStuff(err, code, users) { - fulfill('two'); - if (err) throw err; - assert.equal(selfText, code, "Code should come first"); - assert.equal(etcText, users, "Users should come second"); - } -); - -// Test lock functionality with N parallel calls -expect("test2: 1"); -expect("test2: 1,2,3"); -expect("test2: 2"); -Step( - function() { - return 1; - }, - function makeParallelCalls(err, num) { - if(err) throw err; - fulfill("test2: " + num); - - setTimeout((function(callback) { return function() { callback(null, 1); } })(this.parallel()), 100); - this.parallel()(null, 2); - setTimeout((function(callback) { return function() { callback(null, 3); } })(this.parallel()), 0); - }, - function parallelResults(err, one, two, three) { - if(err) throw err; - fulfill("test2: " + [one, two, three]); - return 2 - }, - function terminate(err, num) { - if(err) throw err; - fulfill("test2: " + num); - } -) \ No newline at end of file diff --git a/node_modules/mongodb/dev/benchmark/bson_benchmark.js b/node_modules/mongodb/dev/benchmark/bson_benchmark.js deleted file mode 100644 index 884f9ea..0000000 --- a/node_modules/mongodb/dev/benchmark/bson_benchmark.js +++ /dev/null @@ -1,86 +0,0 @@ -var BSON = require('../lib/mongodb').BSONNative.BSON, - ObjectID = require('../lib/mongodb').BSONNative.ObjectID, - Code = require('../lib/mongodb').BSONNative.Code, - Long = require('../lib/mongodb').BSONNative.Long, - Binary = require('../lib/mongodb').BSONNative.Binary, - debug = require('util').debug, - inspect = require('util').inspect; - -// var BSON = require('../lib/mongodb').BSONPure.BSON, -// ObjectID = require('../lib/mongodb').BSONPure.ObjectID, -// Code = require('../lib/mongodb').BSONPure.Code, -// Long = require('../lib/mongodb').BSONPure.Long, -// Binary = require('../lib/mongodb').BSONPure.Binary; - -var COUNT = 1000; -var COUNT = 100; - -var object = { - string: "Strings are great", - decimal: 3.14159265, - bool: true, - integer: 5, - long: Long.fromNumber(100), - bin: new Binary(), - - subObject: { - moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", - longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin." - }, - - subArray: [1,2,3,4,5,6,7,8,9,10], - anotherString: "another string", - code: new Code("function() {}", {i:1}) -} - -// Number of objects -var numberOfObjects = 100; -// var numberOfObjects = 2; - -// Object serialized -objectBSON = BSON.serialize(object, null, true) - -// Buffer With copies of the objectBSON -var data = new Buffer(objectBSON.length * numberOfObjects); -var index = 0; - -// Copy the buffer 1000 times to create a strea m of objects -for(var i = 0; i < numberOfObjects; i++) { - // Copy data - objectBSON.copy(data, index); - // Adjust index - index = index + objectBSON.length; -} - -// console.log("-----------------------------------------------------------------------------------") -// console.dir(objectBSON) - -var x, start, end, j -var objectBSON, objectJSON - -// Allocate the return array (avoid concatinating everything) -var results = new Array(numberOfObjects); - -console.log(COUNT + "x (objectBSON = BSON.serialize(object))") -start = new Date - -// var objects = BSON.deserializeStream(data, 0, numberOfObjects); -// console.log("----------------------------------------------------------------------------------- 0") -// var objects = BSON.deserialize(data); -// console.log("----------------------------------------------------------------------------------- 1") -// console.dir(objects) - -for (j=COUNT; --j>=0; ) { - var nextIndex = BSON.deserializeStream(data, 0, numberOfObjects, results, 0); -} - -end = new Date -var opsprsecond = COUNT / ((end - start)/1000); -console.log("bson size (bytes): ", objectBSON.length); -console.log("time = ", end - start, "ms -", COUNT / ((end - start)/1000), " ops/sec"); -console.log("MB/s = " + ((opsprsecond*objectBSON.length)/1024)); - -// console.dir(nextIndex) -// console.dir(results) - - diff --git a/node_modules/mongodb/dev/benchmark/bson_buffalo_benchmark.js b/node_modules/mongodb/dev/benchmark/bson_buffalo_benchmark.js deleted file mode 100644 index 43848b2..0000000 --- a/node_modules/mongodb/dev/benchmark/bson_buffalo_benchmark.js +++ /dev/null @@ -1,299 +0,0 @@ -var BSON = require('/Users/christiankvalheim/coding/checkout/node-buffalo/buffalo') -var mongoNative = require('../lib/mongodb'), - assert = require('assert'), - Long = require('../lib/mongodb/bson/long').Long, - ObjectID = require('../lib/mongodb/bson/bson').ObjectID, - Binary = require('../lib/mongodb/bson/bson').Binary, - Code = require('../lib/mongodb/bson/bson').Code, - DBRef = require('../lib/mongodb/bson/bson').DBRef, - Symbol = require('../lib/mongodb/bson/bson').Symbol, - Double = require('../lib/mongodb/bson/bson').Double, - MaxKey = require('../lib/mongodb/bson/bson').MaxKey, - MinKey = require('../lib/mongodb/bson/bson').MinKey, - Timestamp = require('../lib/mongodb/bson/bson').Timestamp; - -var BSONPure = new mongoNative.BSONPure.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]); -var BSONNative = new mongoNative.BSONNative.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]); - -var COUNT = 100000 -// var COUNT = 20000 -// var COUNT = 10000 -// var COUNT = 1 - -// Function with scope -var function2 = function() {}; -function2.scope = {a:1}; - -// var COUNT = 1 -var object = { - string: "Strings are great", - decimal: 3.14159265, - 'undefined': undefined, - bool: true, - integer: 5, - regexp:/fdfdfd/, - // regexp:/fdfdfd/mig, - subObject: { - moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", - longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin.", - - subObject: { - moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", - longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin.", - }, - }, - date: new Date(), - code: function() {}, - function2: function2, - buffer:new Buffer('hello world'), - 'null': null, - subArray: [1,2,3,4,5,6,7,8,9,10], - anotherString: "another string" -} - -// var object2 = { -// string: "Strings are great", -// obj: { -// string2: "This is String 2", -// }, -// -// decimal: 3.14159265, -// 'undefined': undefined, -// bool: true, -// integer: 5, -// regexp:/fdfdfd/mig, -// regexp:/fdfdfd/, -// subObject: { -// moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", -// longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin.", -// -// subObject: { -// moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", -// longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin." -// } -// }, -// dbref: new DBRef('collection', new ObjectID(), 'db'), -// long: Long.fromNumber(1000), -// double: new Double(3.14), -// code1: new Code((function() {}).toString(), {a:1}), -// code: new Code((function() {}).toString()), -// minKey: new MinKey(), -// maxKey: new MaxKey(), -// objectId: new ObjectID(), -// binary: new Binary('hello world'), -// symbol: new Symbol('hello'), -// timestamp: Timestamp.fromNumber(1000), -// date: new Date(), -// function1: function() {}, -// function2: function2, -// buffer:new Buffer('hello world'), -// 'null': null, -// subArray: [1,2,3,4,5,6,7,8,9,10], -// anotherString: "another string" -// } -// -// var object2 = { -// cursorId: Long.fromString("3688496768165567218"), -// } - -// Serialize the object -var serializedDoc = BSONPure.serialize(object, null, true); - -// Read a test doc -// var bufferData = require('fs').readFileSync("/Users/christiankvalheim/coding/projects/node-mongodb-native/1325633340440_18.txt", 'ascii'); -// Serialized doc -// var serializedDoc = new Buffer(bufferData, 'hex'); - -// console.dir(serializedDoc) -// var index = 0; -// var binary_reply = serializedDoc; -// -// console.log("---------------------------------------------------------") -// while(index < serializedDoc.length) { -// // Read the size of the bson object -// var bsonObjectSize = binary_reply[index] | binary_reply[index + 1] << 8 | binary_reply[index + 2] << 16 | binary_reply[index + 3] << 24; -// // var d_doc = BSONNative.deserialize(binary_reply.slice(index, index + bsonObjectSize)); -// var d_doc = BSONPure.deserialize(binary_reply.slice(index, index + bsonObjectSize)); -// console.dir(d_doc); -// index = index + bsonObjectSize; -// } -// -// Deserialize the object -// var d_doc = BSONPure.deserialize2(serializedDoc, {evalFunctions:true, cacheFunctions:true}); -// var d_doc = BSONPure.deserialize(serializedDoc); -// var d_doc = BSONNative.deserialize(serializedDoc); -// -// console.log("---------------------------------------------------------") -// console.dir(d_doc); -// return - -// Warm up the method -for(var i = 0 ; i < COUNT; i++) { - BSONPure.deserialize(serializedDoc); - BSON.parse(serializedDoc); - BSONNative.deserialize(serializedDoc); -} - -// var object2 = { authenticate: 1, -// user: 'admin', -// nonce: '2e8e9e9533db3dae', -// key: 'e75fea840d9f52bab39903b011898b8f' } -// -// var object2 = {'name' : 'child', 'parent' : new DBRef("test_resave_dbref", new ObjectID())} -// -// var object2 = {'doc': {'doc2': new Code('this.a > i', {i:1})}}; -// // var object2 = {'doc2': new Code('this.a > i', {i:1})}; -// var object2 = {'doc': {'doc2': new Code('this.a > i', {})}}; -// -// var object3 = { -// // function2: new Code((function() {}).toString(), {a:1}), -// // function1: new Code((function() {}).toString()), -// } - -// // object2 = object; -// var x, start, end, i -// var serializedBSON, serializedBSONPure, serializedBSONNative, serializedJSON -// var deserializedBSON, deserializedBSONPure, deserializedBSONNative, deserializedJSON -// -// for (i=COUNT; --i>=0; ) { -// calculate1 = BSON.calculate(object) -// // calculate2 = BSONPure.calculateObjectSize(object2, true) -// calculate3 = BSONPure.calculateObjectSize2(object2, true) -// calculate4 = BSONNative.calculateObjectSize(object2) -// } -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// calculate1 = BSON.calculate(object) -// } -// end = new Date -// console.log(COUNT + "x buffalo.calculate(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// calculate2 = BSONPure.calculateObjectSize2(object, true) -// } -// end = new Date -// console.log(COUNT + "x BSONPure.calculateObjectSize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// calculate3 = BSONPure.calculateObjectSize2(object2) -// } -// end = new Date -// console.log(COUNT + "x BSONPure.calculateObjectSize2(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// -// console.log("==================================================================") -// console.dir("BSON.calculate :: " + calculate1) -// // console.dir("BSONPure.calculateObjectSize :: " + calculate2) -// console.dir("BSONPure.calculateObjectSize2 :: " + calculate3) -// console.dir("BSONNative.calculateObjectSize :: " + calculate4) - -// console.log("========================================================== serialize") -// console.log("BSON.serialize :: ") -// console.dir(BSON.serialize(object).toString('hex')) -// console.log("BSONPure.serialize2 :: ") -// console.dir(BSONPure.serialize2(object2, null, true).toString('hex')) -// console.dir(BSONPure.serialize2(object2, null, true).toString('ascii')) -// console.log("BSONPure.serialize :: ") -// console.dir(BSONPure.serialize(object, null, true).toString('hex')) -// console.log("BSONNative.serialize :: ") -// console.dir(BSONNative.serialize(object2, null, true).toString('hex')) -// console.dir(BSONNative.serialize(object2, null, true).toString('ascii')) - -// // Serialize -// var a = BSONPure.serialize(object2, null, true); -// var b = BSONNative.serialize(object2, null, true); -// -// console.log("==================================== check") -// for(var i = 0; i < b.length; i++) { -// console.log("[" + a[i] + "] = [" + b[i] + "] :: " + (a[i] === b[i] ? 'true' : "FALSE FALSE FALSE")); -// } -// -// assert.equal(BSONNative.serialize(object2, null, true).toString('hex'), -// BSONPure.serialize2(object2, null, true).toString('hex')) -// -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// serializedBSON = BSON.serialize(object) -// } -// end = new Date -// console.log(COUNT + "x buffalo.serialize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// serializedBSONPure = BSONPure.serialize2(object, null, true) -// } -// end = new Date -// console.log(COUNT + "x mongodb.BSONPure.serialize2(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -// start = new Date -// for (i=COUNT; --i>=0; ) { -// serializedBSONPure = BSONPure.serialize(object, null, true) -// } -// end = new Date -// console.log(COUNT + "x mongodb.BSONPure.serialize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// if (BSONNative) { -// start = new Date -// for (i=COUNT; --i>=0; ) { -// serializedBSONNative = BSONNative.serialize(object, null, true) -// } -// end = new Date -// console.log(COUNT + "x mongodb.BSONNative.serialize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// } -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// serializedJSON = JSON.stringify(object) -// } -// end = new Date -// console.log(COUNT + "x JSON.stringify(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -// start = new Date -// for (i=COUNT; --i>=0; ) { -// deserializedBSONPure = BSONPure.deserialize2(serializedDoc) -// } -// end = new Date -// console.log(COUNT + "x mongodb.BSONPure.deserialize2(buffer) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -start = new Date -for (i=COUNT; --i>=0; ) { - deserializedBSON = BSON.parse(serializedDoc) -} -end = new Date -console.log(COUNT + "x buffalo.parse(buffer) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -if (BSONNative) { - start = new Date - for (i=COUNT; --i>=0; ) { - deserializedBSONNative = BSONNative.deserialize(serializedDoc) - } - end = new Date - console.log(COUNT + "x mongodb.BSONNative.deserialize(buffer) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -} - -start = new Date -for (i=COUNT; --i>=0; ) { - deserializedBSONPure = BSONPure.deserialize(serializedDoc) -} -end = new Date -console.log(COUNT + "x mongodb.BSONPure.deserialize(buffer) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -console.log("---------------------------------------------------------") -console.dir(deserializedBSON) -console.dir(deserializedBSONNative) -console.dir(deserializedBSONPure) - -function compare(b1, b2) { - try { - require('assert').deepEqual(b1,b2) - return true - } catch (e) { - console.error(e) - return false - } -} diff --git a/node_modules/mongodb/dev/benchmark/bson_native_benchmark.js b/node_modules/mongodb/dev/benchmark/bson_native_benchmark.js deleted file mode 100644 index 09d6afd..0000000 --- a/node_modules/mongodb/dev/benchmark/bson_native_benchmark.js +++ /dev/null @@ -1,112 +0,0 @@ -var BSON = require('/Users/christiankvalheim/coding/checkout/node-buffalo/buffalo') -var mongoNative = require('../lib/mongodb'), - assert = require('assert'), - Long = require('../lib/mongodb/bson/long').Long, - ObjectID = require('../lib/mongodb/bson/bson').ObjectID, - Binary = require('../lib/mongodb/bson/bson').Binary, - Code = require('../lib/mongodb/bson/bson').Code, - DBRef = require('../lib/mongodb/bson/bson').DBRef, - Symbol = require('../lib/mongodb/bson/bson').Symbol, - Double = require('../lib/mongodb/bson/bson').Double, - MaxKey = require('../lib/mongodb/bson/bson').MaxKey, - MinKey = require('../lib/mongodb/bson/bson').MinKey, - Timestamp = require('../lib/mongodb/bson/bson').Timestamp; - -var BSONPure = new mongoNative.BSONPure.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]); -var BSONNative = new mongoNative.BSONNative.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]); - -var COUNT = 500000 -// var COUNT = 100000 -// var COUNT = 20000 -// var COUNT = 10000 -// var COUNT = 1 - -// Function with scope -var function2 = function() {}; -function2.scope = {a:1}; - -var object = { - string: "Strings are great", - // obj: { - // string2: "This is String 2", - // }, - // - // decimal: 3.14159265, - // 'undefined': undefined, - // bool: true, - // integer: 5, - // regexp:/fdfdfd/mig, - // regexp:/fdfdfd/, - // subObject: { - // moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", - // longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin.", - // - // subObject: { - // moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", - // longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin." - // } - // }, - // dbref: new DBRef('collection', new ObjectID(), 'db'), - // long: Long.fromNumber(1000), - // double: new Double(3.14), - // code1: new Code((function() {}).toString(), {a:1}), - // code: new Code((function() {}).toString()), - // minKey: new MinKey(), - // maxKey: new MaxKey(), - // objectId: new ObjectID(), - // binary: new Binary('hello world'), - // symbol: new Symbol('hello'), - // timestamp: Timestamp.fromNumber(1000), - // date: new Date(), - // function1: function() {}, - // function2: function2, - // buffer:new Buffer('hello world'), - // 'null': null, - // subArray: [1,2,3,4,5,6,7,8,9,10], - // anotherString: "another string" -} - -var start = new Date -for (i=COUNT; --i>=0; ) { - // calculate1 = BSONPure.calculateObjectSize(object, true); - serialize1 = BSONPure.serialize(object, null, true) -} -var end = new Date -console.log(COUNT + "x BSONPure.calculateObjectSize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -start = new Date -for (i=COUNT; --i>=0; ) { - // calculate2 = BSONNative.calculateObjectSize(object, true); - serialize2 = BSONNative.serialize(object, null, true) -} -end = new Date -console.log(COUNT + "x BSONNative.calculateObjectSize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - - -start = new Date -for (i=COUNT; --i>=0; ) { - // calculate3 = BSONNative.calculateObjectSize2(object) - serialize3 = BSONNative.serialize2(object, null, true) -} -end = new Date -console.log(COUNT + "x BSONNative.calculateObjectSize2(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -// console.log("----------------------------------------------------------------------- size"); -// console.log("calculate1 = " + calculate1); -// console.log("calculate2 = " + calculate2); -// console.log("calculate3 = " + calculate3); - -console.log("----------------------------------------------------------------------- serialize"); -console.log(serialize1.toString('hex')) -console.log(serialize2.toString('hex')) -console.log(serialize3.toString('hex')) - -function compare(b1, b2) { - try { - require('assert').deepEqual(b1,b2) - return true - } catch (e) { - console.error(e) - return false - } -} diff --git a/node_modules/mongodb/dev/benchmark/emit_benchmark.js b/node_modules/mongodb/dev/benchmark/emit_benchmark.js deleted file mode 100644 index aa365de..0000000 --- a/node_modules/mongodb/dev/benchmark/emit_benchmark.js +++ /dev/null @@ -1,49 +0,0 @@ -var debug = require('util').debug, - inspect = require('util').inspect, - inherits = require('util').inherits, - net = require('net'), - EventEmitter = require("events").EventEmitter; - -var COUNT = 1000000; - -var Emitter = function() { -} - -inherits(Emitter, EventEmitter); - -Emitter.prototype.start = function() { - for(var i = 0; i < COUNT; i++) { - this.emit("data", "============================================== data") - } -} - -Emitter.prototype.start2 = function(callback) { - for(var i = 0; i < COUNT; i++) { - callback(null, "============================================== data") - } -} - -// Create test object -var emitObj = new Emitter(); -emitObj.on("data", function(data) { -}) - -console.log(COUNT + "x (objectBSON = BSON.serialize(object))") -start = new Date - -emitObj.start(); - -end = new Date -console.log("time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - - -console.log(COUNT + "x (objectBSON = BSON.serialize(object))") -start = new Date - -emitObj.start2(function(err, data) { - // debug(data) -}); - -end = new Date -console.log("time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - diff --git a/node_modules/mongodb/dev/benchmark/grid_fs_write_benchmark.js b/node_modules/mongodb/dev/benchmark/grid_fs_write_benchmark.js deleted file mode 100644 index ae454f2..0000000 --- a/node_modules/mongodb/dev/benchmark/grid_fs_write_benchmark.js +++ /dev/null @@ -1,25 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Server = require('../lib/mongodb').Server, - ObjectID = require('../lib/mongodb').ObjectID, - GridStore = require('../lib/mongodb').GridStore; - -var simulated_buffer = new Buffer(1024*1000*10).toString(); - -new Db('grid_fs_write_benchmark', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {}).open(function(err, new_client) { - new_client.dropDatabase(function(err, result) { - new_client.close(); - - for(var i = 0; i < 1; i++) { - new Db('grid_fs_write_benchmark', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {}).open(function(err, client) { - var gridStore = new GridStore(client, "foobar" + i, "w"); - gridStore.open(function(err, gridStore) { - gridStore.write(simulated_buffer.toString(), function(err, gridStore) { - gridStore.close(function(err, result) { - client.close(); - }); - }); - }); - }); - } - }) -}); diff --git a/node_modules/mongodb/dev/benchmark/gridfs_benchmark.js b/node_modules/mongodb/dev/benchmark/gridfs_benchmark.js deleted file mode 100644 index 23d7aa5..0000000 --- a/node_modules/mongodb/dev/benchmark/gridfs_benchmark.js +++ /dev/null @@ -1,104 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Server = require('../lib/mongodb').Server, - ObjectID = require('../lib/mongodb').ObjectID, - GridStore = require('../lib/mongodb').GridStore; - -var Mongolian = require('mongolian'); -var COUNT = 1000; -var currentWritingIndex = 0; -var server = new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:1, native_parser:true}); - -// Read in the test file -var fileData = require('fs').readFileSync("./test/gridstore/iya_logo_final_bw.jpg"); - -// ------------------------------------------------------------------------------ -// TEST MONGODB NATIVE -// ------------------------------------------------------------------------------ -// Open a db for the file -new Db('gridfs_benchmark', server, {}).open(function(err, new_client) { - new_client.dropDatabase(function(err, result) { - new_client.close(); - - new Db('gridfs_benchmark', server, {}).open(function(err, client) { - // Start Time - var startTime = new Date().getTime(); - - // Iterate COUNT times writing file to gridfs - for(var i = 0; i < COUNT; i++) { - var gridStore = new GridStore(client, "foobar" + i, "w"); - gridStore.open(function(err, gridStore) { - gridStore.writeBuffer(fileData, true, function(err, gridStore) { - // Update current write index - currentWritingIndex = currentWritingIndex + 1; - - // finish up - if(currentWritingIndex >= COUNT) { - // Start Time - var endTime = new Date().getTime(); - var totalTime = (endTime - startTime); - var msPerOperation = totalTime/COUNT; - var operationsPrSecond = 1000/msPerOperation; - var bytesPrSecond = Math.floor(fileData.length * operationsPrSecond); - var mbsPrSecond = (bytesPrSecond/1024)/1024 ; - - console.log("-------------------------------------------------- DONE NATIVE") - console.log("total time ms :: " + totalTime); - console.log("ms pr operation :: " + msPerOperation); - console.log("operations pr second :: " + operationsPrSecond); - console.log("bytes pr second :: " + bytesPrSecond); - console.log("MB pr second :: " + mbsPrSecond); - // Close db - client.close(); - // Execute mongolian test - executeMongolianTest(); - } - }) - }); - } - }); - }) -}); - -// ------------------------------------------------------------------------------ -// TEST MONGODB NATIVE -// ------------------------------------------------------------------------------ -var executeMongolianTest = function() { - var db = new Mongolian('mongo://localhost/mongolian_test', { log:false }) - var gridfs = db.gridfs('testfs') - - // Number of executed operations - var currentWritingIndexM = 0; - // Start Time - var startTime = new Date().getTime(); - - // Execute Mongolian Count times writing data - for(var i = 0; i < COUNT; i++) { - var stream = gridfs.create('foo' + i).writeStream(); - stream.on('close', function() { - currentWritingIndexM = currentWritingIndexM + 1; - - if(currentWritingIndexM >= COUNT) { - // Start Time - var endTime = new Date().getTime(); - var totalTime = (endTime - startTime); - var msPerOperation = totalTime/COUNT; - var operationsPrSecond = 1000/msPerOperation; - var bytesPrSecond = Math.floor(fileData.length * operationsPrSecond); - var mbsPrSecond = (bytesPrSecond/1024)/1024 ; - - console.log("-------------------------------------------------- DONE MONGOLIAN") - console.log("total time ms :: " + totalTime); - console.log("ms pr operation :: " + msPerOperation); - console.log("operations pr second :: " + operationsPrSecond); - console.log("bytes pr second :: " + bytesPrSecond); - console.log("MB pr second :: " + mbsPrSecond); - - // Close connection - db.server.close() - } - }); - - // Write file - stream.end(fileData); - } -} diff --git a/node_modules/mongodb/dev/benchmark/hammer.js b/node_modules/mongodb/dev/benchmark/hammer.js deleted file mode 100644 index fa8d533..0000000 --- a/node_modules/mongodb/dev/benchmark/hammer.js +++ /dev/null @@ -1,143 +0,0 @@ -var BSON = require('../../lib/mongodb').BSONNative.BSON, - ObjectID = require('../../lib/mongodb').BSONNative.ObjectID, - Code = require('../../lib/mongodb').BSONNative.Code, - debug = require('util').debug, - inspect = require('util').inspect, - mongodb = require('../../lib/mongodb'), - Db = mongodb.Db, - Server = mongodb.Server, - Step = require("../../deps/step/lib/step"); - -var BSON = require('../../lib/mongodb').BSONPure.BSON, - ObjectID = require('../../lib/mongodb').BSONPure.ObjectID; - -// Open the db connection -new Db('hammer_db', new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: false}).open(function(err, db) { - db.dropCollection('hammer_collection', function(err, result) { - db.admin().authenticate('admin', 'admin', function(err, result) { - var i = 0; - // Fire random command - setInterval(function() { - var command = Math.round(Math.random() * 4); - // command = 1; - - // debug("================= execute :: " + i++ + " = " + command) - - // Execute the command - if(command == 1) { - // Execute an insert - db.collection('hammer_collection', function(err, collection) { - collection.insert(randomDoc(), {safe:false}, function(err, result) { - debug("---------------------------------------- INSERT") - }); - }); - } else if(command == 2) { - // Update some random record - db.collection('hammer_collection', function(err, collection) { - collection.findOne({}, function(err, item) { - if(!err && item != null) { - // Grab key before we bork it - var _id = item._id; - var keys = Object.keys(item); - var objLength = keys.length; - var pickRandomItem = Math.round(Math.random() * objLength); - // Show a random doc in - item[keys[pickRandomItem]] = randomDoc(); - // Update doc - collection.update({'_id':_id}, item, {safe:false}, function(err, result) { - debug("---------------------------------------- UPDATE") - }); - } - }) - }); - } else if(command == 3) { - // Update some random record - db.collection('hammer_collection', function(err, collection) { - collection.findOne({}, function(err, item) { - if(!err && item != null) { - // Update doc - collection.remove({'_id':item._id}, {safe:false}, function(err, result) { - debug("---------------------------------------- REMOVE") - }); - } - }) - }); - } else if(command == 4) { - db.collection('hammer_collection', function(err, collection) { - collection.find().limit(100).toArray(function(err, items) { - debug("---------------------------------------- QUERY :: " + items.length) - }) - }) - } - }, 0); - }) - }); -}); - -// -// Create a random document -var randomDoc = function() { - var numberOfElements = Math.round(Math.random() * 100); - var object = {}; - - for(var i = 0; i< numberOfElements; i++) { - // Pick an element and add it - var element = Math.round(Math.random() * 4); - var name = randomName(); - - if(element == 1) { - object[name] = randomString(); - } else if(element == 2) { - object[name] = Math.round(Math.random() * 4294967295); - } else if(element == 3) { - object[name] = Math.round(Math.random() * -4294967295); - } else if(element == 4) { - - } - } - - return object; -} - -// -// Create a random name -var randomName = function() { - var numberOfElements = Math.round(Math.random() * 250); - var buffer = new Buffer(numberOfElements); - - for(var i = 0; i< numberOfElements; i++) { - buffer[i] = 97 + Math.round(Math.random() * (122-97)); - } - - return buffer.toString(); -} - -// -// Create a random string -var randomString = function() { - var numberOfElements = Math.round(Math.random() * 250); - var buffer = new Buffer(numberOfElements); - - for(var i = 0; i< numberOfElements; i++) { - buffer[i] = Math.round(Math.random() * 255); - } - - return buffer.toString(); -} - - - - - - - - - - - - - - - - - diff --git a/node_modules/mongodb/dev/benchmark/hammer_replicaset.js b/node_modules/mongodb/dev/benchmark/hammer_replicaset.js deleted file mode 100644 index fc2d038..0000000 --- a/node_modules/mongodb/dev/benchmark/hammer_replicaset.js +++ /dev/null @@ -1,197 +0,0 @@ -var BSON = require('../../lib/mongodb').BSONNative.BSON, - ObjectID = require('../../lib/mongodb').BSONNative.ObjectID, - Code = require('../../lib/mongodb').BSONNative.Code, - debug = require('util').debug, - inspect = require('util').inspect, - mongodb = require('../../lib/mongodb'), - Db = mongodb.Db, - Server = mongodb.Server, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager, - Step = require("../../deps/step/lib/step"); - -var BSON = require('../../lib/mongodb').BSONPure.BSON, - ObjectID = require('../../lib/mongodb').BSONPure.ObjectID; - -var db = null; -var poolSize = 1; -var RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true, poolSize: poolSize } ), - // new Server( RS.host, RS.ports[0], { auto_reconnect: true, poolSize: poolSize } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true, poolSize: poolSize } ) - ], - {rs_name:RS.name, readPreference:Server.READ_SECONDARY, poolSize: poolSize} - ); - - // Open the db connection - new Db('hammer_db', replSet, {native_parser: false, retryMiliSeconds: 1000}).open(function(err, p_db) { - db = p_db; - if(err != null) throw err; - // Start hammering - hammerTime(); - }); -}); - -// Hammer the set -var hammerTime = function() { - db.dropCollection('hammer_collection', function(err, result) { - var i = 0; - // Fire random command - setInterval(function() { - var command = Math.round(Math.random() * 4); - // command = 2; - - debug("================= execute :: " + i++ + " = " + command) - - // Execute the command - if(command == 1) { - // Execute an insert - db.collection('hammer_collection', function(err, collection) { - collection.insert(randomDoc(), {safe:false}, function(err, result) { - debug("---------------------------------------- INSERT ") - debug(inspect(err)) - }); - }); - } else if(command == 2) { - // Update some random record - db.collection('hammer_collection', function(err, collection) { - // console.log("================================================================== update :: 0") - if(err != null) { - console.log("------------------------------------- error update 1") - console.dir(err) - } - - collection.findOne({}, function(err, item) { - if(err == null && item != null) { - // console.log("================================================================== update :: 1") - // Grab key before we bork it - var _id = item._id; - var keys = Object.keys(item); - var objLength = keys.length; - var pickRandomItem = Math.round(Math.random() * objLength); - // Show a random doc in - item[keys[pickRandomItem]] = randomDoc(); - // Update doc - collection.update({'_id':_id}, item, {safe:false}, function(err, result) { - debug("---------------------------------------- UPDATE") - }); - } else { - console.log("------------------------------------- error update 2") - console.dir(err) - } - }) - }); - } else if(command == 3) { - // Update some random record - db.collection('hammer_collection', function(err, collection) { - // if(err != null) { - // console.log("------------------------------------- error remove 1") - // console.dir(err) - // } - - collection.findOne({}, function(err, item) { - // debug(inspect(err)) - // debug(inspect(item)) - - if(err == null && item != null) { - // Update doc - collection.remove({'_id':item._id}, {safe:false}, function(err, result) { - debug("---------------------------------------- REMOVE") - }); - } else { - // console.log("------------------------------------- error remove 2") - // console.dir(err) - } - }) - }); - } else if(command == 4) { - db.collection('hammer_collection', function(err, collection) { - // if(err != null) { - // console.log("------------------------------------- error query 1") - // console.dir(err) - // } - - collection.find().limit(100).toArray(function(err, items) { - if(err != null) { - console.log("------------------------------------- error query 2") - console.dir(err) - } else { - debug("---------------------------------------- QUERY :: " + items.length) - } - }) - }) - } - }, 100); - }); -} - -// -// Create a random document -var randomDoc = function() { - var numberOfElements = Math.round(Math.random() * 100); - var object = {}; - - for(var i = 0; i< numberOfElements; i++) { - // Pick an element and add it - var element = Math.round(Math.random() * 4); - var name = randomName(); - - if(element == 1) { - object[name] = randomString(); - } else if(element == 2) { - object[name] = Math.round(Math.random() * 4294967295); - } else if(element == 3) { - object[name] = Math.round(Math.random() * -4294967295); - } else if(element == 4) { - - } - } - - return object; -} - -// -// Create a random name -var randomName = function() { - var numberOfElements = Math.round(Math.random() * 250); - var buffer = new Buffer(numberOfElements); - - for(var i = 0; i< numberOfElements; i++) { - buffer[i] = 97 + Math.round(Math.random() * (122-97)); - } - - return buffer.toString(); -} - -// -// Create a random string -var randomString = function() { - var numberOfElements = Math.round(Math.random() * 250); - var buffer = new Buffer(numberOfElements); - - for(var i = 0; i< numberOfElements; i++) { - buffer[i] = Math.round(Math.random() * 255); - } - - return buffer.toString(); -} - - - - - - - - - - - - - - - - - diff --git a/node_modules/mongodb/dev/benchmark/streaming_benchmark.js b/node_modules/mongodb/dev/benchmark/streaming_benchmark.js deleted file mode 100644 index 44014da..0000000 --- a/node_modules/mongodb/dev/benchmark/streaming_benchmark.js +++ /dev/null @@ -1,43 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Server = require('../lib/mongodb').Server, - Cursor = require('../lib/mongodb').Cursor, - Collection = require('../lib/mongodb').Collection, - sys = require('util'), - debug = require('util').debug, - inspect = require('util').inspect; - -var parser = require('../lib/mongodb').BSONPure; -var objectID = require('../lib/mongodb').ObjectID; - -var db = new Db('streaming_benchmark', new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:4}), {}) -// Open the db -db.open(function(err, client) { - client.collection('streaming_benchmark', function(err, collection) { - collection.remove({}, function(err, result) { - // Benchmark - var started_at = new Date().getTime(); - // Add documents - for(var i = 0; i < 100000; i++) { - // for(var i = 0; i < 10000; i++) { - collection.save({'i':i, 'a':i, 'c':i, 'd':{'i':i}}, function(err, result){}); - } - sys.puts("save recs: " + ((new Date().getTime() - started_at)/1000) + "seconds"); - - // Benchmark - var started_at = new Date().getTime(); - var count = 0; - collection.find(function(err, cursor) { - var stream = cursor.streamRecords(function(er,item) {}); - stream.addListener('end', function() { - client.close(); - }); - stream.addListener('data',function(data){ - if(count == 0) started_at = new Date().getTime(); - count++; - if ((count%10000)==0) sys.puts("recs:" + count + " :: " + - ((new Date().getTime() - started_at)/10000) + "seconds"); - }); - }); - }) - }) -}); \ No newline at end of file diff --git a/node_modules/mongodb/dev/harness/memory_leak_harness.js b/node_modules/mongodb/dev/harness/memory_leak_harness.js deleted file mode 100644 index e61ba73..0000000 --- a/node_modules/mongodb/dev/harness/memory_leak_harness.js +++ /dev/null @@ -1,46 +0,0 @@ -var http = require('http'), - Server = require('../lib/mongodb').Server, - ObjectID = require('../lib/mongodb').ObjectID, - Db = require('../lib/mongodb').Db; - -// Set up the mongodb instance -var db = new Db('memory_leak_harness', new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser:false}); - -// Set up http server -var server = http.createServer(); -server.on('request', function(request, response) { - // Fetch the url - var url = request.url; - - // Switch on the url - if(url === "/findAndModify") { - findAndModifyCommand(request, response); - } else { - response.end('Command not supported'); - } -}) - -// Open the db connection -db.open(function(err, db) { - server.listen(8080, '127.0.0.1'); -}); - -// Find And Modify Command -var findAndModifyCommand = function(request, response) { - // Perform an insert and the modify that one - var objectId = new ObjectID(); - // Fetch collection and insert document then modify it - db.createCollection('findAndModify', function(err, collection) { - collection.insert({_id:objectId, a:1, b:true, date:new Date()}, {safe:true}, function(err, result) { - if(err != null) { - response.end("findAndModifyCommand ERROR :: " + err.toString()); - return; - } - - // Perform the modifyAndModify - collection.findAndModify({_id:objectId}, [['_id', 1]], {'$set':{'a':2}}, {'new':true, safe:true}, function(err, updated_doc) { - response.end("findAndModifyCommand SUCCESS :: " + JSON.stringify(updated_doc)); - }); - }) - }); -} \ No newline at end of file diff --git a/node_modules/mongodb/dev/tools/build-docs.js b/node_modules/mongodb/dev/tools/build-docs.js deleted file mode 100644 index c44d29c..0000000 --- a/node_modules/mongodb/dev/tools/build-docs.js +++ /dev/null @@ -1,162 +0,0 @@ -var fs = require('fs'), - dox = require('dox'), - parseJS = require('uglify-js').parser, - ejs = require('ejs'), - exec = require('child_process').exec, - format = require('util').format, - format = require('util').format, - docs = require('./docs'); - -// ---------------------------------------------------------------------------- -// INITALIZE -// ---------------------------------------------------------------------------- -// All source files for the api generation -var apiClasses = [ - {tag:"admin", path:"./lib/mongodb/admin.js"}, - {tag:"collection", path:"./lib/mongodb/collection.js"}, - {tag:"db", path:"./lib/mongodb/db.js"}, - {tag:"cursor", path:"./lib/mongodb/cursor.js"}, - {tag:"cursorstream", path:"./lib/mongodb/cursorstream.js"}, - {tag:"gridstore", path:"./lib/mongodb/gridfs/gridstore.js"}, - {tag:"readstream", path:"./lib/mongodb/gridfs/readstream.js"}, - {tag:"grid", path:"./lib/mongodb/gridfs/grid.js"} - ]; - -// All test files -var testClasses = [ - {path:"./test/admin_test.js"}, - {path:"./test/objectid_test.js"}, - {path:"./test/insert_test.js"}, - {path:"./test/remove_test.js"}, - {path:"./test/collection_test.js"}, - {path:"./test/db_test.js"}, - {path:"./test/find_test.js"}, - {path:"./test/map_reduce_test.js"}, - {path:"./test/index_test.js"}, - {path:"./test/geo_search_test.js"}, - {path:"./test/replicaset/connect_test.js"}, - {path:"./test/connect_test.js"}, - {path:"./test/multiple_dbs_on_connection_pool_test.js"}, - {path:"./test/cursor_test.js"}, - {path:"./test/cursorstream_test.js"}, - {path:"./test/gridstore/grid_store_test.js"}, - {path:"./test/gridstore/grid_store_file_test.js"}, - {path:"./test/gridstore/grid_store_stream_test.js"}, - {path:"./test/gridstore/readstream_test.js"}, - {path:"./test/gridstore/grid_test.js"}, - {path:"./test/bson_types_test.js"}, - {path:"./test/bson/bson_test.js"} - ] - -// Read all the templates -var templates = [ - {tag:'index', path:'./dev/tools/doc-templates/index.ejs'}, - {tag:'changelog', path:'./dev/tools/doc-templates/changelog.ejs'}, - {tag:'index_no_header', path:'./dev/tools/doc-templates/index_no_header.ejs'}, - {tag:'class', path:'./dev/tools/doc-templates/class.ejs'}, - {tag:'function', path:'./dev/tools/doc-templates/function.ejs'} -] - -// Output directory -var outputDirectory = "./docs/sphinx-docs/source/api-generated" - -// Force create the directory for the generated docs -exec('rm -rf ' + outputDirectory, function (error, stdout, stderr) {}); -exec('mkdir ' + outputDirectory, function (error, stdout, stderr) {}); - -// ---------------------------------------------------------------------------- -// PROCESS Driver API -// ---------------------------------------------------------------------------- -// Extract meta data from source files -var dataObjects = docs.extractLibraryMetaData(apiClasses); -// Filter out and prepare the test Objects hash -var testObjects = docs.buildTestHash(docs.extractLibraryMetaData(testClasses)); -// Read all the templates -var templates = docs.readAllTemplates(templates); -// Render all the classes that are decorated -docs.renderAllTemplates(outputDirectory, templates, dataObjects, testObjects, {index_title:'Driver API'}); - -// ---------------------------------------------------------------------------- -// PROCESS BSON API -// ---------------------------------------------------------------------------- -// Output directory -var outputDirectory2 = "./docs/sphinx-docs/source/api-bson-generated" -// Force create the directory for the generated docs -exec('rm -rf ' + outputDirectory2, function (error, stdout, stderr) {}); -exec('mkdir ' + outputDirectory2, function (error, stdout, stderr) {}); - -var apiClasses2 = [ - {tag:"objectid", path:"./lib/mongodb/bson/objectid.js"}, - {tag:"binary", path:"./lib/mongodb/bson/binary.js"}, - {tag:"code", path:"./lib/mongodb/bson/code.js"}, - {tag:"code", path:"./lib/mongodb/bson/db_ref.js"}, - {tag:"double", path:"./lib/mongodb/bson/double.js"}, - {tag:"minkey", path:"./lib/mongodb/bson/min_key.js"}, - {tag:"maxkey", path:"./lib/mongodb/bson/max_key.js"}, - {tag:"symbol", path:"./lib/mongodb/bson/symbol.js"}, - {tag:"timestamp", path:"./lib/mongodb/bson/timestamp.js"}, - {tag:"long", path:"./lib/mongodb/bson/long.js"}, - {tag:"bson", path:"./lib/mongodb/bson/bson.js"} - ]; - -// Read all the templates -var templates2 = [ - {tag:'index', path:'./dev/tools/doc-templates/index.ejs'}, - {tag:'changelog', path:'./dev/tools/doc-templates/changelog.ejs'}, - {tag:'index_no_header', path:'./dev/tools/doc-templates/index_no_header.ejs'}, - {tag:'class', path:'./dev/tools/doc-templates/class.ejs'}, - {tag:'function', path:'./dev/tools/doc-templates/function.ejs'} -] - -// Extract meta data from source files -var dataObjects2 = docs.extractLibraryMetaData(apiClasses2); -// Filter out and prepare the test Objects hash -var testObjects2 = docs.buildTestHash(docs.extractLibraryMetaData(testClasses)); -// Render all the classes that are decorated -docs.renderAllTemplates(outputDirectory2, templates, dataObjects2, testObjects2, {index_title:'Binary JSON API'}); - -// ---------------------------------------------------------------------------- -// PROCESS MARKDOWN DOCUMENTS TO STRUCTURED TEXT -// ---------------------------------------------------------------------------- - -// Transform the tutorials -var articles = [ - {name:"NodeKOArticle1", output:"NodeKOArticle1.rst", path:"./docs/articles/NodeKOArticle1.md"}, - {name:"NodeKOArticle2", output:"NodeKOArticle2.rst", path:"./docs/articles/NodeKOArticle2.md"} - ]; -// Tranform the markdown to restructured text -docs.writeMarkDownFile("./docs/sphinx-docs/source/api-articles", articles, templates, - {title:'Articles', template:'index'}); - -// Transform the tutorials -var articles = [ - {name:"collections", output:"collections.rst", path:"./docs/collections.md"}, - {name:"database", output:"database.rst", path:"./docs/database.md"}, - {name:"gridfs", output:"gridfs.rst", path:"./docs/gridfs.md"}, - {name:"indexes", output:"indexes.rst", path:"./docs/indexes.md"}, - {name:"insert", output:"insert.rst", path:"./docs/insert.md"}, - {name:"queries", output:"queries.rst", path:"./docs/queries.md"}, - {name:"replicaset", output:"replicaset.rst", path:"./docs/replicaset.md"}, - ]; -// Tranform the markdown to restructured text -docs.writeMarkDownFile("./docs/sphinx-docs/source/markdown-docs", articles, templates, - {title:'Using the driver', template:'index_no_header'}); - -// ---------------------------------------------------------------------------- -// WRITE CHANGELOG TO THE DOCUMENTATION -// ---------------------------------------------------------------------------- - -// Outputdiectory -var outputDirectory = "./docs/sphinx-docs/source/changelog"; -// Force create the directory for the generated docs -exec('rm -rf ' + outputDirectory, function (error, stdout, stderr) {}); -exec('mkdir ' + outputDirectory, function (error, stdout, stderr) { - // Read the changelog - var changelog = fs.readFileSync('./HISTORY').toString(); - // Just write out the index - var content = ejs.render(templates["changelog"], {content:changelog}); - // Write it out - fs.writeFileSync(format("%s/changelog.rst", outputDirectory), content); -}); - - diff --git a/node_modules/mongodb/dev/tools/doc-templates/changelog.ejs b/node_modules/mongodb/dev/tools/doc-templates/changelog.ejs deleted file mode 100644 index 54626d1..0000000 --- a/node_modules/mongodb/dev/tools/doc-templates/changelog.ejs +++ /dev/null @@ -1,5 +0,0 @@ -========= -Changelog -========= - -<%= content %> \ No newline at end of file diff --git a/node_modules/mongodb/dev/tools/doc-templates/class.ejs b/node_modules/mongodb/dev/tools/doc-templates/class.ejs deleted file mode 100644 index 333b0f8..0000000 --- a/node_modules/mongodb/dev/tools/doc-templates/class.ejs +++ /dev/null @@ -1,317 +0,0 @@ -<% -for(var i = 0; i < entries.length; i++) { - if(isClass(entries[i].tags)) { - - } -} - -var addLine = function(char, length) { - var chars = []; - for(var i = 0; i < length; i++) chars[i] = char; - return chars.join(''); -} - -// Contains the current class name -var className = null; - -for(var i = 0; i < entries.length; i++) { - if(isClass(entries[i].tags)) { - var _name = entries[i].ctx.string.trim(); - - %><%= format("%s\n%s\n%s\n", addLine("=", _name.length), _name, addLine("=", _name.length)) %><% - className = entries[i].ctx.string.replace("()", ""); - - %><%= format("\n------------------\nConstructor\n------------------\n") %><% - - // Get full description and clean it - var fullDescription = entries[i].description.summary; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/strong\>/g, "**") - .replace(/\|\<\/em\>/g, "*") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - %><%- format("%s\n\n", fullDescription) %><% - %><%= format("\n .. js:class:: %s\n\n", entries[i].ctx.string) %><% - - for(var ti = 0; ti < entries[i].tags.length; ti++) { - // Get the current tag - var tag = entries[i].tags[ti]; - // If we have a parameter render it - if(tag.type == 'param') { - // Unpack the tag - var type = tag.types[0].toLowerCase(); - var name = tag.name; - var description = tag.description; - // Render the parameter - %><%= format(" :param %s %s: %s\n", type, name, description) %><% - } else if(tag.type == 'return') { - // Unpack the tag - var type = tag.types[0].toLowerCase(); - var description = tag.description; - // Render the parameter - %><%= format(" :returns: %s %s\n", type, description) %><% - } - } - - // Get full description and clean it - var fullDescription = entries[i].description.body; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/strong\>/g, "**") - .replace(/\|\<\/em\>/g, "*") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - %><%- format("%s\n\n", fullDescription) %><% - } -} - -for(var i = 0; i < entries.length; i++) { - if(isClassConstant(entries[i])) { - %><%= format("\n------------------\nConstants\n------------------\n") %><% -%> -.. csv-table:: - :header: "Constant Name", "Value", "Description" - :widths: 15, 10, 30 - -<% - break; - } -} - -for(var i = 0; i < entries.length; i++) { - if(isClassConstant(entries[i])) { - // Extract values - var attributeName = format("%s = %s;", entries[i].ctx.string, entries[i].ctx.value); - var getterSetters = []; - var type = ""; - - // Get full description and clean it - var fullDescription = entries[i].description.full; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - - // Write out the class definition row - %><%- format(" \"%s\", \"%s\", \"%s\"\n", entries[i].ctx.string.trim(), entries[i].ctx.value.trim(), fullDescription.trim()) %><% - } -} - -for(var i = 0; i < entries.length; i++) { - if(isProperty(entries[i])) { - %><%= format("\n------------------\nProperties\n------------------\n") %><% - break; - } -} - -for(var i = 0; i < entries.length; i++) { - if(isProperty(entries[i])) { - // Extract values - var attributeName = ""; - var getterSetters = []; - var type = ""; - - // Loop over all tags - for(var ti = 0; ti < entries[i].tags.length; ti++) { - if(entries[i].tags[ti].type == 'field') attributeName = entries[i].tags[ti].string; - if(entries[i].tags[ti].type == 'getter') getterSetters.push("Getter"); - if(entries[i].tags[ti].type == 'setter') getterSetters.push("Setter"); - if(entries[i].tags[ti].type == 'type') type = entries[i].tags[ti].types[0].toLowerCase(); - } - - // Get full description and clean it - var fullDescription = entries[i].description.full; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - - // Write out the text - %><%- format("%s\n\n", fullDescription) %><% - %><%= format(".. js:attribute:: %s %s [%s]\n\n", attributeName, type, getterSetters.join("|")) %><% - - // If we have examples render them - if(examples != null && examples[attributeName]) { - %><%= format("\n**Examples**\n\n") %><% - var examplesArray = examples[attributeName]; - // Iterate over all the examples - for(var ei = 0; ei < examplesArray.length; ei++) { - // Fetch an example - var example = examplesArray[ei]; - var code = example.code; - code = code.replace(", ssl:useSSL", "") - .replace("native_parser: native_parser", "native_parser: false") - .replace(/test\.ok/g, "assert.ok") - .replace(/test\.equal/g, "assert.equal") - .replace(/test\.deepEqual/g, "assert.deepEqual") - .replace(/\n[ |\t]*test\.done\(\)\;/, ""); - - // Split and adjust code - var codeLines = code.split(/\n/); - for(var ci = 0; ci < codeLines.length; ci++) { - codeLines[ci] = " " + codeLines[ci]; - } - - var fullDescription = example.description.full; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - - // Split up and move - var fullDescriptionLines = fullDescription.split(/\n/); - for(var ci = 0; ci < fullDescriptionLines.length; ci++) { - fullDescriptionLines[ci] = " " + fullDescriptionLines[ci]; - } - - // Starting template Lines - var startingTemplateLines = [ - " var Db = require('mongodb').Db,", - " Server = require('mongodb').Server,", - " ReplSetServers = require('mongodb').ReplSetServers,", - " ObjectID = require('mongodb').ObjectID,", - " Binary = require('mongodb').Binary,", - " GridStore = require('mongodb').GridStore,", - " Code = require('mongodb').Code,", - " BSON = require('mongodb').pure().BSON,", - " assert = require('assert');\n\n" - ]; - - // Let's render it - %><%- format("%s\n\n", fullDescriptionLines.join("\n")) %><% - %><%- format(" .. code-block:: javascript\n\n%s%s\n\n", startingTemplateLines.join("\n"), codeLines.join("\n")) %><% - } - } - } -} - -for(var i = 0; i < entries.length; i++) { - // If it's a function parse it - if(isFunction(entries[i])) { - var paramsStrings = []; - var paramNames = []; - - for(var ti = 0; ti < entries[i].tags.length; ti++) { - // Get the current tag - var tag = entries[i].tags[ti]; - // If we have a parameter render it - if(tag.type == 'param') { - // Unpack the tag - var type = tag.types[0].toLowerCase(); - var name = tag.name; - var description = tag.description; - // Add to list of params - paramNames.push(name); - // Render the parameter - paramsStrings.push(format(" :param %s %s: %s\n", type, name, description)); - } else if(tag.type == 'return') { - // Unpack the tag - var type = tag.types[0].toLowerCase(); - var description = tag.description; - // Render the parameter - paramsStrings.push(format(" :returns: %s %s\n\n", type, description)); - } - } - - // Reformat any optional parameters from ,[] to [,] - var paramsString = paramNames.join(", ").replace(/\, \[/, "[, "); - // Write out the methods - var fullDescription = entries[i].description.full; - - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/strong\>/g, "**") - .replace(/\|\<\/em\>/g, "*") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - - // The name of examples - var examplesName = entries[i].ctx.name; - - // Write header depending on if it's class or instance level - if(entries[i].ctx.receiver != null) { - // Change examples Name to include class name - var examplesName = format("%s.%s", className, entries[i].ctx.name); - var _length = format("%s.%s", className, entries[i].ctx.name).length; - %><%= format("\n%s\n%s.%s\n%s\n", addLine("-", _length), className, entries[i].ctx.name, addLine("-", _length)) %><% - %><%- format("%s\n\n", fullDescription) %><% - %><%= format(".. js:function:: %s.%s(%s)\n\n", className, entries[i].ctx.name, paramsString) %><% - } else { - var _length = entries[i].ctx.name.length; - %><%= format("\n%s\n%s\n%s\n", addLine("-", _length), entries[i].ctx.name, addLine("-", _length)) %><% - %><%- format("%s\n\n", fullDescription) %><% - %><%= format(".. js:function:: %s(%s)\n\n", entries[i].ctx.name, paramsString) %><% - } - - %><%= Array.isArray(paramsStrings) ? paramsStrings.join("") : paramsStrings %><% - - // If we have examples render them - if(examples != null && examples[examplesName]) { - %><%= format("\n**Examples**\n\n") %><% - var examplesArray = examples[examplesName]; - // Iterate over all the examples - for(var ei = 0; ei < examplesArray.length; ei++) { - // Fetch an example - var example = examplesArray[ei]; - var code = example.code; - code = code.replace(", ssl:useSSL", "") - .replace("native_parser: native_parser", "native_parser: false") - .replace(/test\.ok/g, "assert.ok") - .replace(/test\.equal/g, "assert.equal") - .replace(/test\.deepEqual/g, "assert.deepEqual") - .replace(/\n[ |\t]*test\.done\(\)\;/, ""); - - // Split and adjust code - var codeLines = code.split(/\n/); - for(var ci = 0; ci < codeLines.length; ci++) { - codeLines[ci] = " " + codeLines[ci]; - } - - var fullDescription = example.description.full; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - - // Split up and move - var fullDescriptionLines = fullDescription.split(/\n/); - for(var ci = 0; ci < fullDescriptionLines.length; ci++) { - fullDescriptionLines[ci] = " " + fullDescriptionLines[ci]; - } - - // Starting template Lines - var startingTemplateLines = [ - " var Db = require('mongodb').Db,", - " Server = require('mongodb').Server,", - " ReplSetServers = require('mongodb').ReplSetServers,", - " ObjectID = require('mongodb').ObjectID,", - " Binary = require('mongodb').Binary,", - " GridStore = require('mongodb').GridStore,", - " Code = require('mongodb').Code,", - " BSON = require('mongodb').pure().BSON,", - " assert = require('assert');\n\n" - ]; - - // Let's render it - %><%- format("%s\n\n", fullDescriptionLines.join("\n")) %><% - %><%- format(" .. code-block:: javascript\n\n%s%s\n\n", startingTemplateLines.join("\n"), codeLines.join("\n")) %><% - } - } - } -} -%> \ No newline at end of file diff --git a/node_modules/mongodb/dev/tools/doc-templates/function.ejs b/node_modules/mongodb/dev/tools/doc-templates/function.ejs deleted file mode 100644 index 1ff17c5..0000000 --- a/node_modules/mongodb/dev/tools/doc-templates/function.ejs +++ /dev/null @@ -1 +0,0 @@ -Function \ No newline at end of file diff --git a/node_modules/mongodb/dev/tools/doc-templates/index.ejs b/node_modules/mongodb/dev/tools/doc-templates/index.ejs deleted file mode 100644 index 453e61d..0000000 --- a/node_modules/mongodb/dev/tools/doc-templates/index.ejs +++ /dev/null @@ -1,15 +0,0 @@ -================== -<%- title %> -================== - -.. toctree:: - :maxdepth: 2 - -<% - for(var i = 0; i < entries.length; i++) { - // Classname - var name = entries[i]; - // Write out the name - %><%= format(" %s\n", name) %><% - } -%> \ No newline at end of file diff --git a/node_modules/mongodb/dev/tools/doc-templates/index_no_header.ejs b/node_modules/mongodb/dev/tools/doc-templates/index_no_header.ejs deleted file mode 100644 index 62b582a..0000000 --- a/node_modules/mongodb/dev/tools/doc-templates/index_no_header.ejs +++ /dev/null @@ -1,11 +0,0 @@ -.. toctree:: - :maxdepth: 1 - -<% - for(var i = 0; i < entries.length; i++) { - // Classname - var name = entries[i]; - // Write out the name - %><%= format(" %s\n", name) %><% - } -%> \ No newline at end of file diff --git a/node_modules/mongodb/dev/tools/docs.js b/node_modules/mongodb/dev/tools/docs.js deleted file mode 100644 index c370c9b..0000000 --- a/node_modules/mongodb/dev/tools/docs.js +++ /dev/null @@ -1,312 +0,0 @@ -var fs = require('fs'), - dox = require('dox'), - parseJS = require('uglify-js').parser, - ejs = require('ejs'), - exec = require('child_process').exec, - markdown = require('markdown').markdown, - format = require('util').format; - -// ----------------------------------------------------------------------------------------------------- -// -// Markdown converter -// -// ----------------------------------------------------------------------------------------------------- - -// Parse markdown to Rich text format -var transformMarkdownToStructuredText = exports.transformMarkdownToStructuredText = function(markDownText) { - // Parse the md file and generate a json tree - var jsonTree = markdown.parse(markDownText); - var documentLines = []; - return convert_tree_to_rs(jsonTree, documentLines).join('\n'); -} - -var addLine = function(char, length) { - var chars = []; - for(var i = 0; i < length; i++) chars[i] = char; - return chars.join(''); -} - -var convert_tree_to_rs = function(nodes, documentLines) { - if(!Array.isArray(nodes)) throw new Error("Malformed tree structure"); - // Go through all the tags and render - for(var i = 0; i < nodes.length; i++) { - var line = nodes[i]; - // console.dir(line) - - if(Array.isArray(line)) { - switch(line[0]) { - case 'header': - // Unpack the parts - var options = line[1]; - var title = line[2]; - // Add lines to the document - if(options.level == 1) { - documentLines.push(addLine("=", title.length)) - documentLines.push(title); - documentLines.push(addLine("=", title.length)) - } else if(options.level == 2) { - documentLines.push(addLine("-", title.length)) - documentLines.push(title); - documentLines.push(addLine("-", title.length)) - } - break; - case 'para': - var paraLines = []; - paraLines.push("\n"); - - for(var j = 1; j < line.length; j++) { - // bullet list item - if(Array.isArray(line[j])) { - var subdocs = []; - convert_tree_to_rs([line[j]], subdocs); - paraLines.push(subdocs.join('')); - } else { - paraLines.push(line[j]); - } - } - - // Merge the docs in - documentLines.push(paraLines.join(' ')); - documentLines.push('\n'); - break; - case 'link': - documentLines.push(format("`%s <%s>`_", line[2], line[1].href.replace(".md", ".html"))); - break; - case 'inlinecode': - documentLines.push(format("``%s``", line[1])); - break; - case 'code_block': - // Unpack code block - var codeLines = line[1].split("\n"); - // Format all the lines - documentLines.push(" .. code-block:: javascript\n"); - for(var j = 0; j < codeLines.length; j++) { - documentLines.push(format(" %s", codeLines[j])); - } - - documentLines.push("\n"); - break; - case 'bulletlist': - // Render the list (line.length - 1) - for(var j = 1; j < line.length; j++) { - // bullet list item - if(Array.isArray(line[j])) { - var subdocs = []; - convert_tree_to_rs([line[j]], subdocs); - documentLines.push(subdocs.join(' ')); - } else { - documentLines.push(line[j]); - } - } - - // Add an empty line - documentLines.push("\n"); - break; - case 'listitem': - var listitemLines = []; - - for(var j = 1; j < line.length; j++) { - // bullet list item - if(Array.isArray(line[j])) { - var subdocs = []; - convert_tree_to_rs([line[j]], subdocs); - listitemLines.push(subdocs.join(' ')); - } else { - listitemLines.push(line[j]); - } - } - - // Merge the docs in - documentLines.push(format(" * %s", listitemLines.join(' ').trim())); - break; - case 'em': - documentLines.push(format("*%s*", line[1])); - break; - case 'strong': - documentLines.push(format("**%s**", line[1])); - break; - default: - console.dir(line) - break; - } - } - } - - return documentLines; -} - -exports.writeMarkDownFile = function(outputDirectory, articles, templates, options) { - // Force create the directory for the generated docs - exec('rm -rf ' + outputDirectory, function (error, stdout, stderr) {}); - exec('mkdir ' + outputDirectory, function (error, stdout, stderr) {}); - - // Contains all the names for the index - var names = []; - - // Process all the articles - for(var i = 0 ; i < articles.length; i++) { - // Fetch the article markdown content - var article = fs.readFileSync(articles[i].path).toString(); - // Convert the text into restructured text for sphinx - var text = transformMarkdownToStructuredText(article); - // Write out the content - fs.writeFileSync(format("%s/%s", outputDirectory, articles[i].output.toLowerCase()), text); - names.push(articles[i].name.toLowerCase()); - } - - // Just write out the index - var indexContent = ejs.render(templates[options.template], {entries:names, format:format, title:options.title}); - fs.writeFileSync(format("%s/%s", outputDirectory, 'index.rst'), indexContent); -} - -// ----------------------------------------------------------------------------------------------------- -// -// API Doc generation -// -// ----------------------------------------------------------------------------------------------------- -// Parses all the files and extracts the dox data for the library -exports.extractLibraryMetaData = function(sourceFiles) { - var dataObjects = {}; - // Iterate over all source files - for(var i = 0; i < sourceFiles.length; i++) { - // Read source file content - var sourceFile = fs.readFileSync(sourceFiles[i].path); - // Parse the content - var metaData = dox.parseComments(sourceFile.toString()); - // Save the metadata - dataObjects[sourceFiles[i]["tag"] != null ? sourceFiles[i].tag : i] = metaData; - } - - // Return all objects - return dataObjects; -} - -// Build a hash to easy access to the objects -exports.buildTestHash = function(objects) { - // Organize the objects by class-function so we can query them - var objectsByClassAndMethod = {}; - var objectKeys = Object.keys(objects); - - // Get all the objects - for(var i = 0; i < objectKeys.length; i++) { - // Get the object with the metadata - var object = objects[objectKeys[i]]; - // Go through each example and pull them out - for(var j = 0; j < object.length; j++) { - var block = object[j]; - var tags = block.tags; - - // Build a class type - var tagObject = {}; - - // Check for the _class tag - for(var tagIndex = 0; tagIndex < tags.length; tagIndex++) { - // Get the tag - var tag = tags[tagIndex]; - // Grab the tag if it's got it - if(tag['type'] != null && tag['string'] != null) { - tagObject[tag['type']] = tag['string']; - } - } - - // Check if we have the tags _class and _function signaling a test - if(tagObject['_class'] != null && tagObject['_function'] != null) { - // Add a class reference if none exists - if(objectsByClassAndMethod[tagObject['_class']] == null) { - objectsByClassAndMethod[tagObject['_class']] = {}; - } - - // Add a method reference if none exists - if(objectsByClassAndMethod[tagObject['_class']][tagObject['_function']] == null) { - objectsByClassAndMethod[tagObject['_class']][tagObject['_function']] = []; - } - - // Push the object on the list - objectsByClassAndMethod[tagObject['_class']][tagObject['_function']].push(block); - - // Format the block code - var codeLines = block.code.split(/\n/); - // Drop first and last line - codeLines = codeLines.slice(1, codeLines.length - 1); - // Indent the code - for(var k = 0; k < codeLines.length; k++) { - codeLines[k] = codeLines[k].replace(/^ /, "") - } - // Reasign the code block - block.code = codeLines.join("\n"); - } - } - } - - // Return the object mapped by _class and _function - return objectsByClassAndMethod; -} - -// Render all the templates -exports.renderAllTemplates = function(outputDirectory, templates, dataObjects, testObjects, attributeTags) { - // Helper methods used in the rendering - var isClass = function(tags) { - for(var k = 0; k < tags.length; k++) { - if(tags[k].type == 'class') return true; - } - return false; - } - - var isFunction = function(entry) { - return entry.ctx != null && entry.ctx.type == 'method' && entry.isPrivate == false; - } - - var isProperty = function(entry) { - var tags = entry.tags; - for(var k = 0; k < tags.length; k++) { - if(tags[k].type == 'property') return true; - } - return false; - } - - var isClassConstant = function(entry) { - var tags = entry.tags; - for(var k = 0; k < tags.length; k++) { - if(tags[k].type == 'classconstant') return true; - } - return false; - } - - // Iterate over all classes - var classNames = Object.keys(dataObjects); - - // For each class generate output - for(var i = 0; i < classNames.length; i++) { - var className = classNames[i]; - // The meta data object - var classMetaData = dataObjects[className]; - // Grab the examples for this Metadata class - var classExamplesData = testObjects[className]; - // Render the class template - var classContent = ejs.render(templates['class'], - {entries:classMetaData, examples:classExamplesData, isClass:isClass, - isFunction:isFunction, isProperty:isProperty, isClassConstant:isClassConstant, - format:format}); - // Write out the content to disk - fs.writeFileSync(format("%s/%s.rst", outputDirectory, className), classContent); - } - - // Let's render the index api file - var indexContent = ejs.render(templates['index'], - {entries:classNames, isClass:isClass, isFunction:isFunction, isProperty:isProperty, - isClassConstant:isClassConstant, format:format, title:attributeTags['index_title']}); - // Write out the api index to disk - fs.writeFileSync(format("%s/%s.rst", outputDirectory, "index"), indexContent); -} - -// Read all the templates -exports.readAllTemplates = function(templates) { - var finishedTemplates = {}; - // Read in all the templates - for(var i = 0; i < templates.length; i++) { - finishedTemplates[templates[i].tag] = fs.readFileSync(templates[i].path).toString(); - } - - // Return the finished templates - return finishedTemplates; -} diff --git a/node_modules/mongodb/dev/tools/gleak.js b/node_modules/mongodb/dev/tools/gleak.js deleted file mode 100644 index 0a1bc6d..0000000 --- a/node_modules/mongodb/dev/tools/gleak.js +++ /dev/null @@ -1,5 +0,0 @@ - -var gleak = require('../../deps/gleak')(); -gleak.ignore('AssertionError'); - -module.exports = gleak; diff --git a/node_modules/mongodb/dev/tools/test_all.js b/node_modules/mongodb/dev/tools/test_all.js deleted file mode 100644 index 6fa8918..0000000 --- a/node_modules/mongodb/dev/tools/test_all.js +++ /dev/null @@ -1,176 +0,0 @@ -var nodeunit = require('../../deps/nodeunit'), - debug = require('util').debug, - inspect = require('util').inspect, - fs = require('fs'), - exec = require('child_process').exec, - spawn = require('child_process').spawn, - Step = require('../../deps/step/lib/step'), - ServerManager = require('../../test/tools/server_manager').ServerManager, - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager; - -// Manage the test server -var serverManager = new ServerManager(); -var replicaSetManager = new ReplicaSetManager(); -// test directories -var files = []; -var directories = [{dir: __dirname + "/../../test", path: "/test/"}, - {dir: __dirname + "/../../test/gridstore", path: "/test/gridstore/"}, - {dir: __dirname + "/../../test/connection", path: "/test/connection/"}, - {dir: __dirname + "/../../test/bson", path: "/test/bson/"}]; - -// Generate a list of tests -directories.forEach(function(dirEntry) { - // Add the files - files = files.concat(fs.readdirSync(dirEntry.dir).filter(function(item) { - return /_test\.js$/i.test(item); - }).map(function(file) { - return dirEntry.path + file; - })); -}); - -// Replicasetfiles -var replicasetFiles = fs.readdirSync(__dirname + "/../../test/replicaset").filter(function(item) { - return /_test\.js$/i.test(item); -}).map(function(file) { - return "/test/replicaset/" + file; -}); - -var specifedParameter = function(arguments, param) { - for(var i = 0; i < arguments.length; i++) { - if(arguments[i] == param) return true; - } - return false; -} - -// Different options -var junit = specifedParameter(process.argv, '--junit', false); -var noReplicaSet = specifedParameter(process.argv, '--noreplicaset', false); -var boot = specifedParameter(process.argv, '--boot', false); -// Basic default test runner -var runner = nodeunit.reporters.default; -var options = { error_prefix: '\u001b[31m', - error_suffix: '\u001b[39m', - ok_prefix: '\u001b[32m', - ok_suffix: '\u001b[39m', - bold_prefix: '\u001b[1m', - bold_suffix: '\u001b[22m', - assertion_prefix: '\u001b[35m', - assertion_suffix: '\u001b[39m' }; - -// cleanup output directory -exec('rm -rf ./output', function(err, stdout, stderr) { - // if we have a junit reporter - if(junit) { - // Remove directory - fs.mkdirSync("./output", 0777); - // Set up options - options.output = './output'; - options.junit = true; - } - - // Run all tests including replicaset ones - if(!noReplicaSet) { - // Boot up the test server and run the tests - Step( - // Start the single server - function startSingleServer() { - if(boot) { - serverManager.start(true, {purgedirectories:true}, this); - } else { - this(null, null); - } - }, - - // Run all the integration tests using the pure js bson parser - function runPureJS() { - options.suffix = 'pure'; - var test_set_runner = spawn('node', ['./dev/tools/test_set_runner.js', JSON.stringify(files), JSON.stringify(options)]); - test_set_runner.stdout.on('data', function(data) { - process.stdout.write(data.toString()); - }); - test_set_runner.stderr.on('data', function(data) { - process.stdout.write("err: " + data.toString()); - }); - - test_set_runner.on('exit', this); - }, - - // Execute all the replicaset tests - function executeReplicaSetTests() { - options.suffix = 'pure'; - var test_set_runner = spawn('node', ['./dev/tools/test_set_runner.js', JSON.stringify(replicasetFiles), JSON.stringify(options)]); - test_set_runner.stdout.on('data', function(data) { - process.stdout.write(data.toString()); - }); - test_set_runner.stderr.on('data', function(data) { - process.stdout.write("err: " + data.toString()); - }); - - test_set_runner.on('exit', this); - }, - - function done() { - if(boot) { - // Kill all mongod server - replicaSetManager.killAll(function() { - // Force exit - process.exit(); - }) - } else { - process.exit(); - } - } - ); - } else { - // Execute without replicaset tests - Step( - function startSingleServer() { - if(boot) { - serverManager.start(true, {purgedirectories:true}, this); - } else { - this(null, null); - } - }, - - function runPureJS() { - options.suffix = 'pure'; - var test_set_runner = spawn('node', ['./dev/tools/test_set_runner.js', JSON.stringify(files), JSON.stringify(options)]); - test_set_runner.stdout.on('data', function(data) { - process.stdout.write(data.toString()); - }); - test_set_runner.stderr.on('data', function(data) { - process.stdout.write("err: " + data.toString()); - }); - - test_set_runner.on('exit', this); - }, - - function runNativeJS() { - options.suffix = 'native'; - options.native = true; - - var test_set_runner = spawn('node', ['./dev/tools/test_set_runner.js', JSON.stringify(files), JSON.stringify(options)]); - test_set_runner.stdout.on('data', function(data) { - process.stdout.write(data.toString()); - }); - test_set_runner.stderr.on('data', function(data) { - process.stdout.write("err: " + data.toString()); - }); - - test_set_runner.on('exit', this); - }, - - function done() { - if(boot) { - // Kill all mongod server - replicaSetManager.killAll(function() { - // Force exit - process.exit(); - }) - } else { - process.exit(); - } - } - ); - } -}); diff --git a/node_modules/mongodb/dev/tools/test_set_runner.js b/node_modules/mongodb/dev/tools/test_set_runner.js deleted file mode 100644 index 6cfb6b1..0000000 --- a/node_modules/mongodb/dev/tools/test_set_runner.js +++ /dev/null @@ -1,27 +0,0 @@ -var nodeunit = require('../../deps/nodeunit'); - -// Let's parse the argv (ensure we have all the number of parameters) -if(process.argv.length === 4) { - // Pop the arguments off - var options = JSON.parse(process.argv.pop()); - var files = JSON.parse(process.argv.pop()); - - // Basic default test runner - var runner = options['junit'] == true ? nodeunit.reporters.junit : nodeunit.reporters.default; - var nativeExecution = options['native'] == null ? false : options['native']; - // Remove junit tag if it exists - delete options['junit']; - delete options['native']; - - // Set native process - if(nativeExecution) { - process.env['TEST_NATIVE'] = 'TRUE'; - } - - // Let's set up nodeunit to run - runner.run(files, options, function() { - process.exit(0); - }); -} else { - console.error("Must pass in a list of files and options object"); -} diff --git a/node_modules/mongodb/docs/sphinx-docs/build/html/.buildinfo b/node_modules/mongodb/docs/sphinx-docs/build/html/.buildinfo deleted file mode 100644 index c99c1eb..0000000 --- a/node_modules/mongodb/docs/sphinx-docs/build/html/.buildinfo +++ /dev/null @@ -1,4 +0,0 @@ -# Sphinx build info version 1 -# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: c17150b5838a3e308c3c7bec6e59b487 -tags: fbb0d17656682115ca4d033fb2f83ba1 diff --git a/node_modules/mongodb/docs/sphinx-docs/build/singlehtml/.buildinfo b/node_modules/mongodb/docs/sphinx-docs/build/singlehtml/.buildinfo deleted file mode 100644 index 0885fbe..0000000 --- a/node_modules/mongodb/docs/sphinx-docs/build/singlehtml/.buildinfo +++ /dev/null @@ -1,4 +0,0 @@ -# Sphinx build info version 1 -# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: -tags: diff --git a/node_modules/mongodb/docs/sphinx-docs/source/static/.mongodb b/node_modules/mongodb/docs/sphinx-docs/source/static/.mongodb deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mongodb/docs/sphinx-docs/templates/.mongodb b/node_modules/mongodb/docs/sphinx-docs/templates/.mongodb deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/mongodb/examples/admin.js b/node_modules/mongodb/examples/admin.js deleted file mode 100644 index 2619e7e..0000000 --- a/node_modules/mongodb/examples/admin.js +++ /dev/null @@ -1,53 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropDatabase(function(err, result){ - db.dropCollection('test', function(err, result) { - db.createCollection('test', function(err, collection) { - - // Erase all records in collection - collection.remove({}, function(err, r) { - db.admin(function(err, admin) { - - // Profiling level set/get - admin.profilingLevel(function(err, profilingLevel) { - console.log("Profiling level: " + profilingLevel); - }); - - // Start profiling everything - admin.setProfilingLevel('all', function(err, level) { - console.log("Profiling level: " + level); - - // Read records, creating a profiling event - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - // Stop profiling - admin.setProfilingLevel('off', function(err, level) { - // Print all profiling info - admin.profilingInfo(function(err, info) { - console.dir(info); - - // Validate returns a hash if all is well or return an error hash if there is a - // problem. - admin.validateCollection(collection.collectionName, function(err, result) { - console.dir(result); - db.close(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/mongodb/examples/blog.js b/node_modules/mongodb/examples/blog.js deleted file mode 100644 index ff9c16b..0000000 --- a/node_modules/mongodb/examples/blog.js +++ /dev/null @@ -1,102 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -var LINE_SIZE = 120; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-blog', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropDatabase(function(err, result) { - console.log("==================================================================================="); - console.log(">> Adding Authors"); - db.collection('authors', function(err, collection) { - collection.createIndex(["meta", ['_id', 1], ['name', 1], ['age', 1]], function(err, indexName) { - console.log("==================================================================================="); - var authors = {}; - - // Insert authors - collection.insert([{'name':'William Shakespeare', 'email':'william@shakespeare.com', 'age':587}, - {'name':'Jorge Luis Borges', 'email':'jorge@borges.com', 'age':123}], function(err, docs) { - docs.forEach(function(doc) { - console.dir(doc); - authors[doc.name] = doc; - }); - }); - - console.log("==================================================================================="); - console.log(">> Authors ordered by age ascending"); - console.log("==================================================================================="); - collection.find({}, {'sort':[['age', 1]]}, function(err, cursor) { - cursor.each(function(err, author) { - if(author != null) { - console.log("[" + author.name + "]:[" + author.email + "]:[" + author.age + "]"); - } else { - console.log("==================================================================================="); - console.log(">> Adding users"); - console.log("==================================================================================="); - db.collection('users', function(err, userCollection) { - var users = {}; - - userCollection.insert([{'login':'jdoe', 'name':'John Doe', 'email':'john@doe.com'}, - {'login':'lsmith', 'name':'Lucy Smith', 'email':'lucy@smith.com'}], function(err, docs) { - docs.forEach(function(doc) { - console.dir(doc); - users[doc.login] = doc; - }); - }); - - console.log("==================================================================================="); - console.log(">> Users ordered by login ascending"); - console.log("==================================================================================="); - userCollection.find({}, {'sort':[['login', 1]]}, function(err, cursor) { - cursor.each(function(err, user) { - if(user != null) { - console.log("[" + user.login + "]:[" + user.name + "]:[" + user.email + "]"); - } else { - console.log("==================================================================================="); - console.log(">> Adding articles"); - console.log("==================================================================================="); - db.collection('articles', function(err, articlesCollection) { - articlesCollection.insert([ - { 'title':'Caminando por Buenos Aires', - 'body':'Las callecitas de Buenos Aires tienen ese no se que...', - 'author_id':authors['Jorge Luis Borges']._id}, - { 'title':'I must have seen thy face before', - 'body':'Thine eyes call me in a new way', - 'author_id':authors['William Shakespeare']._id, - 'comments':[{'user_id':users['jdoe']._id, 'body':"great article!"}] - } - ], function(err, docs) { - docs.forEach(function(doc) { - console.dir(doc); - }); - }) - - console.log("==================================================================================="); - console.log(">> Articles ordered by title ascending"); - console.log("==================================================================================="); - articlesCollection.find({}, {'sort':[['title', 1]]}, function(err, cursor) { - cursor.each(function(err, article) { - if(article != null) { - console.log("[" + article.title + "]:[" + article.body + "]:[" + article.author_id.toHexString() + "]"); - console.log(">> Closing connection"); - db.close(); - } - }); - }); - }); - } - }); - }); - }); - } - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/mongodb/examples/capped.js b/node_modules/mongodb/examples/capped.js deleted file mode 100644 index fb98911..0000000 --- a/node_modules/mongodb/examples/capped.js +++ /dev/null @@ -1,27 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropCollection('test', function(err, result) { - // A capped collection has a max size and optionally a max number of records. - // Old records get pushed out by new ones once the size or max num records is - // reached. - db.createCollection('test', {'capped':true, 'size':1024, 'max':12}, function(err, collection) { - for(var i = 0; i < 100; i++) { collection.insert({'a':i}); } - - // We will only see the last 12 records - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - console.log("The number of records: " + items.length); - db.close(); - }) - }) - }); - }); -}); \ No newline at end of file diff --git a/node_modules/mongodb/examples/cursor.js b/node_modules/mongodb/examples/cursor.js deleted file mode 100644 index cd5c5f3..0000000 --- a/node_modules/mongodb/examples/cursor.js +++ /dev/null @@ -1,70 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.collection('test', function(err, collection) { - // Erase all records from collection, if any - collection.remove(function(err, result) { - - // Insert 3 records - for(var i = 0; i < 3; i++) { - collection.insert({'a':i}); - } - - // Cursors don't run their queries until you actually attempt to retrieve data - // from them. - - // Find returns a Cursor, which is Enumerable. You can iterate: - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) console.dir(item); - }); - }); - - // You can turn it into an array - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - console.log("count: " + items.length); - }); - }); - - // You can iterate after turning it into an array (the cursor will iterate over - // the copy of the array that it saves internally.) - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - cursor.each(function(err, item) { - if(item != null) console.dir(item); - }); - }); - }); - - // You can get the next object - collection.find(function(err, cursor) { - cursor.nextObject(function(err, item) { - if(item != null) console.dir(item); - }); - }); - - // next_object returns null if there are no more objects that match - collection.find(function(err, cursor) { - cursor.nextObject(function(err, item) { - cursor.nextObject(function(err, item) { - cursor.nextObject(function(err, item) { - cursor.nextObject(function(err, item) { - console.log("nextObject returned: "); - console.dir(item); - db.close(); - }); - }); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/mongodb/examples/gridfs.js b/node_modules/mongodb/examples/gridfs.js deleted file mode 100644 index 359af25..0000000 --- a/node_modules/mongodb/examples/gridfs.js +++ /dev/null @@ -1,149 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - GridStore = require('../lib/mongodb').GridStore; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log(">> Connecting to " + host + ":" + port); -var db1 = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db1.open(function(err, db) { - // Write a new file - var gridStore = new GridStore(db, "foobar", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - // Read the file and dump the contents - dump(db, 'foobar'); - - // Append more data - gridStore = new GridStore(db, 'foobar', "w+"); - gridStore.open(function(err, gridStore) { - gridStore.write('\n', function(err, gridStore) { - gridStore.puts('line two', function(err, gridStore) { - gridStore.close(function(err, result) { - dump(db, 'foobar'); - - // Overwrite - gridStore = new GridStore(db, 'foobar', "w"); - gridStore.open(function(err, gridStore) { - gridStore.write('hello, sailor!', function(err, gridStore) { - gridStore.close(function(err, result) { - dump(db, 'foobar', function() { - db.close(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -}); - -var db2 = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db2.open(function(err, db) { - // File existence tests - var gridStore = new GridStore(db, "foobar2", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write( 'hello sailor', function(err, gridStore) { - gridStore.close(function(err, result) { - GridStore.exist(db, 'foobar2', function(err, result) { - console.log("File 'foobar2' exists: " + result); - }); - - GridStore.exist(db, 'does-not-exist', function(err, result) { - console.log("File 'does-not-exist' exists: " + result); - }); - - // Read with offset(uses seek) - GridStore.read(db, 'foobar2', 6, 7, function(err, data) { - console.log(data); - }); - - // Rewind/seek/tell - var gridStore2 = new GridStore(db, 'foobar2', 'w'); - gridStore2.open(function(err, gridStore) { - gridStore.write('hello, world!', function(err, gridStore){}); - gridStore.rewind(function(){}); - gridStore.write('xyzzz', function(err, gridStore){}); - gridStore.tell(function(tell) { - console.log("tell: " + tell); // Should be 5 - }); - gridStore.seek(4, function(err, gridStore){}); - gridStore.write('y', function(){}); - gridStore.close(function() { - dump(db, 'foobar2'); - - // Unlink file (delete) - GridStore.unlink(db, 'foobar2', function(err, gridStore) { - GridStore.exist(db, 'foobar2', function(err, result) { - console.log("File 'foobar2' exists: " + result); - db.close(); - }); - }); - }); - }); - }); - }); - }); -}); - -var db3 = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db3.open(function(err, db) { - // Metadata - var gridStore = new GridStore(db, "foobar3", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write('hello, world!', function(err, gridStore){}); - gridStore.close(function(err, gridStore) { - gridStore = new GridStore(db, 'foobar3', "r"); - gridStore.open(function(err, gridStore) { - console.log("contentType: " + gridStore.contentType); - console.log("uploadDate: " + gridStore.uploadDate); - console.log("chunkSize: " + gridStore.chunkSize); - console.log("metadata: " + gridStore.metadata); - }); - - // Add some metadata - gridStore = new GridStore(db, 'foobar3', "w+"); - gridStore.open(function(err, gridStore) { - gridStore.contentType = 'text/xml'; - gridStore.metadata = {'a':1}; - gridStore.close(function(err, gridStore) { - // Print the metadata - gridStore = new GridStore(db, 'foobar3', "r"); - gridStore.open(function(err, gridStore) { - console.log("contentType: " + gridStore.contentType); - console.log("uploadDate: " + gridStore.uploadDate); - console.log("chunkSize: " + gridStore.chunkSize); - console.log("metadata: " + gridStore.metadata); - db.close(); - }); - }); - }); - }); - }); - - // You can also set meta data when initially writing to a file - // setting root means that the file and its chunks are stored in a different root - // collection: instead of gridfs.files and gridfs.chunks, here we use - // my_files.files and my_files.chunks - var gridStore = new GridStore(db, "foobar3", "w", {'content_type':'text/plain', - 'metadata':{'a':1}, 'chunk_size': 1024*4, 'root':'my_files'}); - gridStore.open(function(err, gridStore) { - gridStore.write('hello, world!', function(err, gridStore){}); - gridStore.close(function() { - }); - }); -}); - -function dump(db, filename, callback) { - GridStore.read(db, filename, function(err, data) { - console.log(data); - if(callback != null) callback(); - }); -} \ No newline at end of file diff --git a/node_modules/mongodb/examples/index.js b/node_modules/mongodb/examples/index.js deleted file mode 100644 index 73d3348..0000000 --- a/node_modules/mongodb/examples/index.js +++ /dev/null @@ -1,62 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - mongo = require('../lib/mongodb'); - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log(">> Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - console.log(">> Dropping collection test"); - db.dropCollection('test', function(err, result) { - console.log("dropped: "); - console.dir(result); - }); - - console.log(">> Creating collection test"); - db.collection('test', function(err, collection) { - console.log("created: "); - console.dir(collection); - - var objectCount = 100; - var objects = []; - var messages = ["hola", "hello", "aloha", "ciao"]; - console.log(">> Generate test data"); - for(var i = 0; i < objectCount; i++) { - objects.push({'number':i, 'rndm':((5*Math.random()) + 1), 'msg':messages[parseInt(4*Math.random())]}) - } - console.log("generated"); - - console.log(">> Inserting data (" + objects.length + ")"); - collection.insert(objects); - console.log("inserted"); - - console.log(">> Creating index") - collection.createIndex([['all'], ['_id', 1], ['number', 1], ['rndm', 1], ['msg', 1]], function(err, indexName) { - console.log("created index: " + indexName); - - console.log(">> Gathering index information"); - - collection.indexInformation(function(err, doc) { - console.log("indexInformation: "); - console.dir(doc); - - console.log(">> Dropping index"); - collection.dropIndex('all_1__id_1_number_1_rndm_1_msg_1', function(err, result) { - console.log("dropped: "); - console.dir(result); - - console.log(">> Gathering index information"); - collection.indexInformation(function(err, doc) { - console.log("indexInformation: "); - console.dir(doc); - console.log(">> Closing connection"); - db.close(); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/mongodb/examples/info.js b/node_modules/mongodb/examples/info.js deleted file mode 100644 index 54ca60c..0000000 --- a/node_modules/mongodb/examples/info.js +++ /dev/null @@ -1,48 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.collection('test', function(err, collection) { - - // Remove all existing documents in collection - collection.remove(function(err, result) { - - // Insert 3 records - for(var i = 0; i < 3; i++) { - collection.insert({'a':i}); - } - - // Show collection names in the database - db.collectionNames(function(err, names) { - names.forEach(function(name) { - console.dir(name); - }); - }); - - // More information about each collection - db.collectionsInfo(function(err, cursor) { - cursor.toArray(function(err, items) { - items.forEach(function(item) { - console.dir(item); - }); - }); - }) - - // Index information - db.createIndex('test', 'a', function(err, indexName) { - db.indexInformation('test', function(err, doc) { - console.dir(doc); - collection.drop(function(err, result) { - db.close(); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/mongodb/examples/oplog.js b/node_modules/mongodb/examples/oplog.js deleted file mode 100644 index 4441a61..0000000 --- a/node_modules/mongodb/examples/oplog.js +++ /dev/null @@ -1,114 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - Cursor = require('../lib/mongodb').Cursor; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -Slave = function() { - this.running = false; - this.callbacks = []; - //no native_parser right now (because timestamps) - //no strict mode (because system db signed with $ db.js line 189) - //connect without dbName for querying not only "local" db - console.log("Connecting to " + host + ":" + port); - this.db = new Db('testing', new Server(host, port, {}), {}); -} - -//start watching -Slave.prototype.start = function() { - var self = this; - if (this.running) return; - - this.db.open(function(err, db) { - if (err) { - console.log('> MongoSlave error' + err); - process.exit(1); - } - - db.collection('local.oplog.$main', function(err, collection) { - if (! collection) { - console.log('> MongoSlave - local.oplog.$main not found'); - self.stop(); - return false; - } - - process.on('SIGINT', function () { - self.stop(); //tailable cursor should be stopped manually - }); - - //get last row for init TS - collection.find({}, {'limit': 1, 'sort': [['$natural', -1]]}, function(err, cursor) { - cursor.toArray(function(err, items) { - if (items.length) { - console.log('> MongoSlave started'); - self.running = true; - self._runSlave(collection, items[0]['ts']); - } else if (err) { - console.log(err); - self.stop(); - } - }); - }); - }); - }); -} - -//stop watching -Slave.prototype.stop = function() { - if (!this.running) return; - console.log('> MongoSlave stopped'); - this.running = false; - this.db.close(); -} - -Slave.prototype._runSlave = function(collection, time) { - - var self = this; - - //watch oplog INFINITE (until Slave.stop()) - collection.find({'ts': {'$gt': time}}, {'tailable': 1, 'sort': [['$natural', 1]]}, function(err, cursor) { - cursor.each(function(err, item) { - if (cursor.state == Cursor.CLOSED) { //broken cursor - self.running && self._runSlave(collection, time); - return; - } - time = item['ts']; - - switch(item['op']) { - case 'i': //inserted - self._emitObj(item['o']); - break; - case 'u': //updated - self.db.collection(item['ns'], function(err, collection) { - collection.findOne(item['o2']['_id'], {}, function(err, item) { - item && self._emitObj(item); - }); - }); - break; - case 'd': //deleted - //nothing to do - break; - } - }); - }); -} - -Slave.prototype._emitObj = function (obj) { - for(var i in this.callbacks) this.callbacks[i].call(this, obj); -} - -Slave.prototype.onObject = function(callback) { - this.callbacks.push(callback); -} - - -//just for example -var watcher = new Slave(); - -watcher.onObject(function(obj) { - console.dir(obj); -}); - -watcher.start(); \ No newline at end of file diff --git a/node_modules/mongodb/examples/queries.js b/node_modules/mongodb/examples/queries.js deleted file mode 100644 index 19cc473..0000000 --- a/node_modules/mongodb/examples/queries.js +++ /dev/null @@ -1,125 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); - -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropDatabase(function() { - // Fetch the collection test - db.collection('test', function(err, collection) { - // Remove all records in collection if any - collection.remove(function(err, result) { - // Insert three records - collection.insert([{'a':1}, {'a':2}, {'b':3}], function(docs) { - // Count the number of records - collection.count(function(err, count) { - console.log("There are " + count + " records."); - }); - - // Find all records. find() returns a cursor - collection.find(function(err, cursor) { - // Print each row, each document has an _id field added on insert - // to override the basic behaviour implement a primary key factory - // that provides a 12 byte value - console.log("Printing docs from Cursor Each") - cursor.each(function(err, doc) { - if(doc != null) console.log("Doc from Each "); - console.dir(doc); - }) - }); - // Cursor has an to array method that reads in all the records to memory - collection.find(function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Printing docs from Array") - docs.forEach(function(doc) { - console.log("Doc from Array "); - console.dir(doc); - }); - }); - }); - - // Different methods to access records (no printing of the results) - - // Locate specific document by key - collection.find({'a':1}, function(err, cursor) { - cursor.nextObject(function(err, doc) { - console.log("Returned #1 documents"); - }); - }); - - // Find records sort by 'a', skip 1, limit 2 records - // Sort can be a single name, array, associate array or ordered hash - collection.find({}, {'skip':1, 'limit':1, 'sort':'a'}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }) - }); - - // Find all records with 'a' > 1, you can also use $lt, $gte or $lte - collection.find({'a':{'$gt':1}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - collection.find({'a':{'$gt':1, '$lte':3}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Find all records with 'a' in a set of values - collection.find({'a':{'$in':[1,2]}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Find by regexp - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Print Query explanation - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - }) - }); - - // Use a hint with a query, hint's can also be store in the collection - // and will be applied to each query done through the collection. - // Hint's can also be specified by query which will override the - // hint's associated with the collection - collection.createIndex('a', function(err, indexName) { - collection.hint = 'a'; - - // You will see a different explanation now that the hint was set - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - }) - }); - - collection.find({'a':/[1|2]/}, {'hint':'a'}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - db.close(); - }) - }); - }); - }); - }); - }); - }); -}); diff --git a/node_modules/mongodb/examples/replSetServersQueries.js b/node_modules/mongodb/examples/replSetServersQueries.js deleted file mode 100644 index ab82ac6..0000000 --- a/node_modules/mongodb/examples/replSetServersQueries.js +++ /dev/null @@ -1,138 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - ReplSetServers = require('../lib/mongodb').ReplSetServers; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -var port1 = 27018; -var port2 = 27019; -var server = new Server(host, port, {}); -var server1 = new Server(host, port1, {}); -var server2 = new Server(host, port2, {}); -var servers = new Array(); -servers[0] = server2; -servers[1] = server1; -servers[2] = server; - -var replStat = new ReplSetServers(servers); -console.log("Connecting to " + host + ":" + port); -console.log("Connecting to " + host1 + ":" + port1); -console.log("Connecting to " + host2 + ":" + port2); -var db = new Db('node-mongo-examples', replStat, {native_parser:true}); -db.open(function(err, db) { - db.dropDatabase(function() { - // Fetch the collection test - db.collection('test', function(err, collection) { - // Remove all records in collection if any - collection.remove(function(err, collection) { - // Insert three records - collection.insert([{'a':1}, {'a':2}, {'b':3}], function(docs) { - // Count the number of records - collection.count(function(err, count) { - console.log("There are " + count + " records."); - }); - - // Find all records. find() returns a cursor - collection.find(function(err, cursor) { - // Print each row, each document has an _id field added on insert - // to override the basic behaviour implement a primary key factory - // that provides a 12 byte value - console.log("Printing docs from Cursor Each") - cursor.each(function(err, doc) { - if(doc != null) console.log("Doc from Each "); - console.dir(doc); - }) - }); - // Cursor has an to array method that reads in all the records to memory - collection.find(function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Printing docs from Array") - docs.forEach(function(doc) { - console.log("Doc from Array "); - console.dir(doc); - }); - }); - }); - - // Different methods to access records (no printing of the results) - - // Locate specific document by key - collection.find({'a':1}, function(err, cursor) { - cursor.nextObject(function(err, doc) { - console.log("Returned #1 documents"); - }); - }); - - // Find records sort by 'a', skip 1, limit 2 records - // Sort can be a single name, array, associate array or ordered hash - collection.find({}, {'skip':1, 'limit':1, 'sort':'a'}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }) - }); - - // Find all records with 'a' > 1, you can also use $lt, $gte or $lte - collection.find({'a':{'$gt':1}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - collection.find({'a':{'$gt':1, '$lte':3}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Find all records with 'a' in a set of values - collection.find({'a':{'$in':[1,2]}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Find by regexp - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Print Query explanation - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - }) - }); - - // Use a hint with a query, hint's can also be store in the collection - // and will be applied to each query done through the collection. - // Hint's can also be specified by query which will override the - // hint's associated with the collection - collection.createIndex('a', function(err, indexName) { - collection.hint = 'a'; - - // You will see a different explanation now that the hint was set - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - }) - }); - - collection.find({'a':/[1|2]/}, {'hint':'a'}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - db.close(); - }) - }); - }); - }); - }); - }); - }); -}); diff --git a/node_modules/mongodb/examples/replSetServersSimple.js b/node_modules/mongodb/examples/replSetServersSimple.js deleted file mode 100644 index 9ca3f3f..0000000 --- a/node_modules/mongodb/examples/replSetServersSimple.js +++ /dev/null @@ -1,66 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Admin = require('../lib/mongodb').Admin, - DbCommand = require('../lib/mongodb/commands/db_command').DbCommand, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - ReplSetServers = require('../lib/mongodb').ReplSetServers, - CheckMaster = require('../lib/mongodb').CheckMaster; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -var port1 = 27018; -var port2 = 27019; - - -console.log("Connecting to " + host + ":" + port); -console.log("Connecting to " + host + ":" + port1); -console.log("Connecting to " + host + ":" + port2); - -var server = new Server(host, port, {}); -var server1 = new Server(host, port1, {}); -var server2 = new Server(host, port2, {}); -var servers = new Array(); -servers[0] = server2; -servers[1] = server1; -servers[2] = server; - -var replStat = new ReplSetServers(servers); - -var db = new Db('mongo-example', replStat, {native_parser:true}); -db.open(function(err, db) { - - db.dropDatabase(function(err, result) { - db.collection('test', function(err, collection) { - collection.remove(function(err, collection) { - // Insert 3 records - for(var i = 0; i < 3; i++) { - collection.insert({'a':i}); - } - - collection.count(function(err, count) { - console.log("There are " + count + " records in the test collection. Here they are:"); - - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - console.dir(item); - console.log("created at " + new Date(item._id.generationTime) + "\n") - } - // Null signifies end of iterator - if(item == null) { - // Destory the collection - collection.drop(function(err, collection) { - db.close(); - }); - } - }); - }); - }); - }); - }); - }); -}); - - - diff --git a/node_modules/mongodb/examples/simple.js b/node_modules/mongodb/examples/simple.js deleted file mode 100644 index 9bcdf25..0000000 --- a/node_modules/mongodb/examples/simple.js +++ /dev/null @@ -1,42 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropDatabase(function(err, result) { - db.collection('test', function(err, collection) { - // Erase all records from the collection, if any - collection.remove({}, function(err, result) { - // Insert 3 records - for(var i = 0; i < 3; i++) { - collection.insert({'a':i}); - } - - collection.count(function(err, count) { - console.log("There are " + count + " records in the test collection. Here they are:"); - - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - console.dir(item); - console.log("created at " + new Date(item._id.generationTime) + "\n") - } - // Null signifies end of iterator - if(item == null) { - // Destory the collection - collection.drop(function(err, collection) { - db.close(); - }); - } - }); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/mongodb/examples/strict.js b/node_modules/mongodb/examples/strict.js deleted file mode 100644 index 45c739c..0000000 --- a/node_modules/mongodb/examples/strict.js +++ /dev/null @@ -1,36 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropCollection('does-not-exist', function(err, result) { - db.createCollection('test', function(err, collection) { - db.strict = true; - - // Can't reference collections that does not exist in strict mode - db.collection('does-not-exist', function(err, collection) { - if(err instanceof Error) { - console.log("expected error: " + err.message); - } - - // Can't create collections that does not exist in strict mode - db.createCollection('test', function(err, collection) { - if(err instanceof Error) { - console.log("expected error: " + err.message); - } - - // Remove the strict mode - db.strict = false; - db.dropCollection('test', function(err, collection) { - db.close(); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/mongodb/examples/types.js b/node_modules/mongodb/examples/types.js deleted file mode 100644 index efff89a..0000000 --- a/node_modules/mongodb/examples/types.js +++ /dev/null @@ -1,42 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - BSON = require('../lib/mongodb').BSONPure; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {}); -db.open(function(err, db) { - db.collection('test', function(err, collection) { - // Remove all existing documents in collection - collection.remove(function(err, result) { - // Insert record with all the available types of values - collection.insert({ - 'array':[1,2,3], - 'string':'hello', - 'hash':{'a':1, 'b':2}, - 'date':new Date(), // Stores only milisecond resolution - 'oid':new BSON.ObjectID(), - 'binary':new BSON.Binary("123"), - 'int':42, - 'float':33.3333, - 'regexp':/foobar/i, - 'regexp2':/foobar2/, - 'boolean':true, - 'where':new BSON.Code('this.x == 3'), - 'dbref':new BSON.DBRef(collection.collectionName, new BSON.ObjectID()), - 'null':null - }, function(err, doc) { - // Locate the first document - collection.findOne(function(err, document) { - console.dir(document); - collection.remove(function(err, collection) { - db.close(); - }); - }) - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/mongodb/examples/url.js b/node_modules/mongodb/examples/url.js deleted file mode 100644 index b04c29f..0000000 --- a/node_modules/mongodb/examples/url.js +++ /dev/null @@ -1,12 +0,0 @@ -var Db = require('../lib/mongodb').Db, - connect = require('../lib/mongodb').connect; - -console.log('Connecting to ' + Db.DEFAULT_URL); -connect(Db.DEFAULT_URL, function(err, db) { - db.dropDatabase(function(err, result) { - db.collection('test', function(err, collection) { - collection.insert({'a':1}); - db.close(); - }); - }); -}); diff --git a/node_modules/mongodb/lib/mongodb/admin.js b/node_modules/mongodb/lib/mongodb/admin.js index e85bcae..89ca706 100644 --- a/node_modules/mongodb/lib/mongodb/admin.js +++ b/node_modules/mongodb/lib/mongodb/admin.js @@ -141,17 +141,26 @@ Admin.prototype.logout = function(callback) { * Add a user to the MongoDB server, if the user exists it will * overwrite the current password * + * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. + * * @param {String} username The user name for the authentication. * @param {String} password The password for the authentication. + * @param {Object} [options] additional options during update. * @param {Function} callback Callback function of format `function(err, result) {}`. * @return {null} Returns no result * @api public */ -Admin.prototype.addUser = function(username, password, callback) { +Admin.prototype.addUser = function(username, password, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() : {}; + var self = this; var databaseName = this.db.databaseName; this.db.databaseName = 'admin'; - this.db.addUser(username, password, function(err, result) { + this.db.addUser(username, password, options, function(err, result) { self.db.databaseName = databaseName; return callback(err, result); }) @@ -160,16 +169,25 @@ Admin.prototype.addUser = function(username, password, callback) { /** * Remove a user from the MongoDB server * + * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. + * * @param {String} username The user name for the authentication. + * @param {Object} [options] additional options during update. * @param {Function} callback Callback function of format `function(err, result) {}`. * @return {null} Returns no result * @api public */ -Admin.prototype.removeUser = function(username, callback) { +Admin.prototype.removeUser = function(username, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + var self = this; var databaseName = this.db.databaseName; this.db.databaseName = 'admin'; - this.db.removeUser(username, function(err, result) { + this.db.removeUser(username, options, function(err, result) { self.db.databaseName = databaseName; return callback(err, result); }) diff --git a/node_modules/mongodb/lib/mongodb/collection.js b/node_modules/mongodb/lib/mongodb/collection.js index c9e883e..f875bd3 100644 --- a/node_modules/mongodb/lib/mongodb/collection.js +++ b/node_modules/mongodb/lib/mongodb/collection.js @@ -899,6 +899,11 @@ Collection.prototype.findOne = function findOne () { * @api public */ Collection.prototype.createIndex = function createIndex (fieldOrSpec, options, callback) { + // Clean up call + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + // Execute create index this.db.createIndex(this.collectionName, fieldOrSpec, options, callback); }; @@ -921,6 +926,11 @@ Collection.prototype.createIndex = function createIndex (fieldOrSpec, options, c * @api public */ Collection.prototype.ensureIndex = function ensureIndex (fieldOrSpec, options, callback) { + // Clean up call + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + // Execute create index this.db.ensureIndex(this.collectionName, fieldOrSpec, options, callback); }; @@ -1020,10 +1030,10 @@ Collection.prototype.reIndex = function(callback) { */ Collection.prototype.mapReduce = function mapReduce (map, reduce, options, callback) { if ('function' === typeof options) callback = options, options = {}; - - // Set default to go to the inline table otherwise it will break against - // previous versions of mongodb - if(null == options.out) options.out = "inline"; + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if(null == options.out) { + throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); + } if ('function' === typeof map) { map = map.toString(); diff --git a/node_modules/mongodb/lib/mongodb/db.js b/node_modules/mongodb/lib/mongodb/db.js index f34b4b0..ec6a5d8 100644 --- a/node_modules/mongodb/lib/mongodb/db.js +++ b/node_modules/mongodb/lib/mongodb/db.js @@ -605,13 +605,29 @@ Db.prototype.authenticate = function(username, password, callback) { /** * Add a user to the database. * + * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. + * * @param {String} username username. * @param {String} password password. + * @param {Object} [options] additional options during update. * @param {Function} callback returns the results. * @return {null} * @api public */ -Db.prototype.addUser = function(username, password, callback) { +Db.prototype.addUser = function(username, password, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + // Figure out the safe mode settings + var safe = self.strict != null && self.strict == false ? true : self.strict; + // Override with options passed in if applicable + safe = options != null && options['safe'] != null ? options['safe'] : safe; + // Ensure it's at least set to safe + safe = safe == null ? true : safe; + // Use node md5 generator var md5 = crypto.createHash('md5'); // Generate keys used for authentication @@ -624,11 +640,11 @@ Db.prototype.addUser = function(username, password, callback) { if(err != null) return callback(err, null); // We have a user, let's update the password if(documents.length > 0) { - collection.update({user: username},{user: username, pwd: userPassword}, {safe:true}, function(err, results) { + collection.update({user: username},{user: username, pwd: userPassword}, {safe:safe}, function(err, results) { callback(err, documents); }); } else { - collection.insert({user: username, pwd: userPassword}, {safe:true}, function(err, documents) { + collection.insert({user: username, pwd: userPassword}, {safe:safe}, function(err, documents) { callback(err, documents); }); } @@ -639,17 +655,33 @@ Db.prototype.addUser = function(username, password, callback) { /** * Remove a user from a database * + * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. + * * @param {String} username username. + * @param {Object} [options] additional options during update. * @param {Function} callback returns the results. * @return {null} * @api public */ -Db.prototype.removeUser = function(username, callback) { +Db.prototype.removeUser = function(username, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + // Figure out the safe mode settings + var safe = self.strict != null && self.strict == false ? true : self.strict; + // Override with options passed in if applicable + safe = options != null && options['safe'] != null ? options['safe'] : safe; + // Ensure it's at least set to safe + safe = safe == null ? true : safe; + // Fetch a user collection this.collection(DbCommand.SYSTEM_USER_COLLECTION, function(err, collection) { collection.findOne({user: username}, function(err, user) { if(user != null) { - collection.remove({user: username}, function(err, result) { + collection.remove({user: username}, {safe:safe}, function(err, result) { callback(err, true); }); } else { @@ -684,6 +716,14 @@ Db.prototype.createCollection = function(collectionName, options, callback) { callback = args.pop(); options = args.length ? args.shift() : null; var self = this; + + // Figure out the safe mode settings + var safe = self.strict != null && self.strict == false ? true : self.strict; + // Override with options passed in if applicable + safe = options != null && options['safe'] != null ? options['safe'] : safe; + // Ensure it's at least set to safe + safe = safe == null ? true : safe; + // Check if we have the name this.collectionNames(collectionName, function(err, collections) { if(err != null) return callback(err, null); @@ -706,7 +746,7 @@ Db.prototype.createCollection = function(collectionName, options, callback) { } // Create a new collection and return it - self._executeQueryCommand(DbCommand.createCreateCollectionCommand(self, collectionName, options), {read:false, safe:true}, function(err, result) { + self._executeQueryCommand(DbCommand.createCreateCollectionCommand(self, collectionName, options), {read:false, safe:safe}, function(err, result) { var document = result.documents[0]; // If we have no error let's return the collection if(err == null && document.ok == 1) { @@ -886,6 +926,7 @@ Db.prototype.resetErrorHistory = function(options, callback) { * Creates an index on the collection. * * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. * - **unique** {Boolean, default:false}, creates an unique index. * - **sparse** {Boolean, default:false}, creates a sparse index. * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. @@ -901,11 +942,22 @@ Db.prototype.resetErrorHistory = function(options, callback) { * @api public */ Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callback) { - if(callback == null) { callback = options; options = null; } - var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + // Figure out the safe mode settings + var safe = self.strict != null && self.strict == false ? true : self.strict; + // Override with options passed in if applicable + safe = options != null && options['safe'] != null ? options['safe'] : safe; + // Ensure it's at least set to safe + safe = safe == null ? true : safe; + + // Create command + var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); // Execute insert command - this._executeInsertCommand(command, {read:false, safe:true}, function(err, result) { + this._executeInsertCommand(command, {read:false, safe:safe}, function(err, result) { if(err != null) return callback(err, null); result = result && result.documents; @@ -921,6 +973,7 @@ Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callba * Ensures that an index exists, if it does not it creates it * * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a * - **unique** {Boolean, default:false}, creates an unique index. * - **sparse** {Boolean, default:false}, creates a sparse index. * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. @@ -937,7 +990,19 @@ Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callba * @api public */ Db.prototype.ensureIndex = function(collectionName, fieldOrSpec, options, callback) { - if(callback == null) { callback = options; options = null; } + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + // Figure out the safe mode settings + var safe = self.strict != null && self.strict == false ? true : self.strict; + // Override with options passed in if applicable + safe = options != null && options['safe'] != null ? options['safe'] : safe; + // Ensure it's at least set to safe + safe = safe == null ? true : safe; + + // Create command var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); var index_name = command.documents[0].name; var self = this; @@ -946,7 +1011,7 @@ Db.prototype.ensureIndex = function(collectionName, fieldOrSpec, options, callba if(err != null) return callback(err, null); if(!collectionInfo[index_name]) { - self._executeInsertCommand(command, {read:false, safe:true}, function(err, result) { + self._executeInsertCommand(command, {read:false, safe:safe}, function(err, result) { // Only callback if we have one specified if(typeof callback === 'function') { if(err != null) return callback(err, null); @@ -1385,6 +1450,7 @@ Db.prototype._executeQueryCommand = function(db_command, options, callback) { var __executeInsertCommand = function(self, db_command, options, callback) { // Always checkout a writer for this kind of operations var connection = self.serverConfig.checkoutWriter(); + // Get strict mode var safe = options['safe'] != null ? options['safe'] : false; var raw = options['raw'] != null ? options['raw'] : self.raw; var specifiedConnection = options['connection'] != null ? options['connection'] : null; diff --git a/node_modules/mongodb/lib/mongodb/gridfs/readstream.js b/node_modules/mongodb/lib/mongodb/gridfs/readstream.js index 423abd4..427cb4d 100644 --- a/node_modules/mongodb/lib/mongodb/gridfs/readstream.js +++ b/node_modules/mongodb/lib/mongodb/gridfs/readstream.js @@ -148,6 +148,9 @@ ReadStream.prototype.destroy = function() { * @api public */ ReadStream.prototype.resume = function() { + if (this.paused === false) { + return; + } this.paused = false; var self = this; if(self.pendingChunk != null) { diff --git a/node_modules/mongodb/package.json b/node_modules/mongodb/package.json index 8a9bf48..6011cb9 100644 --- a/node_modules/mongodb/package.json +++ b/node_modules/mongodb/package.json @@ -1,7 +1,7 @@ { "name" : "mongodb" , "description" : "A node.js driver for MongoDB" , "keywords" : ["mongodb", "mongo", "driver", "db"] -, "version" : "0.9.9" +, "version" : "0.9.9-1" , "author" : "Christian Amor Kvalheim " , "contributors" : [ "Aaron Heckmann", "Christoph Pojer", @@ -64,8 +64,11 @@ "dox": "0.1.3" , "uglify-js": "1.2.5" , "ejs": "0.6.1" - , "nodeunit": "0.6.4" - , "markdown": "0.3.1" + , "nodeunit": "0.7.3" + , "github3": ">=0.3.0" + , "markdown": "0.3.1" + , "gleak": "0.2.3" + , "step": "0.0.5" } , "config": { "native" : false } , "main": "./lib/mongodb/index" diff --git a/node_modules/mongodb/test/admin_test.js b/node_modules/mongodb/test/admin_test.js deleted file mode 100644 index 3c504d0..0000000 --- a/node_modules/mongodb/test/admin_test.js +++ /dev/null @@ -1,698 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/*! - * Module dependencies. - */ -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.shouldCorrectlyCallValidateCollection = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - fs_client.collection('test', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, doc) { - fs_client.admin(function(err, adminDb) { - adminDb.addUser('admin', 'admin', function(err, result) { - adminDb.authenticate('admin', 'admin', function(err, replies) { - adminDb.validateCollection('test', function(err, doc) { - // Pre 1.9.1 servers - if(doc.result != null) { - test.ok(doc.result != null); - test.ok(doc.result.match(/firstExtent/) != null); - } else { - test.ok(doc.firstExtent != null); - } - - fs_client.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Authenticate against MongoDB Admin user - * - * @_class admin - * @_function authenticate - * @ignore - */ -exports.shouldCorrectlyAuthenticate = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Grab a collection object - db.collection('test', function(err, collection) { - - // Force the creation of the collection by inserting a document - // Collections are not created until the first document is inserted - collection.insert({'a':1}, {safe:true}, function(err, doc) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Example showing how to access the Admin database for admin level operations. - * - * @_class db - * @_function admin - * @ignore - */ -exports.shouldCorrectlyAuthenticate = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); -} - -/** - * Retrieve the buildInfo for the current MongoDB instance - * - * @_class admin - * @_function buildInfo - * @ignore - */ -exports.shouldCorrectlyAuthenticate = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - // Retrive the build information for the MongoDB instance - adminDb.buildInfo(function(err, info) { - test.ok(err == null); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the buildInfo using the command function - * - * @_class admin - * @_function command - * @ignore - */ -exports.shouldCorrectlyAuthenticate = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - // Retrive the build information using the admin command - adminDb.command({buildInfo:1}, function(err, info) { - test.ok(err == null); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the current profiling level set for the MongoDB instance - * - * @_class admin - * @_function profilingLevel - * @ignore - */ -exports.shouldCorrectlySetDefaultProfilingLevel = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Grab a collection object - db.collection('test', function(err, collection) { - - // Force the creation of the collection by inserting a document - // Collections are not created until the first document is inserted - collection.insert({'a':1}, {safe:true}, function(err, doc) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, replies) { - - // Retrive the profiling level - adminDb.profilingLevel(function(err, level) { - test.equal("off", level); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * An example of how to use the setProfilingInfo - * Use this command to set the Profiling level on the MongoDB server - * - * @_class admin - * @_function setProfilingLevel - */ -exports.shouldCorrectlyChangeProfilingLevel = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Grab a collection object - db.collection('test', function(err, collection) { - - // Force the creation of the collection by inserting a document - // Collections are not created until the first document is inserted - collection.insert({'a':1}, {safe:true}, function(err, doc) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, replies) { - - // Set the profiling level to only profile slow queries - adminDb.setProfilingLevel('slow_only', function(err, level) { - - // Retrive the profiling level and verify that it's set to slow_only - adminDb.profilingLevel(function(err, level) { - test.equal('slow_only', level); - - // Turn profiling off - adminDb.setProfilingLevel('off', function(err, level) { - - // Retrive the profiling level and verify that it's set to off - adminDb.profilingLevel(function(err, level) { - test.equal('off', level); - - // Set the profiling level to log all queries - adminDb.setProfilingLevel('all', function(err, level) { - - // Retrive the profiling level and verify that it's set to all - adminDb.profilingLevel(function(err, level) { - test.equal('all', level); - - // Attempt to set an illegal profiling level - adminDb.setProfilingLevel('medium', function(err, level) { - test.ok(err instanceof Error); - test.equal("Error: illegal profiling level value medium", err.message); - - db.close(); - test.done(); - }); - }) - }); - }) - }); - }) - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * An example of how to use the profilingInfo - * Use this command to pull back the profiling information currently set for Mongodb - * - * @_class admin - * @_function profilingInfo - */ -exports.shouldCorrectlySetAndExtractProfilingInfo = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Grab a collection object - db.collection('test', function(err, collection) { - - // Force the creation of the collection by inserting a document - // Collections are not created until the first document is inserted - collection.insert({'a':1}, {safe:true}, function(doc) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, replies) { - - // Set the profiling level to all - adminDb.setProfilingLevel('all', function(err, level) { - - // Execute a query command - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - - // Turn off profiling - adminDb.setProfilingLevel('off', function(err, level) { - - // Retrive the profiling information - adminDb.profilingInfo(function(err, infos) { - test.ok(infos.constructor == Array); - test.ok(infos.length >= 1); - test.ok(infos[0].ts.constructor == Date); - test.ok(infos[0].millis.constructor == Number); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * An example of how to use the validateCollection command - * Use this command to check that a collection is valid (not corrupt) and to get various statistics. - * - * @_class admin - * @_function validateCollection - */ -exports.shouldCorrectlyCallValidateCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Grab a collection object - db.collection('test', function(err, collection) { - - // Force the creation of the collection by inserting a document - // Collections are not created until the first document is inserted - collection.insert({'a':1}, {safe:true}, function(err, doc) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, replies) { - - // Validate the 'test' collection - adminDb.validateCollection('test', function(err, doc) { - - // Pre 1.9.1 servers - if(doc.result != null) { - test.ok(doc.result != null); - test.ok(doc.result.match(/firstExtent/) != null); - } else { - test.ok(doc.firstExtent != null); - } - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * An example of how to add a user to the admin database - * - * @_class admin - * @_function ping - */ -exports.shouldCorrectlyPingTheMongoDbInstance = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - // Ping the server - adminDb.ping(function(err, pingResult) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An example of how add a user, authenticate and logout - * - * @_class admin - * @_function logout - */ -exports.shouldCorrectlyUseLogoutFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - // Logout the user - adminDb.logout(function(err, result) { - test.equal(true, result); - - db.close(); - test.done(); - }) - }); - }); - }); - }); - }); -} - - -/** - * An example of how to add a user to the admin database - * - * @_class admin - * @_function addUser - */ -exports.shouldCorrectlyAddAUserToAdminDb = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * An example of how to remove a user from the admin database - * - * @_class admin - * @_function removeUser - */ -exports.shouldCorrectlyAddAUserAndRemoveItFromAdminDb = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - // Remove the user - adminDb.removeUser('admin', function(err, result) { - - // Authenticate using the removed user should fail - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(err != null); - test.ok(!result); - - db.close(); - test.done(); - }); - }) - }); - }); - }); - }); - }); -} - -/** - * An example of listing all available databases. - * - * @_class admin - * @_function listDatabases - */ -exports.shouldCorrectlyListAllAvailableDatabases = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // List all the available databases - adminDb.listDatabases(function(err, dbs) { - test.equal(null, err); - test.ok(dbs.databases.length > 0); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/authentication_test.js b/node_modules/mongodb/test/authentication_test.js deleted file mode 100644 index 599b822..0000000 --- a/node_modules/mongodb/test/authentication_test.js +++ /dev/null @@ -1,171 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * Test the authentication method for the user - * - * @ignore - */ -exports.shouldCorrectlyAuthenticate = function(test) { - var user_name = 'spongebob'; - var password = 'squarepants'; - - client.authenticate('admin', 'admin', function(err, replies) { - test.ok(err instanceof Error); - test.ok(!replies); - - // Add a user - client.addUser(user_name, password, function(err, result) { - client.authenticate(user_name, password, function(err, replies) { - test.ok(!(err instanceof Error)); - test.ok(replies); - test.done(); - }); - }); - }); -} - -/** - * Test the authentication method for the user - * - * @ignore - */ -exports.shouldCorrectlyReAuthorizeReconnectedConnections = function(test) { - var user_name = 'spongebob2'; - var password = 'password'; - - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:3, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, automatic_connect_client) { - p_client.authenticate('admin', 'admin', function(err, replies) { - test.ok(err instanceof Error); - // Add a user - p_client.addUser(user_name, password, function(err, result) { - // Execute authentication - p_client.authenticate(user_name, password, function(err, replies) { - test.ok(err == null); - - // Kill a connection to force a reconnect - p_client.serverConfig.close(); - - p_client.createCollection('shouldCorrectlyReAuthorizeReconnectedConnections', function(err, collection) { - collection.insert({a:1}, {safe:true}, function(err, r) { - collection.insert({a:2}, {safe:true}, function(err, r) { - collection.insert({a:3}, {safe:true}, function(err, r) { - collection.count(function(err, count) { - test.equal(3, count); - p_client.close(); - test.done(); - }) - }) - }) - }) - }); - }); - }); - }); - }); -} - -exports.shouldCorrectlyAddAndRemoveUser = function(test) { - var user_name = 'spongebob2'; - var password = 'password'; - - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, automatic_connect_client) { - p_client.authenticate('admin', 'admin', function(err, replies) { - test.ok(err instanceof Error); - - // Add a user - p_client.addUser(user_name, password, function(err, result) { - p_client.authenticate(user_name, password, function(err, replies) { - test.ok(replies); - - // Remove the user and try to authenticate again - p_client.removeUser(user_name, function(err, result) { - p_client.authenticate(user_name, password, function(err, replies) { - test.ok(err instanceof Error); - - test.done(); - p_client.close(); - }); - }); - }); - }); - }); - }); -} - -// run this last -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/auxilliary/authentication_test.js b/node_modules/mongodb/test/auxilliary/authentication_test.js deleted file mode 100644 index 5facab6..0000000 --- a/node_modules/mongodb/test/auxilliary/authentication_test.js +++ /dev/null @@ -1,216 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server, - ServerManager = require('../../test/tools/server_manager').ServerManager, - Step = require("../../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var serverManager = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - serverManager.killAll(function(err, result) { - callback(); - }); -} - -exports.shouldCorrectlyAuthenticate = function(test) { - var db1 = new Db('mongo-ruby-test-auth1', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - var db2 = new Db('mongo-ruby-test-auth2', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - var admin = new Db('admin', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - - Step( - function bootTheServerWithNoAuth() { - serverManager = new ServerManager({auth:false, purgedirectories:true}) - serverManager.start(true, this); - }, - - function openDbs() { - db1.open(this.parallel()); - db2.open(this.parallel()); - admin.open(this.parallel()); - }, - - function addAdminUserToDatabase(err, db1, db2, admin) { - test.equal(null, err); - admin.addUser('admin', 'admin', this); - }, - - function restartServerInAuthMode(err, result) { - test.equal(null, err); - test.equal('7c67ef13bbd4cae106d959320af3f704', result.shift().pwd); - - db1.close(); - db2.close(); - admin.close(); - - serverManager = new ServerManager({auth:true, purgedirectories:false}) - serverManager.start(true, this); - }, - - function openDbs() { - db1.open(this.parallel()); - db2.open(this.parallel()); - admin.open(this.parallel()); - }, - - function authenticateAdminUser(err) { - test.equal(null, err); - - admin.authenticate('admin', 'admin', this.parallel()); - db1.admin().authenticate('admin', 'admin', this.parallel()); - db2.admin().authenticate('admin', 'admin', this.parallel()); - }, - - function addDbUsersForAuthentication(err, result1, result2, result3) { - test.equal(null, err); - test.ok(result1); - test.ok(result2); - test.ok(result3); - - db1.addUser('user1', 'secret', this.parallel()); - db2.addUser('user2', 'secret', this.parallel()); - }, - - function closeAdminConnection(err, result1, result2) { - test.ok(err == null); - test.ok(result1 != null); - test.ok(result2 != null); - admin.logout(this.parallel()); - db1.admin().logout(this.parallel()); - db2.admin().logout(this.parallel()); - }, - - function failAuthenticationWithDbs(err, result) { - var self = this; - - db1.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - - db2.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - }, - - function authenticateAgainstDbs(err, result) { - test.ok(err != null); - - db1.authenticate('user1', 'secret', this.parallel()); - db2.authenticate('user2', 'secret', this.parallel()); - }, - - function correctlyInsertRowToDbs(err, result1, result2) { - var self = this; - test.ok(err == null); - test.ok(result1); - test.ok(result2); - - db1.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - - db2.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - }, - - function validateCorrectInsertsAndBounceServer(err, result1, result2) { - test.ok(err == null); - test.ok(result1 != null); - test.ok(result2 != null); - - serverManager = new ServerManager({auth:true, purgedirectories:false}) - serverManager.start(true, this); - }, - - function reconnectAndVerifyThatAuthIsAutomaticallyApplied() { - var self = this; - db1.collection('stuff', function(err, collection) { - - collection.find({}).toArray(function(err, items) { - test.ok(err == null); - test.equal(1, items.length); - - db1.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - - db2.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - }) - }); - }, - - function logoutDb1(err, result1, result2) { - test.ok(err == null); - test.ok(result1 != null); - test.ok(result2 != null); - - db1.logout(this); - }, - - function insertShouldFail(err, result) { - var self = this; - db1.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - }, - - function logoutDb2(err, result) { - test.ok(err != null); - db2.logout(this); - }, - - function insertShouldFail(err, result) { - var self = this; - db2.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, function(err, result) { - test.ok(err != null); - test.done(); - // Close all connections - db1.close(); - db2.close(); - admin.close(); - }); - }); - } - ) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/auxilliary/repl_set_ssl_test.js b/node_modules/mongodb/test/auxilliary/repl_set_ssl_test.js deleted file mode 100644 index 1bf21ef..0000000 --- a/node_modules/mongodb/test/auxilliary/repl_set_ssl_test.js +++ /dev/null @@ -1,80 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server, - ReplSetServers = mongodb.ReplSetServers, - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager, - Step = require("../../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var serverManager = null; -var RS = RS == null ? null : RS; -var ssl = true; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - RS = new ReplicaSetManager({retries:120, - ssl:ssl, - arbiter_count:1, - secondary_count:1, - passive_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - RS.restartKilledNodes(function(err, result) { - callback(); - }); -} - -exports.shouldCorrectlyConncetToSSLBasedReplicaset = function(test) { - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name, ssl:ssl} - ); - - // Connect to the replicaset - var slaveDb = null; - var db = new Db('foo', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - test.equal(null, err); - test.done(); - p_db.close(); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/auxilliary/replicaset_auth_test.js b/node_modules/mongodb/test/auxilliary/replicaset_auth_test.js deleted file mode 100644 index 34ab2ff..0000000 --- a/node_modules/mongodb/test/auxilliary/replicaset_auth_test.js +++ /dev/null @@ -1,242 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server, - ReplSetServers = mongodb.ReplSetServers, - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager, - Step = require("../../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var serverManager = null; -var RS = RS == null ? null : RS; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - RS = new ReplicaSetManager({retries:120, - auth:true, - arbiter_count:0, - secondary_count:1, - passive_count:0}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports.shouldCorrectlyAuthenticateWithMultipleLoginsAndLogouts = function(test) { - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name} - ); - - // Connect to the replicaset - var slaveDb = null; - var db = new Db('foo', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - Step( - function addUser() { - db.admin().addUser("me", "secret", this); - }, - - function ensureFailingInsert(err, result) { - // return - var self = this; - test.equal(null, err); - test.ok(result != null); - - db.collection("stuff", function(err, collection) { - collection.insert({a:2}, {safe: {w: 3}}, self); - }); - }, - - function authenticate(err, result) { - test.ok(err != null); - - db.admin().authenticate("me", "secret", this); - }, - - function changePassword(err, result) { - var self = this; - test.equal(null, err); - test.ok(result); - - db.admin().addUser("me", "secret2", this); - }, - - function authenticate(err, result) { - db.admin().authenticate("me", "secret2", this); - }, - - function insertShouldSuccedNow(err, result) { - var self = this; - test.equal(null, err); - test.ok(result); - - db.collection("stuff", function(err, collection) { - collection.insert({a:3}, {safe: true}, self); - }); - }, - - function queryShouldExecuteCorrectly(err, result) { - var self = this; - test.equal(null, err); - - db.collection("stuff", function(err, collection) { - collection.findOne(self); - }); - }, - - function logout(err, item) { - test.ok(err == null); - test.equal(3, item.a); - - db.admin().logout(this); - }, - - function findShouldFailDueToLoggedOut(err, result) { - var self = this; - test.equal(null, err); - - db.collection("stuff", function(err, collection) { - collection.findOne(self); - }); - }, - - function sameShouldApplyToRandomSecondaryServer(err, result) { - var self = this; - test.ok(err != null); - - slaveDb = new Db('foo', new Server(db.serverConfig.secondaries[0].host - , db.serverConfig.secondaries[0].port, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null), slave_ok:true}); - slaveDb.open(function(err, slaveDb) { - slaveDb.collection('stuff', function(err, collection) { - collection.findOne(self) - }) - }); - }, - - function shouldCorrectlyAuthenticateAgainstSecondary(err, result) { - test.ok(err != null) - slaveDb.admin().authenticate('me', 'secret2', this); - }, - - function shouldCorrectlyInsertItem(err, result) { - var self = this; - test.equal(null, err); - test.ok(result); - - slaveDb.collection('stuff', function(err, collection) { - collection.findOne(self) - }) - }, - - function finishUp(err, item) { - test.ok(err == null); - test.equal(3, item.a); - - test.done(); - p_db.close(); - slaveDb.close(); - } - ) - }); -} - -exports.shouldCorrectlyAuthenticate = function(test) { - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Connect to the replicaset - var slaveDb = null; - var db = new Db('foo', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - Step( - function addUser() { - db.admin().addUser("me", "secret", this); - }, - - function ensureFailingInsert(err, result) { - var self = this; - test.equal(null, err); - test.ok(result != null); - - db.collection("stuff", function(err, collection) { - collection.insert({a:2}, {safe: {w: 2, wtimeout: 10000}}, self); - }); - }, - - function authenticate(err, result) { - test.ok(err != null); - - db.admin().authenticate("me", "secret", this); - }, - - function insertShouldSuccedNow(err, result) { - var self = this; - test.equal(null, err); - test.ok(result); - - db.collection("stuff", function(err, collection) { - collection.insert({a:2}, {safe: {w: 2, wtimeout: 10000}}, self); - }); - }, - - function queryShouldExecuteCorrectly(err, result) { - var self = this; - test.equal(null, err); - - db.collection("stuff", function(err, collection) { - collection.findOne(self); - }); - }, - - function finishUp(err, item) { - test.ok(err == null); - test.equal(2, item.a); - test.done(); - p_db.close(); - } - ) - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/auxilliary/single_server_kill_reconnect.js b/node_modules/mongodb/test/auxilliary/single_server_kill_reconnect.js deleted file mode 100644 index bb41b9f..0000000 --- a/node_modules/mongodb/test/auxilliary/single_server_kill_reconnect.js +++ /dev/null @@ -1,159 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server, - ServerManager = require('../../test/tools/server_manager').ServerManager, - Step = require("../../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var serverManager = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports.shouldCorrectlyKeepInsertingDocumentsWhenServerDiesAndComesUp = function(test) { - var db1 = new Db('mongo-ruby-test-single-server', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // All inserted docs - var docs = []; - var errs = []; - var insertDocs = []; - // Start server - serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true}) - serverManager.start(true, function() { - db1.open(function(err, db) { - // Startup the insert of documents - var intervalId = setInterval(function() { - db.collection('inserts', function(err, collection) { - var doc = {timestamp:new Date().getTime()}; - insertDocs.push(doc); - // Insert document - collection.insert(doc, {safe:{fsync:true}}, function(err, result) { - // Save errors - if(err != null) errs.push(err); - if(err == null) { - docs.push(result[0]); - } - }) - }); - }, 500); - - // Wait for a second and then kill the server - setTimeout(function() { - // Kill server instance - serverManager.stop(9, function(err, result) { - // Server down for 1 second - setTimeout(function() { - // Restart server - serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true}); - serverManager.start(true, function() { - // Wait for it - setTimeout(function() { - // Drop db - db.dropDatabase(function(err, result) { - clearInterval(intervalId); - // Close db - db.close(); - // Check that we got at least one error - test.ok(docs.length > 0); - test.ok(insertDocs.length > 0); - // Finish up - test.done(); - }); - }, 5000) - }) - }, 1000); - }); - }, 3000); - }) - }); -} - -exports.shouldCorrectlyInsertKillServerFailThenRestartServerAndSucceed = function(test) { - var db = new Db('test-single-server-recovery', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {numberOfRetries:3, retryMiliSeconds:500, native_parser: (process.env['TEST_NATIVE'] != null)}); - // All inserted docs - var docs = []; - var errs = []; - var insertDocs = []; - - // Start server - serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true}) - serverManager.start(true, function() { - db.open(function(err, db) { - // Add an error handler - db.on("error", function(err) { - console.log("----------------------------------------------- received error") - console.dir(err) - errs.push(err); - }); - - db.collection('inserts', function(err, collection) { - var doc = {timestamp:new Date().getTime(), a:1}; - collection.insert(doc, {safe:true}, function(err, result) { - test.equal(null, err); - - // Kill server instance - serverManager.stop(9, function(err, result) { - // Attemp insert (should timeout) - var doc = {timestamp:new Date().getTime(), b:1}; - collection.insert(doc, {safe:true}, function(err, result) { - test.ok(err != null); - test.equal(null, result); - - // Restart server - serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true}); - serverManager.start(true, function() { - // Attemp insert again - collection.insert(doc, {safe:true}, function(err, result) { - // Fetch the documents - collection.find({b:1}).toArray(function(err, items) { - test.equal(null, err); - test.equal(1, items[0].b); - db.close(); - test.done(); - }); - }); - }); - }); - }); - }) - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/auxilliary/ssl_test.js b/node_modules/mongodb/test/auxilliary/ssl_test.js deleted file mode 100644 index c95620b..0000000 --- a/node_modules/mongodb/test/auxilliary/ssl_test.js +++ /dev/null @@ -1,78 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server, - ServerManager = require('../../test/tools/server_manager').ServerManager, - Step = require("../../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var serverManager = null; -var ssl = true; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports.shouldCorrectlyCommunicateUsingSSLSocket = function(test) { - var db1 = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize:4, ssl:ssl}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // All inserted docs - var docs = []; - var errs = []; - var insertDocs = []; - - // Start server - serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true, ssl:ssl}) - serverManager.start(true, function() { - db1.open(function(err, db) { - // Create a collection - db.createCollection('shouldCorrectlyCommunicateUsingSSLSocket', function(err, collection) { - collection.insert([{a:1}, {b:2}, {c:'hello world'}]); - collection.insert([{a:1}, {b:2}, {c:'hello world'}]); - collection.insert([{a:1}, {b:2}, {c:'hello world'}]); - collection.insert([{a:1}, {b:2}, {c:'hello world'}]); - collection.insert([{a:1}, {b:2}, {c:'hello world'}], {safe:true}, function(err, result) { - collection.find({}).toArray(function(err, items) { - // test.equal(3, items.length); - db.close(); - test.done(); - }) - }); - }); - }) - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/bson/bson_test.js b/node_modules/mongodb/test/bson/bson_test.js deleted file mode 100644 index b28aea4..0000000 --- a/node_modules/mongodb/test/bson/bson_test.js +++ /dev/null @@ -1,1606 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - mongoO = require('../../lib/mongodb').pure(), - debug = require('util').debug, - inspect = require('util').inspect, - Buffer = require('buffer').Buffer, - gleak = require('../../dev/tools/gleak'), - fs = require('fs'), - BSON = mongoO.BSON, - Code = mongoO.Code, - Binary = mongoO.Binary, - Timestamp = mongoO.Timestamp, - Long = mongoO.Long, - MongoReply = mongoO.MongoReply, - ObjectID = mongoO.ObjectID, - Symbol = mongoO.Symbol, - DBRef = mongoO.DBRef, - Double = mongoO.Double, - MinKey = mongoO.MinKey, - MaxKey = mongoO.MaxKey, - BinaryParser = mongoO.BinaryParser; - -var BSONSE = mongodb, - BSONDE = mongodb; - -// for tests -BSONDE.BSON_BINARY_SUBTYPE_DEFAULT = 0; -BSONDE.BSON_BINARY_SUBTYPE_FUNCTION = 1; -BSONDE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -BSONDE.BSON_BINARY_SUBTYPE_UUID = 3; -BSONDE.BSON_BINARY_SUBTYPE_MD5 = 4; -BSONDE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -BSONSE.BSON_BINARY_SUBTYPE_DEFAULT = 0; -BSONSE.BSON_BINARY_SUBTYPE_FUNCTION = 1; -BSONSE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -BSONSE.BSON_BINARY_SUBTYPE_UUID = 3; -BSONSE.BSON_BINARY_SUBTYPE_MD5 = 4; -BSONSE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -var hexStringToBinary = function(string) { - var numberofValues = string.length / 2; - var array = ""; - - for(var i = 0; i < numberofValues; i++) { - array += String.fromCharCode(parseInt(string[i*2] + string[i*2 + 1], 16)); - } - return array; -} - -var assertBuffersEqual = function(test, buffer1, buffer2) { - if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2); - - for(var i = 0; i < buffer1.length; i++) { - test.equal(buffer1[i], buffer2[i]); - } -} - -/** - * Module for parsing an ISO 8601 formatted string into a Date object. - */ -var ISODate = function (string) { - var match; - - if (typeof string.getTime === "function") - return string; - else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) { - var date = new Date(); - date.setUTCFullYear(Number(match[1])); - date.setUTCMonth(Number(match[3]) - 1 || 0); - date.setUTCDate(Number(match[5]) || 0); - date.setUTCHours(Number(match[7]) || 0); - date.setUTCMinutes(Number(match[8]) || 0); - date.setUTCSeconds(Number(match[10]) || 0); - date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0); - - if (match[13] && match[13] !== "Z") { - var h = Number(match[16]) || 0, - m = Number(match[17]) || 0; - - h *= 3600000; - m *= 60000; - - var offset = h + m; - if (match[15] == "+") - offset = -offset; - - date = new Date(date.valueOf() + offset); - } - - return date; - } else - throw new Error("Invalid ISO 8601 date given.", __filename); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -/** - * @ignore - */ -exports['Should Correctly get BSON types from require'] = function(test) { - var _mongodb = require('../../lib/mongodb'); - test.ok(_mongodb.ObjectID === ObjectID); - test.ok(_mongodb.Binary === Binary); - test.ok(_mongodb.Long === Long); - test.ok(_mongodb.Timestamp === Timestamp); - test.ok(_mongodb.Code === Code); - test.ok(_mongodb.DBRef === DBRef); - test.ok(_mongodb.Symbol === Symbol); - test.ok(_mongodb.MinKey === MinKey); - test.ok(_mongodb.MaxKey === MaxKey); - test.ok(_mongodb.Double === Double); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Deserialize object'] = function(test) { - var bytes = [95,0,0,0,2,110,115,0,42,0,0,0,105,110,116,101,103,114,97,116,105,111,110,95,116,101,115,116,115,95,46,116,101,115,116,95,105,110,100,101,120,95,105,110,102,111,114,109,97,116,105,111,110,0,8,117,110,105,113,117,101,0,0,3,107,101,121,0,12,0,0,0,16,97,0,1,0,0,0,0,2,110,97,109,101,0,4,0,0,0,97,95,49,0,0]; - var serialized_data = ''; - // Convert to chars - for(var i = 0; i < bytes.length; i++) { - serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]); - } - - var object = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(new Buffer(serialized_data, 'binary')); - test.equal("a_1", object.name); - test.equal(false, object.unique); - test.equal(1, object.key.a); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Deserialize object with all types'] = function(test) { - var bytes = [26,1,0,0,7,95,105,100,0,161,190,98,75,118,169,3,0,0,3,0,0,4,97,114,114,97,121,0,26,0,0,0,16,48,0,1,0,0,0,16,49,0,2,0,0,0,16,50,0,3,0,0,0,0,2,115,116,114,105,110,103,0,6,0,0,0,104,101,108,108,111,0,3,104,97,115,104,0,19,0,0,0,16,97,0,1,0,0,0,16,98,0,2,0,0,0,0,9,100,97,116,101,0,161,190,98,75,0,0,0,0,7,111,105,100,0,161,190,98,75,90,217,18,0,0,1,0,0,5,98,105,110,97,114,121,0,7,0,0,0,2,3,0,0,0,49,50,51,16,105,110,116,0,42,0,0,0,1,102,108,111,97,116,0,223,224,11,147,169,170,64,64,11,114,101,103,101,120,112,0,102,111,111,98,97,114,0,105,0,8,98,111,111,108,101,97,110,0,1,15,119,104,101,114,101,0,25,0,0,0,12,0,0,0,116,104,105,115,46,120,32,61,61,32,51,0,5,0,0,0,0,3,100,98,114,101,102,0,37,0,0,0,2,36,114,101,102,0,5,0,0,0,116,101,115,116,0,7,36,105,100,0,161,190,98,75,2,180,1,0,0,2,0,0,0,10,110,117,108,108,0,0]; - var serialized_data = ''; - // Convert to chars - for(var i = 0; i < bytes.length; i++) { - serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]); - } - - var object = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(new Buffer(serialized_data, 'binary'));//, false, true); - // Perform tests - test.equal("hello", object.string); - test.deepEqual([1,2,3], object.array); - test.equal(1, object.hash.a); - test.equal(2, object.hash.b); - test.ok(object.date != null); - test.ok(object.oid != null); - test.ok(object.binary != null); - test.equal(42, object.int); - test.equal(33.3333, object.float); - test.ok(object.regexp != null); - test.equal(true, object.boolean); - test.ok(object.where != null); - test.ok(object.dbref != null); - test.ok(object[null] == null); - test.done(); -} - -/** - * @ignore - */ -exports['Should Serialize and Deserialize String'] = function(test) { - var test_string = {hello: 'world'}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_string, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_string)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_string, false, serialized_data2, 0); - - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_string, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Serialize and Deserialize Empty String'] = function(test) { - var test_string = {hello: ''}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_string, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_string)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_string, false, serialized_data2, 0); - - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_string, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Integer'] = function(test) { - var test_number = {doc: 5}; - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_number, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_number)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_number, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_number, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.deepEqual(test_number, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data2)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize null value'] = function(test) { - var test_null = {doc:null}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_null, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_null)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_null, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var object = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal(null, object.doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Number'] = function(test) { - var test_number = {doc: 5.5}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_number, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_number)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_number, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.deepEqual(test_number, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Integer'] = function(test) { - var test_int = {doc: 42}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); - - test_int = {doc: -5600}; - serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); - - test_int = {doc: 2147483647}; - serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); - - test_int = {doc: -2147483648}; - serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Object'] = function(test) { - var doc = {doc: {age: 42, name: 'Spongebob', shoe_size: 9.5}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.deepEqual(doc.doc.age, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.age); - test.deepEqual(doc.doc.name, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.name); - test.deepEqual(doc.doc.shoe_size, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.shoe_size); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Array'] = function(test) { - var doc = {doc: [1, 2, 'a', 'b']}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal(doc.doc[0], deserialized.doc[0]) - test.equal(doc.doc[1], deserialized.doc[1]) - test.equal(doc.doc[2], deserialized.doc[2]) - test.equal(doc.doc[3], deserialized.doc[3]) - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Array with added on functions'] = function(test) { - Array.prototype.toXml = function() {}; - var doc = {doc: [1, 2, 'a', 'b']}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal(doc.doc[0], deserialized.doc[0]) - test.equal(doc.doc[1], deserialized.doc[1]) - test.equal(doc.doc[2], deserialized.doc[2]) - test.equal(doc.doc[3], deserialized.doc[3]) - test.done(); -} - -/** - * @ignore - */ -exports['Should correctly deserialize a nested object'] = function(test) { - var doc = {doc: {doc:1}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.deepEqual(doc.doc.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize A Boolean'] = function(test) { - var doc = {doc: true}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.equal(doc.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize a Date'] = function(test) { - var date = new Date(); - //(2009, 11, 12, 12, 00, 30) - date.setUTCDate(12); - date.setUTCFullYear(2009); - date.setUTCMonth(11 - 1); - date.setUTCHours(12); - date.setUTCMinutes(0); - date.setUTCSeconds(30); - var doc = {doc: date}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.equal(doc.date, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.date); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize nested doc'] = function(test) { - var doc = { - string: "Strings are great", - decimal: 3.14159265, - bool: true, - integer: 5, - - subObject: { - moreText: "Bacon ipsum dolor.", - longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly." - }, - - subArray: [1,2,3,4,5,6,7,8,9,10], - anotherString: "another string" - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Oid'] = function(test) { - var doc = {doc: new ObjectID()}; - var doc2 = {doc: ObjectID.createFromHexString(doc.doc.toHexString())}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - delete doc.doc.__id; - test.deepEqual(doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly encode Empty Hash'] = function(test) { - var doc = {}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.deepEqual(doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Ordered Hash'] = function(test) { - var doc = {doc: {b:1, a:2, c:3, d:4}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var decoded_hash = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc; - var keys = []; - - for(var name in decoded_hash) keys.push(name); - test.deepEqual(['b', 'a', 'c', 'd'], keys); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Regular Expression'] = function(test) { - // Serialize the regular expression - var doc = {doc: /foobar/mi}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc.doc.toString(), doc2.doc.toString()); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize a Binary object'] = function(test) { - var bin = new Binary(); - var string = 'binstring'; - for(var index = 0; index < string.length; index++) { - bin.put(string.charAt(index)); - } - - var doc = {doc: bin}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc.doc.value(), deserialized_data.doc.value()); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize a big Binary object'] = function(test) { - var data = fs.readFileSync("test/gridstore/test_gs_weird_bug.png", 'binary'); - var bin = new Binary(); - bin.write(data); - var doc = {doc: bin}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc.value(), deserialized_data.doc.value()); - test.done(); -} - -/** - * @ignore - */ -exports["Should Correctly Serialize and Deserialize DBRef"] = function(test) { - var oid = new ObjectID(); - var doc = {dbref: new DBRef('namespace', oid, null)}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal("namespace", doc2.dbref.namespace); - test.deepEqual(doc2.dbref.oid.toHexString(), oid.toHexString()); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize partial DBRef'] = function(test) { - var id = new ObjectID(); - var doc = {'name':'something', 'user':{'$ref':'username', '$id': id}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal('something', doc2.name); - test.equal('username', doc2.user.namespace); - test.equal(id.toString(), doc2.user.oid.toString()); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize simple Int'] = function(test) { - var doc = {doc:2147483648}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc, doc2.doc) - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Long Integer'] = function(test) { - var doc = {doc: Long.fromNumber(9223372036854775807)}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc, deserialized_data.doc); - - doc = {doc: Long.fromNumber(-9223372036854775)}; - serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc, deserialized_data.doc); - - doc = {doc: Long.fromNumber(-9223372036854775809)}; - serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc, deserialized_data.doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Deserialize Large Integers as Number not Long'] = function(test) { - function roundTrip(val) { - var doc = {doc: val}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc, deserialized_data.doc); - }; - - roundTrip(Math.pow(2,52)); - roundTrip(Math.pow(2,53) - 1); - roundTrip(Math.pow(2,53)); - roundTrip(-Math.pow(2,52)); - roundTrip(-Math.pow(2,53) + 1); - roundTrip(-Math.pow(2,53)); - roundTrip(Math.pow(2,65)); // Too big for Long. - roundTrip(-Math.pow(2,65)); - roundTrip(9223372036854775807); - roundTrip(1234567890123456800); // Bigger than 2^53, stays a double. - roundTrip(-1234567890123456800); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Long Integer and Timestamp as different types'] = function(test) { - var long = Long.fromNumber(9223372036854775807); - var timestamp = Timestamp.fromNumber(9223372036854775807); - test.ok(long instanceof Long); - test.ok(!(long instanceof Timestamp)); - test.ok(timestamp instanceof Timestamp); - test.ok(!(timestamp instanceof Long)); - - var test_int = {doc: long, doc2: timestamp}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(test_int.doc, deserialized_data.doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Always put the id as the first item in a hash'] = function(test) { - var hash = {doc: {not_id:1, '_id':2}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(hash, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(hash)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(hash, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - var keys = []; - - for(var name in deserialized_data.doc) { - keys.push(name); - } - - test.deepEqual(['not_id', '_id'], keys); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize a User defined Binary object'] = function(test) { - var bin = new Binary(); - bin.sub_type = BSON.BSON_BINARY_SUBTYPE_USER_DEFINED; - var string = 'binstring'; - for(var index = 0; index < string.length; index++) { - bin.put(string.charAt(index)); - } - - var doc = {doc: bin}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(deserialized_data.doc.sub_type, BSON.BSON_BINARY_SUBTYPE_USER_DEFINED); - test.deepEqual(doc.doc.value(), deserialized_data.doc.value()); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correclty Serialize and Deserialize a Code object'] = function(test) { - var doc = {'doc': {'doc2': new Code('this.a > i', {i:1})}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc.doc2.code, deserialized_data.doc.doc2.code); - test.deepEqual(doc.doc.doc2.scope.i, deserialized_data.doc.doc2.scope.i); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly serialize and deserialize and embedded array'] = function(test) { - var doc = {'a':0, - 'b':['tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9', 'tmp10', 'tmp11', 'tmp12', 'tmp13', 'tmp14', 'tmp15', 'tmp16'] - }; - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.a, deserialized_data.a); - test.deepEqual(doc.b, deserialized_data.b); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize UTF8'] = function(test) { - // Serialize utf8 - var doc = { "name" : "本荘由利地域に洪水警報", "name1" : "öüóőúéáűíÖÜÓŐÚÉÁŰÍ", "name2" : "abcdedede"}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc, deserialized_data); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize query object'] = function(test) { - var doc = { count: 'remove_with_no_callback_bug_test', query: {}, fields: null}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc, deserialized_data); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize empty query object'] = function(test) { - var doc = {}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc, deserialized_data); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize array based doc'] = function(test) { - var doc = { b: [ 1, 2, 3 ], _id: new ObjectID() }; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.b, deserialized_data.b) - test.deepEqual(doc, deserialized_data); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Symbol'] = function(test) { - if(Symbol != null) { - var doc = { b: [ new Symbol('test') ]}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.b, deserialized_data.b) - test.deepEqual(doc, deserialized_data); - test.ok(deserialized_data.b[0] instanceof Symbol); - } - - test.done(); -} - -/** - * @ignore - */ -exports['Should handle Deeply nested document'] = function(test) { - var doc = {a:{b:{c:{d:2}}}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc, deserialized_data); - test.done(); -} - -/** - * @ignore - */ -exports['Should handle complicated all typed object'] = function(test) { - // First doc - var date = new Date(); - var oid = new ObjectID(); - var string = 'binstring' - var bin = new Binary() - for(var index = 0; index < string.length; index++) { - bin.put(string.charAt(index)) - } - - var doc = { - 'string': 'hello', - 'array': [1,2,3], - 'hash': {'a':1, 'b':2}, - 'date': date, - 'oid': oid, - 'binary': bin, - 'int': 42, - 'float': 33.3333, - 'regexp': /regexp/, - 'boolean': true, - 'long': date.getTime(), - 'where': new Code('this.a > i', {i:1}), - 'dbref': new DBRef('namespace', oid, 'integration_tests_') - } - - // Second doc - var oid = new ObjectID.createFromHexString(oid.toHexString()); - var string = 'binstring' - var bin = new Binary() - for(var index = 0; index < string.length; index++) { - bin.put(string.charAt(index)) - } - - var doc2 = { - 'string': 'hello', - 'array': [1,2,3], - 'hash': {'a':1, 'b':2}, - 'date': date, - 'oid': oid, - 'binary': bin, - 'int': 42, - 'float': 33.3333, - 'regexp': /regexp/, - 'boolean': true, - 'long': date.getTime(), - 'where': new Code('this.a > i', {i:1}), - 'dbref': new DBRef('namespace', oid, 'integration_tests_') - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); - - for(var i = 0; i < serialized_data2.length; i++) { - require('assert').equal(serialized_data2[i], serialized_data[i]) - } - - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize Complex Nested Object'] = function(test) { - var doc = { email: 'email@email.com', - encrypted_password: 'password', - friends: [ '4db96b973d01205364000006', - '4dc77b24c5ba38be14000002' ], - location: [ 72.4930088, 23.0431957 ], - name: 'Amit Kumar', - password_salt: 'salty', - profile_fields: [], - username: 'amit', - _id: new ObjectID() } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = doc; - doc2._id = ObjectID.createFromHexString(doc2._id.toHexString()); - var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); - - for(var i = 0; i < serialized_data2.length; i++) { - require('assert').equal(serialized_data2[i], serialized_data[i]) - } - - test.done(); -} - -/** - * @ignore - */ -exports['Should correctly massive doc'] = function(test) { - var oid1 = new ObjectID(); - var oid2 = new ObjectID(); - - // JS doc - var doc = { dbref2: new DBRef('namespace', oid1, 'integration_tests_'), - _id: oid2 }; - - var doc2 = { dbref2: new DBRef('namespace', ObjectID.createFromHexString(oid1.toHexString()), 'integration_tests_'), - _id: new ObjectID.createFromHexString(oid2.toHexString()) }; - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize/Deserialize regexp object'] = function(test) { - var doc = {'b':/foobaré/}; - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - for(var i = 0; i < serialized_data2.length; i++) { - require('assert').equal(serialized_data2[i], serialized_data[i]) - } - - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize/Deserialize complicated object'] = function(test) { - var doc = {a:{b:{c:[new ObjectID(), new ObjectID()]}}, d:{f:1332.3323}}; - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc, doc2) - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize/Deserialize nested object'] = function(test) { - var doc = { "_id" : { "date" : new Date(), "gid" : "6f35f74d2bea814e21000000" }, - "value" : { - "b" : { "countries" : { "--" : 386 }, "total" : 1599 }, - "bc" : { "countries" : { "--" : 3 }, "total" : 10 }, - "gp" : { "countries" : { "--" : 2 }, "total" : 13 }, - "mgc" : { "countries" : { "--" : 2 }, "total" : 14 } - } - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc, doc2) - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize/Deserialize nested object with even more nesting'] = function(test) { - var doc = { "_id" : { "date" : {a:1, b:2, c:new Date()}, "gid" : "6f35f74d2bea814e21000000" }, - "value" : { - "b" : { "countries" : { "--" : 386 }, "total" : 1599 }, - "bc" : { "countries" : { "--" : 3 }, "total" : 10 }, - "gp" : { "countries" : { "--" : 2 }, "total" : 13 }, - "mgc" : { "countries" : { "--" : 2 }, "total" : 14 } - } - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc, doc2) - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize empty name object'] = function(test) { - var doc = {'':'test', - 'bbbb':1}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal(doc2[''], 'test'); - test.equal(doc2['bbbb'], 1); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly handle Forced Doubles to ensure we allocate enough space for cap collections'] = function(test) { - if(Double != null) { - var doubleValue = new Double(100); - var doc = {value:doubleValue}; - - // Serialize - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual({value:100}, doc2); - } - - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly deserialize a message'] = function(test) { - var data = "24000000be00de4428000000010000000800000000000000000000000000000000000000"; - var parent = {bson_deserializer:{"Long":Long, "BSON":BSONSE.BSON}} - var binaryData = new Buffer(hexStringToBinary(data)); - - var doc2 = new MongoReply(parent, binaryData); - test.deepEqual([], doc2.documents); - test.done(); -} - -/** - * @ignore - */ -exports['Should deserialize correctly'] = function(test) { - var doc = { - "_id" : new ObjectID("4e886e687ff7ef5e00000162"), - "str" : "foreign", - "type" : 2, - "timestamp" : ISODate("2011-10-02T14:00:08.383Z"), - "links" : [ - "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" - ] - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc, doc2) - test.done(); -} - -/** - * @ignore - */ -exports['Should correctly serialize and deserialize MinKey and MaxKey values'] = function(test) { - var doc = { - _id : new ObjectID("4e886e687ff7ef5e00000162"), - minKey : new MinKey(), - maxKey : new MaxKey() - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc, doc2) - test.ok(doc2.minKey instanceof MinKey); - test.ok(doc2.maxKey instanceof MaxKey); - test.done(); -} - -/** - * @ignore - */ -exports['Should correctly serialize Double value'] = function(test) { - var doc = { - value : new Double(34343.2222) - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.ok(doc.value.valueOf(), doc2.value); - test.ok(doc.value.value, doc2.value); - test.done(); -} - -/** - * @ignore - */ -exports['ObjectID should correctly create objects'] = function(test) { - try { - var object1 = ObjectID.createFromHexString('000000000000000000000001') - var object2 = ObjectID.createFromHexString('00000000000000000000001') - test.ok(false); - } catch(err) { - test.ok(err != null); - } - - test.done(); -} - -/** - * @ignore - */ -exports['ObjectID should correctly retrieve timestamp'] = function(test) { - var testDate = new Date(); - var object1 = new ObjectID(); - test.equal(Math.floor(testDate.getTime()/1000), Math.floor(object1.getTimestamp().getTime()/1000)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly throw error on bsonparser errors'] = function(test) { - var data = new Buffer(3); - var parser = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]); - - // Catch to small buffer error - try { - parser.deserialize(data); - test.ok(false); - } catch(err) {} - - data = new Buffer(5); - data[0] = 0xff; - data[1] = 0xff; - // Catch illegal size - try { - parser.deserialize(data); - test.ok(false); - } catch(err) {} - - // Finish up - test.done(); -} - -/** - * A simple example showing the usage of BSON.calculateObjectSize function returning the number of BSON bytes a javascript object needs. - * - * @_class bson - * @_function BSON.calculateObjectSize - * @ignore - */ -exports['Should correctly calculate the size of a given javascript object'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Calculate the size of the object without serializing the function - var size = BSON.calculateObjectSize(doc, false); - test.equal(12, size); - // Calculate the size of the object serializing the function - size = BSON.calculateObjectSize(doc, true); - // Validate the correctness - test.equal(36, size); - test.done(); -} - -/** - * A simple example showing the usage of BSON.calculateObjectSize function returning the number of BSON bytes a javascript object needs. - * - * @_class bson - * @_function calculateObjectSize - * @ignore - */ -exports['Should correctly calculate the size of a given javascript object using instance method'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Create a BSON parser instance - var bson = new BSON(); - // Calculate the size of the object without serializing the function - var size = bson.calculateObjectSize(doc, false); - test.equal(12, size); - // Calculate the size of the object serializing the function - size = bson.calculateObjectSize(doc, true); - // Validate the correctness - test.equal(36, size); - test.done(); -} - -/** - * A simple example showing the usage of BSON.serializeWithBufferAndIndex function. - * - * @_class bson - * @_function BSON.serializeWithBufferAndIndex - * @ignore - */ -exports['Should correctly serializeWithBufferAndIndex a given javascript object'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Calculate the size of the document, no function serialization - var size = BSON.calculateObjectSize(doc, false); - // Allocate a buffer - var buffer = new Buffer(size); - // Serialize the object to the buffer, checking keys and not serializing functions - var index = BSON.serializeWithBufferAndIndex(doc, true, buffer, 0, false); - // Validate the correctness - test.equal(12, size); - test.equal(11, index); - - // Serialize with functions - // Calculate the size of the document, no function serialization - var size = BSON.calculateObjectSize(doc, true); - // Allocate a buffer - var buffer = new Buffer(size); - // Serialize the object to the buffer, checking keys and not serializing functions - var index = BSON.serializeWithBufferAndIndex(doc, true, buffer, 0, true); - // Validate the correctness - test.equal(36, size); - test.equal(35, index); - test.done(); -} - -/** - * A simple example showing the usage of BSON.serializeWithBufferAndIndex function. - * - * @_class bson - * @_function serializeWithBufferAndIndex - * @ignore - */ -exports['Should correctly serializeWithBufferAndIndex a given javascript object using a BSON instance'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Create a BSON parser instance - var bson = new BSON(); - // Calculate the size of the document, no function serialization - var size = bson.calculateObjectSize(doc, false); - // Allocate a buffer - var buffer = new Buffer(size); - // Serialize the object to the buffer, checking keys and not serializing functions - var index = bson.serializeWithBufferAndIndex(doc, true, buffer, 0, false); - // Validate the correctness - test.equal(12, size); - test.equal(11, index); - - // Serialize with functions - // Calculate the size of the document, no function serialization - var size = bson.calculateObjectSize(doc, true); - // Allocate a buffer - var buffer = new Buffer(size); - // Serialize the object to the buffer, checking keys and not serializing functions - var index = bson.serializeWithBufferAndIndex(doc, true, buffer, 0, true); - // Validate the correctness - test.equal(36, size); - test.equal(35, index); - test.done(); -} - -/** - * A simple example showing the usage of BSON.serialize function returning serialized BSON Buffer object. - * - * @_class bson - * @_function BSON.serialize - * @ignore - */ -exports['Should correctly serialize a given javascript object'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Serialize the object to a buffer, checking keys and not serializing functions - var buffer = BSON.serialize(doc, true, true, false); - // Validate the correctness - test.equal(12, buffer.length); - - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = BSON.serialize(doc, true, true, true); - // Validate the correctness - test.equal(36, buffer.length); - test.done(); -} - -/** - * A simple example showing the usage of BSON.serialize function returning serialized BSON Buffer object. - * - * @_class bson - * @_function serialize - * @ignore - */ -exports['Should correctly serialize a given javascript object using a bson instance'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Create a BSON parser instance - var bson = new BSON(); - // Serialize the object to a buffer, checking keys and not serializing functions - var buffer = bson.serialize(doc, true, true, false); - // Validate the correctness - test.equal(12, buffer.length); - - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = bson.serialize(doc, true, true, true); - // Validate the correctness - test.equal(36, buffer.length); - test.done(); -} - -/** - * A simple example showing the usage of BSON.deserialize function returning a deserialized Javascript function. - * - * @_class bson - * @_function BSON.deserialize - * @ignore - */ - exports['Should correctly deserialize a buffer using the BSON class level parser'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){ console.log('hello world'); }} - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = BSON.serialize(doc, true, true, true); - // Validate the correctness - test.equal(65, buffer.length); - - // Deserialize the object with no eval for the functions - var deserializedDoc = BSON.deserialize(buffer); - // Validate the correctness - test.equal('object', typeof deserializedDoc.func); - test.equal(1, deserializedDoc.a); - - // Deserialize the object with eval for the functions caching the functions - deserializedDoc = BSON.deserialize(buffer, {evalFunctions:true, cacheFunctions:true}); - // Validate the correctness - test.equal('function', typeof deserializedDoc.func); - test.equal(1, deserializedDoc.a); - test.done(); -} - -/** - * A simple example showing the usage of BSON instance deserialize function returning a deserialized Javascript function. - * - * @_class bson - * @_function deserialize - * @ignore - */ -exports['Should correctly deserialize a buffer using the BSON instance parser'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){ console.log('hello world'); }} - // Create a BSON parser instance - var bson = new BSON(); - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = bson.serialize(doc, true, true, true); - // Validate the correctness - test.equal(65, buffer.length); - - // Deserialize the object with no eval for the functions - var deserializedDoc = bson.deserialize(buffer); - // Validate the correctness - test.equal('object', typeof deserializedDoc.func); - test.equal(1, deserializedDoc.a); - - // Deserialize the object with eval for the functions caching the functions - deserializedDoc = bson.deserialize(buffer, {evalFunctions:true, cacheFunctions:true}); - // Validate the correctness - test.equal('function', typeof deserializedDoc.func); - test.equal(1, deserializedDoc.a); - test.done(); -} - -/** - * A simple example showing the usage of BSON.deserializeStream function returning deserialized Javascript objects. - * - * @_class bson - * @_function BSON.deserializeStream - * @ignore - */ -exports['Should correctly deserializeStream a buffer object'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){ console.log('hello world'); }} - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = BSON.serialize(doc, true, true, true); - // Validate the correctness - test.equal(65, buffer.length); - - // The array holding the number of retuned documents - var documents = new Array(1); - // Deserialize the object with no eval for the functions - var index = BSON.deserializeStream(buffer, 0, 1, documents, 0); - // Validate the correctness - test.equal(65, index); - test.equal(1, documents.length); - test.equal(1, documents[0].a); - test.equal('object', typeof documents[0].func); - - // Deserialize the object with eval for the functions caching the functions - // The array holding the number of retuned documents - var documents = new Array(1); - // Deserialize the object with no eval for the functions - var index = BSON.deserializeStream(buffer, 0, 1, documents, 0, {evalFunctions:true, cacheFunctions:true}); - // Validate the correctness - test.equal(65, index); - test.equal(1, documents.length); - test.equal(1, documents[0].a); - test.equal('function', typeof documents[0].func); - test.done(); -} - -/** - * A simple example showing the usage of BSON instance deserializeStream function returning deserialized Javascript objects. - * - * @_class bson - * @_function deserializeStream - * @ignore - */ -exports['Should correctly deserializeStream a buffer object'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){ console.log('hello world'); }} - // Create a BSON parser instance - var bson = new BSON(); - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = bson.serialize(doc, true, true, true); - // Validate the correctness - test.equal(65, buffer.length); - - // The array holding the number of retuned documents - var documents = new Array(1); - // Deserialize the object with no eval for the functions - var index = bson.deserializeStream(buffer, 0, 1, documents, 0); - // Validate the correctness - test.equal(65, index); - test.equal(1, documents.length); - test.equal(1, documents[0].a); - test.equal('object', typeof documents[0].func); - - // Deserialize the object with eval for the functions caching the functions - // The array holding the number of retuned documents - var documents = new Array(1); - // Deserialize the object with no eval for the functions - var index = bson.deserializeStream(buffer, 0, 1, documents, 0, {evalFunctions:true, cacheFunctions:true}); - // Validate the correctness - test.equal(65, index); - test.equal(1, documents.length); - test.equal(1, documents[0].a); - test.equal('function', typeof documents[0].func); - test.done(); -} - -/** - * @ignore - */ -// 'Should Correctly Function' = function(test) { -// var doc = {b:1, func:function() { -// this.b = 2; -// }}; -// -// var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); -// -// debug("----------------------------------------------------------------------") -// debug(inspect(serialized_data)) -// -// // var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); -// // new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); -// // assertBuffersEqual(test, serialized_data, serialized_data2, 0); -// var COUNT = 100000; -// -// // var b = null; -// // eval("b = function(x) { return x+x; }"); -// // var b = new Function("x", "return x+x;"); -// -// console.log(COUNT + "x (objectBSON = BSON.serialize(object))") -// start = new Date -// -// for (i=COUNT; --i>=0; ) { -// var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data, {evalFunctions: true, cacheFunctions:true}); -// } -// -// end = new Date -// console.log("time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// // debug(inspect(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).functionCache)) -// // -// // var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data, {evalFunctions: true, cacheFunctions:true}); -// // // test.deepEqual(doc, doc2) -// // // -// // debug(inspect(doc2)) -// // doc2.func() -// // debug(inspect(doc2)) -// // -// // var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); -// // var doc3 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data, {evalFunctions: true, cacheFunctions:true}); -// // -// // debug("-----------------------------------------------") -// // debug(inspect(doc3)) -// -// // var key = "0" -// // for(var i = 1; i < 10000; i++) { -// // key = key + " " + i -// // } -// -// test.done(); -// -// -// // var car = { -// // model : "Volvo", -// // country : "Sweden", -// // -// // isSwedish : function() { -// // return this.country == "Sweden"; -// // } -// // } -// -// }, - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/bson/commands_test.js b/node_modules/mongodb/test/bson/commands_test.js deleted file mode 100644 index 13a9a06..0000000 --- a/node_modules/mongodb/test/bson/commands_test.js +++ /dev/null @@ -1,129 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - mongoO = require('../../lib/mongodb').pure(), - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - fs = require('fs'), - BSON = mongodb.BSON, - Code = mongoO.Code, - Binary = mongoO.Binary, - Symbol = mongoO.Symbol, - DBRef = mongoO.DBRef, - Double = mongoO.Double, - MinKey = mongoO.MinKey, - MaxKey = mongoO.MaxKey, - Timestamp = mongoO.Timestamp, - Long = mongoO.Long, - ObjectID = mongoO.ObjectID, - DBRef = mongoO.DBRef, - BaseCommand = mongoO.BaseCommand, - InsertCommand = mongoO.InsertCommand, - UpdateCommand = mongoO.UpdateCommand, - DeleteCommand = mongoO.DeleteCommand, - GetMoreCommand = mongoO.GetMoreCommand, - KillCursorCommand = mongoO.KillCursorCommand, - QueryCommand = mongoO.QueryCommand, - MongoReply = mongoO.MongoReply, - BinaryParser = mongoO.BinaryParser; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports['Should Correctly Generate an Insert Command'] = function(test) { - var full_collection_name = "db.users"; - var insert_command = new InsertCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name); - insert_command.add({name: 'peter pan'}); - insert_command.add({name: 'monkey king'}); - // assert the length of the binary - test.equal(81, insert_command.toBinary().length); - test.done(); -} - -exports['Should Correctly Generate an Update Command'] = function(test) { - var full_collection_name = "db.users"; - var flags = UpdateCommand.DB_UPSERT; - var selector = {name: 'peter pan'}; - var document = {name: 'peter pan junior'}; - // Create the command - var update_command = new UpdateCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name, selector, document, flags); - // assert the length of the binary - test.equal(90, update_command.toBinary().length); - test.done(); -} - -exports['Should Correctly Generate a Delete Command'] = function(test) { - var full_collection_name = "db.users"; - var selector = {name: 'peter pan'}; - // Create the command - var delete_command = new DeleteCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name, selector); - // assert the length of the binary - test.equal(58, delete_command.toBinary().length); - test.done(); -} - -exports['Should Correctly Generate a Get More Command'] = function(test) { - var full_collection_name = "db.users"; - var numberToReturn = 100; - var cursorId = Long.fromNumber(10000222); - // Create the command - var get_more_command = new GetMoreCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name, numberToReturn, cursorId); - // assert the length of the binary - test.equal(41, get_more_command.toBinary().length); - test.done(); -} - -exports['Should Correctly Generate a Kill Cursors Command'] = function(test) { - Array.prototype.toXml = function() {} - var cursorIds = [Long.fromNumber(1), Long.fromNumber(10000222)]; - // Create the command - var kill_cursor_command = new KillCursorCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, cursorIds); - // assert the length of the binary - test.equal(40, kill_cursor_command.toBinary().length); - test.done(); -} - -exports['Should Correctly Generate a Query Command'] = function(test) { - var full_collection_name = "db.users"; - var options = QueryCommand.OPTS_SLAVE; - var numberToSkip = 100; - var numberToReturn = 200; - var query = {name:'peter pan'}; - var query_command = new QueryCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name, options, numberToSkip, numberToReturn, query, null); - // assert the length of the binary - test.equal(62, query_command.toBinary().length); - // Generate command with return field filter - query_command = new QueryCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name, options, numberToSkip, numberToReturn, query, { a : 1, b : 1, c : 1}); - test.equal(88, query_command.toBinary().length); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/bson_types_test.js b/node_modules/mongodb/test/bson_types_test.js deleted file mode 100644 index ed21cf3..0000000 --- a/node_modules/mongodb/test/bson_types_test.js +++ /dev/null @@ -1,215 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); - -var testCase = require('../deps/nodeunit').testCase, - Buffer = require('buffer').Buffer, - gleak = require('../dev/tools/gleak'), - fs = require('fs'), - BSON = mongodb.BSON, - Code = mongodb.Code, - Binary = mongodb.Binary, - Timestamp = mongodb.Timestamp, - Long = mongodb.Long, - MongoReply = mongodb.MongoReply, - ObjectID = mongodb.ObjectID, - Symbol = mongodb.Symbol, - DBRef = mongodb.DBRef, - Double = mongodb.Double, - MinKey = mongodb.MinKey, - MaxKey = mongodb.MaxKey, - BinaryParser = mongodb.BinaryParser; - -var BSONSE = mongodb, - BSONDE = mongodb; - -// for tests -BSONDE.BSON_BINARY_SUBTYPE_DEFAULT = 0; -BSONDE.BSON_BINARY_SUBTYPE_FUNCTION = 1; -BSONDE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -BSONDE.BSON_BINARY_SUBTYPE_UUID = 3; -BSONDE.BSON_BINARY_SUBTYPE_MD5 = 4; -BSONDE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -BSONSE.BSON_BINARY_SUBTYPE_DEFAULT = 0; -BSONSE.BSON_BINARY_SUBTYPE_FUNCTION = 1; -BSONSE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -BSONSE.BSON_BINARY_SUBTYPE_UUID = 3; -BSONSE.BSON_BINARY_SUBTYPE_MD5 = 4; -BSONSE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -var hexStringToBinary = function(string) { - var numberofValues = string.length / 2; - var array = ""; - - for(var i = 0; i < numberofValues; i++) { - array += String.fromCharCode(parseInt(string[i*2] + string[i*2 + 1], 16)); - } - return array; -} - -var assertBuffersEqual = function(test, buffer1, buffer2) { - if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2); - - for(var i = 0; i < buffer1.length; i++) { - test.equal(buffer1[i], buffer2[i]); - } -} - -/** - * Module for parsing an ISO 8601 formatted string into a Date object. - */ -var ISODate = function (string) { - var match; - - if (typeof string.getTime === "function") - return string; - else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) { - var date = new Date(); - date.setUTCFullYear(Number(match[1])); - date.setUTCMonth(Number(match[3]) - 1 || 0); - date.setUTCDate(Number(match[5]) || 0); - date.setUTCHours(Number(match[7]) || 0); - date.setUTCMinutes(Number(match[8]) || 0); - date.setUTCSeconds(Number(match[10]) || 0); - date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0); - - if (match[13] && match[13] !== "Z") { - var h = Number(match[16]) || 0, - m = Number(match[17]) || 0; - - h *= 3600000; - m *= 60000; - - var offset = h + m; - if (match[15] == "+") - offset = -offset; - - date = new Date(date.valueOf() + offset); - } - - return date; - } else - throw new Error("Invalid ISO 8601 date given.", __filename); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -/** - * A simple example showing the usage of the binary put method. - * - * @_class binary - * @_function put - * @ignore - */ -exports.shouldCorrectUsePutForBinaryType = function(test) { - // Create an empty Binary object - var binary = new Binary(new Buffer(''), BSON.BSON_BINARY_SUBTYPE_DEFAULT); - // Write some character to the Binary value - binary.put('h'); - binary.put('e'); - binary.put('l'); - binary.put('l'); - binary.put('o'); - // Validate the content of the binary - test.equal('hello', binary.toString('ascii')); - test.done(); -} - -/** - * A simple example showing the usage of the binary write method. - * - * @_class binary - * @_function write - * @ignore - */ -exports.shouldCorrectUseWriteForBinaryType = function(test) { - // Create an empty Binary object - var binary = new Binary(new Buffer(''), BSON.BSON_BINARY_SUBTYPE_DEFAULT); - // Write some data to the binary - binary.write('hello', 0); - // Validate the content of the binary - test.equal('hello', binary.toString('ascii')); - test.done(); -} - -/** - * A simple example showing the usage of the binary read method. - * - * @_class binary - * @_function read - * @ignore - */ -exports.shouldCorrectUseReadForBinaryType = function(test) { - // Create an empty Binary object - var binary = new Binary(new Buffer(''), BSON.BSON_BINARY_SUBTYPE_DEFAULT); - // Write some data to the binary - binary.write('hello', 0); - // Read a couple of characters from the binary - var data = binary.read(1, 2); - // Validate the content of the binary - test.equal('el', data.toString('ascii')); - test.done(); -} - -/** - * A simple example showing the usage of the binary value method. - * - * @_class binary - * @_function value - * @ignore - */ -exports.shouldCorrectUseValueForBinaryType = function(test) { - // Create an empty Binary object - var binary = new Binary(new Buffer(''), BSON.BSON_BINARY_SUBTYPE_DEFAULT); - // Write some data to the binary - binary.write('hello', 0); - // Validate the content of the binary - test.equal('hello', binary.value()); - test.done(); -} - -/** - * A simple example showing the usage of the binary length method. - * - * @_class binary - * @_function length - * @ignore - */ -exports.shouldCorrectUseLengthForBinaryType = function(test) { - // Create an empty Binary object - var binary = new Binary(new Buffer(''), BSON.BSON_BINARY_SUBTYPE_DEFAULT); - // Write some data to the binary - binary.write('hello'); - // Validate the content of the binary - test.equal(5, binary.length()); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/certificates/mycert.pem b/node_modules/mongodb/test/certificates/mycert.pem deleted file mode 100644 index 954627c..0000000 --- a/node_modules/mongodb/test/certificates/mycert.pem +++ /dev/null @@ -1,36 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: DES-EDE3-CBC,5BC1D8935109F6C8 - -cbr7PTUV8ySzjBsvtCLng+0m7aez0D/Q76JnsW265oLxwqqID9mgS3rIZUgbu2SQ -+rfTTG+xcrONJs41Pbao1D1BNcUrmLF+8pl6055xFOPWrE1cxHQRShlhgG/pLVE3 -JqLFLV4Pd8Tf+o3FwbZ3zqgqwMPVZN/TLfzw94qcrXiidNvWuWf3oyU4w+CzD4Vt -f9HYNOeZWCUtaGGM5koUU/qu/RYQdKXZTRPz9wCHTjSsrznE4BpAJgtBbaOpr850 -c3WP48aveK9NZ9aoR1c+BW6MN+HPN2HhwA9rQUBSwfwlVVxxY1Ir2ArbP7fStlvK -TRtuE7Ro0ZEOUiHB5c9X7p6clKgshP7K19ZG6O0ns1P9d9z7l35f1WG/XQxA66tg -h8haN8nOtPJfrAyn5NcmOS2kTA0kL6Lk2TWwqoVErvpCRgdyhQ94GxjMiHLvkfxx -z5fVQqoXuYV8O6ozfdx+58qJnRTLC1cHf8iwWc9sDE/IP9OTpxwMUBKX4EYOL8MQ -4pjv0qnD/PQN4B5CbQ0RViBLykl22SScxqS3Zq14/sItEjM44ctjgAfmoPZSElTz -n9zhc8VQzgyjuNRt02xAi+tx2RD5I44ylm7QTYnXdWVgftnSgY+Ir4npTK5bnxIB -b9CLPljXbj8k5utoTyFkZa+bRES3a3+MEq5dNFRb0neQ3nJXqB83hMEDE35XWbU0 -gJwG7KsVS6Vr3SfBi47fsoIH1Ii92hZxWrtbTlzjy884zSps+mTWGA6TuU8jb6jn -b2JyNJDhVqDk19DPP+TtMv+GgXuoj7EXenQbwRXO/NVyaWpyBU7dHA== ------END RSA PRIVATE KEY----- ------BEGIN CERTIFICATE----- -MIIC4TCCAkqgAwIBAgIJAM0r5teNISyyMA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV -BAYTAkVTMRIwEAYDVQQIEwlCYXJjZWxvbmExEjAQBgNVBAcTCUJhcmNlbG9uYTEO -MAwGA1UEChMFMTBnZW4xDjAMBgNVBAMTBTEwZ2VuMB4XDTExMTIwMjEwMTcwM1oX -DTEyMTIwMTEwMTcwM1owVTELMAkGA1UEBhMCRVMxEjAQBgNVBAgTCUJhcmNlbG9u -YTESMBAGA1UEBxMJQmFyY2Vsb25hMQ4wDAYDVQQKEwUxMGdlbjEOMAwGA1UEAxMF -MTBnZW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPBY5u20gJQAXw/m3hiY -kC1zqDt4lahjUauPUDeshceAuBIgQLePZwckR3caPqS1a1uPsKMQIKN1E/z781MY -iAdgRPwpQfKt1MRZRZdUVzOsGQdDtF1XEnIbQgdiahbXVqVeULLLuypWnw1ceAys -ESu8kWqPAm1eu+utqJOENXWpAgMBAAGjgbgwgbUwHQYDVR0OBBYEFN1iayQf9puR -3OZxEy/FtFv6YSRoMIGFBgNVHSMEfjB8gBTdYmskH/abkdzmcRMvxbRb+mEkaKFZ -pFcwVTELMAkGA1UEBhMCRVMxEjAQBgNVBAgTCUJhcmNlbG9uYTESMBAGA1UEBxMJ -QmFyY2Vsb25hMQ4wDAYDVQQKEwUxMGdlbjEOMAwGA1UEAxMFMTBnZW6CCQDNK+bX -jSEssjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAOvATDKZ95epzVjV -qGnaHgu4u6NJuvZlGmBl2Mq/EA2ymw2LL+Pt38BqyQWvO/5TlxF1EFhH3kl6RENw -9U7C+w8tqhQL3hQsTASdX9gTczaYgHwHsKLc2JFcC7J2ffXM0aW5wUCKUwvvtf/h -7rUWJPi+evtVGTxRhCQGJcoI9lEK ------END CERTIFICATE----- diff --git a/node_modules/mongodb/test/collection_test.js b/node_modules/mongodb/test/collection_test.js deleted file mode 100644 index e5c15ca..0000000 --- a/node_modules/mongodb/test/collection_test.js +++ /dev/null @@ -1,1189 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Long = require('../lib/mongodb/bson/long').Long, - Step = require("../deps/step/lib/step"), - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * Example of a simple document save with safe set to false - * - * @_class collection - * @_function save - * @ignore - */ -exports.shouldCorrectlySaveASimpleDocument = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch the collection - db.collection("save_a_simple_document", function(err, collection) { - - // Save a document with no safe option - collection.save({hello:'world'}); - - // Wait for a second - setTimeout(function() { - - // Find the saved document - collection.findOne({hello:'world'}, function(err, item) { - test.equal(null, err); - test.equal('world', item.hello); - db.close(); - test.done(); - }); - }, 1000); - }); - }); -} - -/** - * Example of a simple document save and then resave with safe set to true - * - * @_class collection - * @_function save - * @ignore - */ -exports.shouldCorrectlySaveASimpleDocumentModifyItAndResaveIt = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch the collection - db.collection("save_a_simple_document_modify_it_and_resave_it", function(err, collection) { - - // Save a document with no safe option - collection.save({hello:'world'}, {safe:true}, function(err, result) { - - // Find the saved document - collection.findOne({hello:'world'}, function(err, item) { - test.equal(null, err); - test.equal('world', item.hello); - - // Update the document - item['hello2'] = 'world2'; - - // Save the item with the additional field - collection.save(item, {safe:true}, function(err, result) { - - // Find the changed document - collection.findOne({hello:'world'}, function(err, item) { - test.equal(null, err); - test.equal('world', item.hello); - test.equal('world2', item.hello2); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectExecuteBasicCollectionMethods = function(test) { - client.createCollection('test_collection_methods', function(err, collection) { - // Verify that all the result are correct coming back (should contain the value ok) - test.equal('test_collection_methods', collection.collectionName); - // Let's check that the collection was created correctly - client.collectionNames(function(err, documents) { - var found = false; - documents.forEach(function(document) { - if(document.name == "integration_tests_.test_collection_methods") found = true; - }); - test.ok(true, found); - // Rename the collection and check that it's gone - client.renameCollection("test_collection_methods", "test_collection_methods2", function(err, reply) { - test.equal(null, err); - // Drop the collection and check that it's gone - client.dropCollection("test_collection_methods2", function(err, result) { - test.equal(true, result); - test.done(); - }) - }); - }); - }) -} - -/** - * @ignore - */ -exports.shouldAccessToCollections = function(test) { - // Create two collections - client.createCollection('test.spiderman', function(r) { - client.createCollection('test.mario', function(r) { - // Insert test documents (creates collections) - client.collection('test.spiderman', function(err, spiderman_collection) { - spiderman_collection.insert({foo:5}, {safe:true}, function(err, r) { - - client.collection('test.mario', function(err, mario_collection) { - mario_collection.insert({bar:0}, {safe:true}, function(err, r) { - // Assert collections - client.collections(function(err, collections) { - var found_spiderman = false; - var found_mario = false; - var found_does_not_exist = false; - - collections.forEach(function(collection) { - if(collection.collectionName == "test.spiderman") found_spiderman = true; - if(collection.collectionName == "test.mario") found_mario = true; - if(collection.collectionName == "does_not_exist") found_does_not_exist = true; - }); - - test.ok(found_spiderman); - test.ok(found_mario); - test.ok(!found_does_not_exist); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyDropCollection = function(test) { - client.createCollection('test_drop_collection2', function(err, r) { - client.dropCollection('test_drop_collection', function(err, r) { - test.ok(err instanceof Error); - test.equal("ns not found", err.message); - var found = false; - // Ensure we don't have the collection in the set of names - client.collectionNames(function(err, replies) { - replies.forEach(function(err, document) { - if(document.name == "test_drop_collection") { - found = true; - return; - } - }); - // If we have an instance of the index throw and error - if(found) throw new Error("should not fail"); - // Let's close the db - test.done(); - }); - }); - }); -} - -/** - * Example of a simple document save and then resave with safe set to true - * - * @_class collection - * @_function drop - * @ignore - */ -exports.shouldCorrectlyDropCollectionWithDropFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('test_other_drop', function(err, collection) { - test.equal(null, err); - - // Drop the collection - collection.drop(function(err, reply) { - - // Ensure we don't have the collection in the set of names - db.collectionNames(function(err, replies) { - - var found = false; - // For each collection in the list of collection names in this db look for the - // dropped collection - replies.forEach(function(document) { - if(document.name == "test_other_drop") { - found = true; - return; - } - }); - - // Ensure the collection is not found - test.equal(false, found); - - // Let's close the db - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyRetriveCollectionNames = function(test) { - client.createCollection('test_collection_names', function(err, r) { - client.collectionNames(function(err, documents) { - var found = false; - var found2 = false; - documents.forEach(function(document) { - if(document.name == MONGODB + '.test_collection_names') found = true; - }); - test.ok(found); - // Insert a document in an non-existing collection should create the collection - client.collection('test_collection_names2', function(err, collection) { - collection.insert({a:1}, {safe:true}, function(err, r) { - client.collectionNames(function(err, documents) { - documents.forEach(function(document) { - if(document.name == MONGODB + '.test_collection_names2') found = true; - if(document.name == MONGODB + '.test_collection_names') found2 = true; - }); - - test.ok(found); - test.ok(found2); - // Let's close the db - test.done(); - }); - }) - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyRetrieveCollectionInfo = function(test) { - client.createCollection('test_collections_info', function(err, r) { - client.collectionsInfo(function(err, cursor) { - test.ok((cursor instanceof Cursor)); - // Fetch all the collection info - cursor.toArray(function(err, documents) { - test.ok(documents.length > 1); - - var found = false; - documents.forEach(function(document) { - if(document.name == MONGODB + '.test_collections_info') found = true; - }); - test.ok(found); - // Let's close the db - test.done(); - }); - }); - }); -} - -/** - * An example returning the options for a collection. - * - * @_class collection - * @_function options - */ -exports.shouldCorrectlyRetriveCollectionOptions = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection that we are getting the options back from - db.createCollection('test_collection_options', {'capped':true, 'size':1024}, function(err, collection) { - test.ok(collection instanceof Collection); - test.equal('test_collection_options', collection.collectionName); - - // Let's fetch the collection options - collection.options(function(err, options) { - test.equal(true, options.capped); - test.equal(1024, options.size); - test.equal("test_collection_options", options.create); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * An example showing how to establish if it's a capped collection - * - * @_class collection - * @_function isCapped - */ -exports.shouldCorrectlyExecuteIsCapped = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection that we are getting the options back from - db.createCollection('test_collection_is_capped', {'capped':true, 'size':1024}, function(err, collection) { - test.ok(collection instanceof Collection); - test.equal('test_collection_is_capped', collection.collectionName); - - // Let's fetch the collection options - collection.isCapped(function(err, capped) { - test.equal(true, capped); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * An example showing the use of the indexExists function for a single index name and a list of index names. - * - * @_class collection - * @_function indexExists - */ -exports.shouldCorrectlyExecuteIndexExists = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection that we are getting the options back from - db.createCollection('test_collection_index_exists', function(err, collection) { - test.equal(null, err); - - // Create an index on the collection - collection.createIndex('a', function(err, indexName) { - - // Let's test to check if a single index exists - collection.indexExists("a_1", function(err, result) { - test.equal(true, result); - - // Let's test to check if multiple indexes are available - collection.indexExists(["a_1", "_id_"], function(err, result) { - test.equal(true, result); - - // Check if a non existing index exists - collection.indexExists("c_1", function(err, result) { - test.equal(false, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldEnsureStrictAccessCollection = function(test) { - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - test.equal(true, error_client.strict); - - error_client.open(function(err, error_client) { - error_client.collection('does-not-exist', function(err, collection) { - test.ok(err instanceof Error); - test.equal("Collection does-not-exist does not exist. Currently in strict mode.", err.message); - }); - - error_client.createCollection('test_strict_access_collection', function(err, collection) { - error_client.collection('test_strict_access_collection', function(err, collection) { - test.ok(collection instanceof Collection); - // Let's close the db - error_client.close(); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldPerformStrictCreateCollection = function(test) { - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - test.equal(true, error_client.strict); - - error_client.open(function(err, error_client) { - error_client.createCollection('test_strict_create_collection', function(err, collection) { - test.ok(collection instanceof Collection); - - // Creating an existing collection should fail - error_client.createCollection('test_strict_create_collection', function(err, collection) { - test.ok(err instanceof Error); - test.equal("Collection test_strict_create_collection already exists. Currently in strict mode.", err.message); - - // Switch out of strict mode and try to re-create collection - error_client.strict = false; - error_client.createCollection('test_strict_create_collection', function(err, collection) { - test.ok(collection instanceof Collection); - - // Let's close the db - error_client.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldFailToInsertDueToIllegalKeys = function(test) { - client.createCollection('test_invalid_key_names', function(err, collection) { - // Legal inserts - collection.insert([{'hello':'world'}, {'hello':{'hello':'world'}}], {safe:true}, function(err, r) { - // Illegal insert for key - collection.insert({'$hello':'world'}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key $hello must not start with '$'", err.message); - - collection.insert({'hello':{'$hello':'world'}}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key $hello must not start with '$'", err.message); - - collection.insert({'he$llo':'world'}, {safe:true}, function(err, docs) { - test.ok(docs[0].constructor == Object); - - collection.insert({'hello':{'hell$o':'world'}}, {safe:true}, function(err, docs) { - test.ok(err == null); - - collection.insert({'.hello':'world'}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key .hello must not contain '.'", err.message); - - collection.insert({'hello':{'.hello':'world'}}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key .hello must not contain '.'", err.message); - - collection.insert({'hello.':'world'}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key hello. must not contain '.'", err.message); - - collection.insert({'hello':{'hello.':'world'}}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key hello. must not contain '.'", err.message); - // Let's close the db - test.done(); - }); - }); - }); - }); - }) - }) - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldFailDueToIllegalCollectionNames = function(test) { - client.collection(5, function(err, collection) { - test.equal("collection name must be a String", err.message); - }); - - client.collection("", function(err, collection) { - test.equal("collection names cannot be empty", err.message); - }); - - client.collection("te$t", function(err, collection) { - test.equal("collection names must not contain '$'", err.message); - }); - - client.collection(".test", function(err, collection) { - test.equal("collection names must not start or end with '.'", err.message); - }); - - client.collection("test.", function(err, collection) { - test.equal("collection names must not start or end with '.'", err.message); - }); - - client.collection("test..t", function(err, collection) { - test.equal("collection names cannot be empty", err.message); - test.done(); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCountOnNonExistingCollection = function(test) { - client.collection('test_multiple_insert_2', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - // Let's close the db - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteSave = function(test) { - client.createCollection('test_save', function(err, collection) { - var doc = {'hello':'world'}; - collection.save(doc, {safe:true}, function(err, docs) { - test.ok(docs._id instanceof ObjectID || Object.prototype.toString.call(docs._id) === '[object ObjectID]'); - - collection.count(function(err, count) { - test.equal(1, count); - doc = docs; - - collection.save(doc, {safe:true}, function(err, doc2) { - - collection.count(function(err, count) { - test.equal(1, count); - - collection.findOne(function(err, doc3) { - test.equal('world', doc3.hello); - - doc3.hello = 'mike'; - - collection.save(doc3, {safe:true}, function(err, doc4) { - collection.count(function(err, count) { - test.equal(1, count); - - collection.findOne(function(err, doc5) { - test.equal('mike', doc5.hello); - - // Save another document - collection.save({hello:'world'}, {safe:true}, function(err, doc) { - collection.count(function(err, count) { - test.equal(2, count); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveDocumentWithLongValue = function(test) { - client.createCollection('test_save_long', function(err, collection) { - collection.insert({'x':Long.fromNumber(9223372036854775807)}, {safe:true}, function(err, r) { - collection.findOne(function(err, doc) { - test.ok(Long.fromNumber(9223372036854775807).equals(doc.x)); - // Let's close the db - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldSaveObjectThatHasIdButDoesNotExistInCollection = function(test) { - client.createCollection('test_save_with_object_that_has_id_but_does_not_actually_exist_in_collection', function(err, collection) { - var a = {'_id':'1', 'hello':'world'}; - collection.save(a, {safe:true}, function(err, docs) { - collection.count(function(err, count) { - test.equal(1, count); - - collection.findOne(function(err, doc) { - test.equal('world', doc.hello); - - doc.hello = 'mike'; - collection.save(doc, {safe:true}, function(err, doc) { - collection.count(function(err, count) { - test.equal(1, count); - }); - - collection.findOne(function(err, doc) { - test.equal('mike', doc.hello); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformUpsert = function(test) { - client.createCollection('test_should_correctly_do_upsert', function(err, collection) { - var id = new ObjectID(null) - var doc = {_id:id, a:1}; - - Step( - function test1() { - var self = this; - - collection.update({"_id":id}, doc, {upsert:true, safe:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - collection.findOne({"_id":id}, self); - }); - }, - - function test2(err, doc) { - var self = this; - test.equal(1, doc.a); - - id = new ObjectID(null) - doc = {_id:id, a:2}; - - collection.update({"_id":id}, doc, {safe:true, upsert:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - collection.findOne({"_id":id}, self); - }); - }, - - function test3(err, doc2) { - var self = this; - test.equal(2, doc2.a); - - collection.update({"_id":id}, doc2, {safe:true, upsert:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - collection.findOne({"_id":id}, function(err, doc) { - test.equal(2, doc.a); - test.done(); - }); - }); - } - ); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyUpdateWithNoDocs = function(test) { - client.createCollection('test_should_correctly_do_update_with_no_docs', function(err, collection) { - var id = new ObjectID(null) - var doc = {_id:id, a:1}; - collection.update({"_id":id}, doc, {safe:true}, function(err, numberofupdateddocs) { - test.equal(null, err); - test.equal(0, numberofupdateddocs); - - test.done(); - }); - }); -} - -/** - * Example of a simple document update with safe set to false on an existing document - * - * @_class collection - * @_function update - */ -exports.shouldCorrectlyUpdateASimpleDocument = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Get a collection - db.collection('update_a_simple_document', function(err, collection) { - - // Insert a document, then update it - collection.insert({a:1}, {safe:true}, function(err, doc) { - - // Update the document with an atomic operator - collection.update({a:1}, {$set:{b:2}}); - - // Wait for a second then fetch the document - setTimeout(function() { - - // Fetch the document that we modified - collection.findOne({a:1}, function(err, item) { - test.equal(null, err); - test.equal(1, item.a); - test.equal(2, item.b); - db.close(); - test.done(); - }); - }, 1000); - }) - }); - }); -} - -/** - * Example of a simple document update using upsert (the document will be inserted if it does not exist) - * - * @_class collection - * @_function update - * @ignore - */ -exports.shouldCorrectlyUpsertASimpleDocument = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Get a collection - db.collection('update_a_simple_document_upsert', function(err, collection) { - - // Update the document using an upsert operation, ensuring creation if it does not exist - collection.update({a:1}, {b:2, a:1}, {upsert:true, safe:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - // Fetch the document that we modified and check if it got inserted correctly - collection.findOne({a:1}, function(err, item) { - test.equal(null, err); - test.equal(1, item.a); - test.equal(2, item.b); - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * Example of an update across multiple documents using the multi option. - * - * @_class collection - * @_function update - * @ignore - */ -exports.shouldCorrectlyUpdateMultipleDocuments = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Get a collection - db.collection('update_a_simple_document_multi', function(err, collection) { - - // Insert a couple of documentations - collection.insert([{a:1, b:1}, {a:1, b:2}], {safe:true}, function(err, result) { - - // Update multiple documents using the multi option - collection.update({a:1}, {$set:{b:0}}, {safe:true, multi:true}, function(err, numberUpdated) { - test.equal(null, err); - test.equal(2, numberUpdated); - - // Fetch all the documents and verify that we have changed the b value - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(1, items[0].a); - test.equal(0, items[0].b); - test.equal(1, items[1].a); - test.equal(0, items[1].b); - - db.close(); - test.done(); - }); - }) - }); - }); - }); -} - -/** - * Example of running the distinct command against a collection - * - * @_class collection - * @_function distinct - * @ignore - */ -exports.shouldCorrectlyHandleDistinctIndexes = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Crete the collection for the distinct example - db.createCollection('simple_key_based_distinct', function(err, collection) { - - // Insert documents to perform distinct against - collection.insert([{a:0, b:{c:'a'}}, {a:1, b:{c:'b'}}, {a:1, b:{c:'c'}}, - {a:2, b:{c:'a'}}, {a:3}, {a:3}], {safe:true}, function(err, ids) { - - // Peform a distinct query against the a field - collection.distinct('a', function(err, docs) { - test.deepEqual([0, 1, 2, 3], docs.sort()); - - // Perform a distinct query against the sub-field b.c - collection.distinct('b.c', function(err, docs) { - test.deepEqual(['a', 'b', 'c'], docs.sort()); - - db.close(); - test.done(); - }); - }); - }) - }); - }); -} - -/** - * Example of running the distinct command against a collection with a filter query - * - * @_class collection - * @_function distinct - * @ignore - */ -exports.shouldCorrectlyHandleDistinctIndexesWithSubQueryFilter = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Crete the collection for the distinct example - db.createCollection('simple_key_based_distinct_sub_query_filter', function(err, collection) { - - // Insert documents to perform distinct against - collection.insert([{a:0, b:{c:'a'}}, {a:1, b:{c:'b'}}, {a:1, b:{c:'c'}}, - {a:2, b:{c:'a'}}, {a:3}, {a:3}, {a:5, c:1}], {safe:true}, function(err, ids) { - - // Peform a distinct query with a filter against the documents - collection.distinct('a', {c:1}, function(err, docs) { - test.deepEqual([5], docs.sort()); - - db.close(); - test.done(); - }); - }) - }); - }); -} - -/** - * Example of running simple count commands against a collection. - * - * @_class collection - * @_function count - * @ignore - */ -exports.shouldCorrectlyDoSimpleCountExamples = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Crete the collection for the distinct example - db.createCollection('simple_count_example', function(err, collection) { - - // Insert documents to perform distinct against - collection.insert([{a:1}, {a:2}, {a:3}, {a:4, b:1}], {safe:true}, function(err, ids) { - - // Perform a total count command - collection.count(function(err, count) { - test.equal(null, err); - test.equal(4, count); - - // Peform a partial account where b=1 - collection.count({b:1}, function(err, count) { - test.equal(null, err); - test.equal(1, count); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteInsertUpdateDeleteSafeMode = function(test) { - client.createCollection('test_should_execute_insert_update_delete_safe_mode', function(err, collection) { - test.ok(collection instanceof Collection); - test.equal('test_should_execute_insert_update_delete_safe_mode', collection.collectionName); - - collection.insert({i:1}, {safe:true}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]._id.toHexString().length == 24); - - // Update the record - collection.update({i:1}, {"$set":{i:2}}, {safe:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - // Remove safely - collection.remove({}, {safe:true}, function(err, result) { - test.equal(null, err); - - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldPerformMultipleSaves = function(test) { - client.createCollection("multiple_save_test", function(err, collection) { - var doc = { - name: 'amit', - text: 'some text' - }; - - //insert new user - collection.save(doc, {safe:true}, function(err, r) { - collection.find({}, {name: 1}).limit(1).toArray(function(err, users){ - var user = users[0] - - if(err) { - throw new Error(err) - } else if(user) { - user.pants = 'worn' - - collection.save(user, {safe:true}, function(err, result){ - test.equal(null, err); - test.equal(1, result); - - test.done(); - }) - } - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveDocumentWithNestedArray = function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, db) { - db.createCollection("save_error_on_save_test", function(err, collection) { - // Create unique index for username - collection.createIndex([['username', 1]], true, function(err, result) { - var doc = { - email: 'email@email.com', - encrypted_password: 'password', - friends: - [ '4db96b973d01205364000006', - '4db94a1948a683a176000001', - '4dc77b24c5ba38be14000002' ], - location: [ 72.4930088, 23.0431957 ], - name: 'Amit Kumar', - password_salt: 'salty', - profile_fields: [], - username: 'amit' }; - //insert new user - collection.save(doc, {safe:true}, function(err, doc) { - - collection.find({}).limit(1).toArray(function(err, users) { - test.equal(null, err); - var user = users[0] - user.friends.splice(1,1) - - collection.save(user, function(err, doc) { - test.equal(null, err); - - // Update again - collection.update({_id:new ObjectID(user._id.toString())}, {friends:user.friends}, {upsert:true, safe:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldPeformCollectionRemoveWithNoCallback = function(test) { - client.collection("remove_with_no_callback_bug_test", function(err, collection) { - collection.save({a:1}, {safe:true}, function(){ - collection.save({b:1}, {safe:true}, function(){ - collection.save({c:1}, {safe:true}, function(){ - collection.remove({a:1}, {safe:true}, function() { - // Let's perform a count - collection.count(function(err, count) { - test.equal(null, err); - test.equal(2, count); - test.done(); - }); - }) - }); - }); - }); - }); -}, - -/** - * Example of retrieving a collections indexes - * - * @_class collection - * @_function indexes - * @ignore - */ -exports.shouldCorrectlyRetriveACollectionsIndexes = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Crete the collection for the distinct example - db.createCollection('simple_key_based_distinct', function(err, collection) { - - // Create a geo 2d index - collection.ensureIndex({loc:"2d"}, function(err, result) { - test.equal(null, err); - - // Create a simple single field index - collection.ensureIndex({a:1}, function(err, result) { - test.equal(null, err); - - // List all of the indexes on the collection - collection.indexes(function(err, indexes) { - test.equal(3, indexes.length); - - db.close(); - test.done(); - }); - }) - }) - }); - }); -} - -/** - * Example of retrieving a collections stats - * - * @_class collection - * @_function stats - * @ignore - */ -exports.shouldCorrectlyReturnACollectionsStats = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Crete the collection for the distinct example - db.createCollection('collection_stats_test', function(err, collection) { - - // Insert some documents - collection.insert([{a:1}, {hello:'world'}], {safe:true}, function(err, result) { - - // Retrieve the statistics for the collection - collection.stats(function(err, stats) { - test.equal(2, stats.count); - - db.close(); - test.done(); - }); - }); - }); - }); -} - - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/connect_test.js b/node_modules/mongodb/test/connect_test.js deleted file mode 100644 index 9fd8252..0000000 --- a/node_modules/mongodb/test/connect_test.js +++ /dev/null @@ -1,148 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - connect = mongodb.connect, - gleak = require('../dev/tools/gleak'), - Script = require('vm'), - Collection = mongodb.Collection, - Server = mongodb.Server, - Step = require("../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var clientUrl = 'mongo://localhost:27017/' + MONGODB + (useSSL == true ? '?ssl=true' : ''); - -/** - * @ignore - */ -function connectionTester(test, testName) { - return function(err, db) { - test.equal(err, null); - db.collection(testName, function(err, collection) { - test.equal(err, null); - var doc = {foo:123}; - collection.insert({foo:123}, {safe:true}, function(err, docs) { - test.equal(err, null); - db.dropDatabase(function(err, done) { - db.close(); - test.equal(err, null); - test.ok(done); - test.done(); - }); - }); - }); - }; -}; - -/** - * @ignore - */ -exports.testConnectNoOptions = function(test) { - connect(clientUrl, connectionTester(test, 'testConnectNoOptions')); -}; - -/** - * @ignore - */ -exports.testConnectDbOptions = function(test) { - connect(clientUrl, - { db: {native_parser: (process.env['TEST_NATIVE'] != null)} }, - connectionTester(test, 'testConnectDbOptions')); -}; - -/** - * @ignore - */ -exports.testConnectServerOptions = function(test) { - connect(clientUrl, - { server: {auto_reconnect: true, poolSize: 4} }, - connectionTester(test, 'testConnectServerOptions')); -}; - -/** - * @ignore - */ -exports.testConnectAllOptions = function(test) { - connect(clientUrl, - { server: {auto_reconnect: true, poolSize: 4}, - db: {native_parser: (process.env['TEST_NATIVE'] != null)} }, - connectionTester(test, 'testConnectAllOptions')); -}; - -/** - * @ignore - */ -exports.testConnectGoodAuth = function(test) { - var user = 'testConnectGoodAuth', password = 'password'; - // First add a user. - connect(clientUrl, function(err, db) { - test.equal(err, null); - db.addUser(user, password, function(err, result) { - test.equal(err, null); - db.close(); - restOfTest(); - }); - }); - - function restOfTest() { - var url = 'mongo://' + user + ':' + password + '@localhost:27017/' + MONGODB + (useSSL == true ? '?ssl=true' : ''); - connect(url, connectionTester(test, 'testConnectGoodAuth')); - } -}; - -/** - * @ignore - */ -exports.testConnectBadAuth = function(test) { - var url = 'mongo://slithy:toves@localhost:27017/' + MONGODB + (useSSL == true ? '?ssl=true' : ''); - connect(url, function(err, db) { - test.ok(err); - test.ok(db); - db.close(); - test.done(); - }); -}; - -/** - * @ignore - */ -exports.testConnectBadUrl = function(test) { - test.throws(function() { - connect('mango://localhost:27017/' + MONGODB, function(err, db) { - test.ok(false, 'Bad URL!'); - }); - }); - test.done(); -}; - -/** - * Example of a simple url connection string. - * - * @_class db - * @_function Db.connect - * @ignore - */ -exports.shouldCorrectlyDoSimpleCountExamples = function(test) { - // Connect to the server - Db.connect('mongodb://localhost:27017/integration_tests' + (useSSL == true ? '?ssl=true' : ''), function(err, db) { - test.equal(null, err); - - db.close(); - test.done(); - }); -} - - -/** - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} diff --git a/node_modules/mongodb/test/connection/connection_pool_test.js b/node_modules/mongodb/test/connection/connection_pool_test.js deleted file mode 100644 index fe34beb..0000000 --- a/node_modules/mongodb/test/connection/connection_pool_test.js +++ /dev/null @@ -1,102 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - Buffer = require('buffer').Buffer, - gleak = require('../../dev/tools/gleak'), - fs = require('fs'), - ConnectionPool = require('../../lib/mongodb/connection/connection_pool').ConnectionPool; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports['Should Correctly create a pool instance with the expected values'] = function(test) { - var connectionPool = new ConnectionPool('localhost', 2000, 1, null, {timeout:100, noDelay:true}); - test.equal(100, connectionPool.socketOptions.timeout); - test.equal(true, connectionPool.socketOptions.noDelay); - test.equal(null, connectionPool.socketOptions.encoding); - test.equal(0, connectionPool.socketOptions.bufferSize); - test.done(); -} - -exports['Should correctly fail due to no server'] = function(test) { - var connectionPool = new ConnectionPool('localhost', 2000, 4, null, {timeout:100, noDelay:true}); - - // // Add event handler that will fire once the pool is ready - connectionPool.on("poolReady", function(err, result) { - }) - - // Add event handler that will fire when it fails - connectionPool.on("error", function(err, connection) { - test.equal(0, connectionPool.connections.length) - test.equal(0, connectionPool.openConnections.length) - test.done(); - }); - - // Start the pool - connectionPool.start(); -} - -exports['Should Correctly create a pool of connections and receive an ok when all connections are active'] = function(test) { - var connectionPool = new ConnectionPool('localhost', 27017, 4, {timeout:100, noDelay:true}); - - // Add event handler that will fire once the pool is ready - connectionPool.on("poolReady", function() { - connectionPool.stop(); - test.done(); - }) - - // Start the pool - connectionPool.start(); -} - -exports['Should Correctly connect and then force a restart creating new connections'] = function(test) { - var connectionPool = new ConnectionPool('localhost', 27017, 4, {timeout:100, noDelay:true}); - var done = false; - - // Add event handler that will fire once the pool is ready - connectionPool.on("poolReady", function() { - // Restart - if(done) { - connectionPool.stop(); - test.done(); - } else { - // Trigger stop - connectionPool.restart(); - done = true; - } - }) - - // Start the pool - connectionPool.start(); -}, - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/connection/message_parser_test.js b/node_modules/mongodb/test/connection/message_parser_test.js deleted file mode 100644 index 06702d3..0000000 --- a/node_modules/mongodb/test/connection/message_parser_test.js +++ /dev/null @@ -1,436 +0,0 @@ -// var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - Buffer = require('buffer').Buffer, - gleak = require('../../dev/tools/gleak'), - Connection = require('../../lib/mongodb/connection/connection').Connection; - -var assertBuffersEqual = function(test, buffer1, buffer2) { - if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2); - - for(var i = 0; i < buffer1.length; i++) { - test.equal(buffer1[i], buffer2[i]); - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports['Should correctly parse perfectly aligned message from socket'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(10); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer, data); - test.done(); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer); -}, - -exports['Should correctly parse perfectly aligned double message from socket'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(20); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - buffer[index+4] = 0xa; - - // var result index - var resultIndex = 0; - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(resultIndex, resultIndex + 10), data); - resultIndex = resultIndex + 10; - - if(resultIndex === buffer.length) { - test.done(); - } - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - // Execute parsing of message - dataHandler(buffer); -} - -exports['Should correctly parse message + in two packets from socket'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(10); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer, data); - test.done(); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6)); -}, - -exports['Should correctly parse message + in two packets from socket and partial third one'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(20); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - buffer[index + 4] = 0xff; - buffer[index + 5] = 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(0, 10), data); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 15)); - - // Check status of the parser - test.equal(5, self.bytesRead); - test.equal(10, self.sizeOfMessage); - assertBuffersEqual(test, buffer.slice(10, 15), self.buffer.slice(0, 5)); - test.equal(null, self.stubBuffer); - // Finish test - test.done(); -} - -exports['Should correctly parse message + in two packets from socket and smaller than 4 bytes additional one'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(20); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(0, 10), data); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 13)); - - // Check status of the parser - test.equal(0, self.bytesRead); - test.equal(0, self.sizeOfMessage); - test.equal(null, self.buffer); - assertBuffersEqual(test, buffer.slice(10, 13), self.stubBuffer); - test.done(); -} - -exports['Should correctly parse message + in two packets from socket and smaller than 4 bytes additional one then rest of the message'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(20); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - buffer[index + 4] = 0xff; - buffer[index + 5] = 0xff; - buffer[index + 6] = 0xff; - buffer[index + 7] = 0xff; - buffer[index + 8] = 0xfd; - buffer[index + 9] = 0xfe; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(0, 10), data); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 13)); - dataHandler(buffer.slice(13, 19)); - - // Check status of the parser - test.equal(9, self.bytesRead); - test.equal(10, self.sizeOfMessage); - test.equal(null, self.stubBuffer); - assertBuffersEqual(test, buffer.slice(10, 19), self.buffer.slice(0, 9)); - // Test done - test.done(); -} - -exports['Should correctly parse message + in two packets from socket and smaller than 4 bytes additional one then partial message'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(20); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - // Add data to check - buffer[index + 4] = 0xff; - buffer[index + 5] = 0xff; - buffer[index + 6] = 0xff; - buffer[index + 7] = 0xff; - buffer[index + 8] = 0xfd; - buffer[index + 9] = 0xfe; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(0, 10), data); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 13)); - dataHandler(buffer.slice(13, 15)); - - // Check status of the parser - test.equal(5, self.bytesRead); - test.equal(10, self.sizeOfMessage); - test.equal(null, self.stubBuffer); - assertBuffersEqual(test, buffer.slice(10, 15), self.buffer.slice(0, 5)); - // Test done - test.done(); -} - -exports['Should correctly parse message + in two packets from socket and smaller than 4 bytes additional one then partial message'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(40); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - var value = 20; - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - var value = 15; - // Adjust the index - index = index + 20; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(0, 10), data); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 15)); - dataHandler(buffer.slice(15, 27)); - - // Check status of the parser - test.equal(17, self.bytesRead); - test.equal(20, self.sizeOfMessage); - test.equal(null, self.stubBuffer); - assertBuffersEqual(test, buffer.slice(10, 27), self.buffer.slice(0, 17)); - // Test done - test.done(); -} - -exports['Corrupt the message baby'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(40); - var value = -40; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - test.equal('parseError', message) - // test.equal('socketHandler', data.err) - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 15)); - dataHandler(buffer.slice(15, 27)); - test.done(); -} - -exports['Corrupt the message baby but catch the log error'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(40); - for(var i = 0; i < buffer.length; i++) buffer[i] = 0; - var value = -40; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - test.equal('parseError', message) - }}; - - // Count the number of errors - var totalCountOfErrors = 0; - - // Add a logger object - self.logger = { - doDebug:true, - doError:true, - doLog:true, - - error:function(message, object) { - totalCountOfErrors = totalCountOfErrors + 1; - if(totalCountOfErrors == 3) { - test.done(); - } - }, - - log:function(message, object) { - }, - - debug:function(message, object) { - } - } - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 15)); - dataHandler(buffer.slice(15, 27)); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/connection_test.js b/node_modules/mongodb/test/connection_test.js deleted file mode 100644 index f9148d6..0000000 --- a/node_modules/mongodb/test/connection_test.js +++ /dev/null @@ -1,171 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - connect = mongodb.connect, - Script = require('vm'), - Collection = mongodb.Collection, - Server = mongodb.Server, - ServerManager = require('../test/tools/server_manager').ServerManager, - Step = require("../deps/step/lib/step"), - mongodb = require('../lib/mongodb'); - -// Test db -var MONGODB = 'integration_tests'; -var client = null; - -function connectionTester(test, testName, callback) { - return function(err, db) { - test.equal(err, null); - db.collection(testName, function(err, collection) { - test.equal(err, null); - var doc = {foo:123}; - collection.insert({foo:123}, {safe:true}, function(err, docs) { - test.equal(err, null); - db.dropDatabase(function(err, done) { - test.equal(err, null); - test.ok(done); - callback(); - }); - }); - }); - }; -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldThrowErrorDueToSharedConnectionUsage = function(test) { - var server = new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}); - - try { - var db = new Db(MONGODB, server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - var db1 = new Db(MONGODB, server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - } catch(err) { - test.done(); - } -} - -exports.testCloseNoCallback = function(test) { - var db = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(connectionTester(test, 'testCloseNoCallback', function() { - var dbCloseCount = 0, connectionCloseCount = 0, poolCloseCount = 0; - // Ensure no close events are fired as we are closing the connection specifically - db.on('close', function() { dbCloseCount++; }); - - var connectionPool = db.serverConfig.connectionPool; - var connections = connectionPool.getAllConnections(); - - // Force the connection close, should not trigger close command - db.serverConfig.connectionPool.stop(); - // Test done - test.equal(0, dbCloseCount); - test.done(); - })); -} - -exports.testCloseWithCallback = function(test) { - var db = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}),{native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(connectionTester(test, 'testCloseWithCallback', function() { - var dbCloseCount = 0, connectionCloseCount = 0, poolCloseCount = 0; - // Ensure no close events are fired as we are closing the connection specifically - db.on('close', function() { dbCloseCount++; }); - - var connectionPool = db.serverConfig.connectionPool; - var connections = connectionPool.getAllConnections(); - - // Ensure no close events are fired as we are closing the connection specifically - for(var i = 0; i < connections.length; i++) { - connections[i].on("close", function() { test.ok(false); }); - } - - db.close(function() { - // Test done - test.equal(0, dbCloseCount); - test.done(); - }); - })); -} - -exports.testShouldCorrectlyCloseOnUnopedConnection = function(test) { - var db = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}),{native_parser: (process.env['TEST_NATIVE'] != null)}); - db.close(); - test.done(); -} - -exports.testConnectUsingDefaultHostAndPort = function(test) { - var db = new Db(MONGODB, new Server("127.0.0.1", mongodb.Connection.DEFAULT_PORT, {auto_reconnect: true, poolSize: 4, ssl:useSSL}),{native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, db) { - test.equal(null, err); - test.done(); - db.close(); - }) -} - -exports.testConnectUsingSocketOptions = function(test) { - var db = new Db(MONGODB, new Server("127.0.0.1", mongodb.Connection.DEFAULT_PORT, {auto_reconnect: true, poolSize: 4, socketOptions:{keepAlive:100}, ssl:useSSL}),{native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, db) { - test.equal(null, err); - test.equal(100, db.serverConfig.checkoutWriter().socketOptions.keepAlive) - test.done(); - db.close(); - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/cursor_test.js b/node_modules/mongodb/test/cursor_test.js deleted file mode 100644 index 4ac4fc7..0000000 --- a/node_modules/mongodb/test/cursor_test.js +++ /dev/null @@ -1,1965 +0,0 @@ -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = require('../lib/mongodb').Db, - Cursor = require('../lib/mongodb').Cursor, - Step = require("../deps/step/lib/step"), - Collection = require('../lib/mongodb').Collection, - fs = require('fs'), - Server = require('../lib/mongodb').Server; - -var MONGODB = 'integration_tests'; -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * An example showing the information returned by indexInformation - * - * @_class cursor - * @_function toArray - */ -exports.shouldCorrectlyExecuteToArray = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection to hold our documents - db.createCollection('test_array', function(err, collection) { - - // Insert a test document - collection.insert({'b':[1, 2, 3]}, {safe:true}, function(err, ids) { - - // Retrieve all the documents in the collection - collection.find().toArray(function(err, documents) { - test.equal(1, documents.length); - test.deepEqual([1, 2, 3], documents[0].b); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteToArrayAndFailOnFurtherCursorAccess = function(test) { - client.createCollection('test_to_a', function(err, collection) { - test.ok(collection instanceof Collection); - collection.insert({'a':1}, {safe:true}, function(err, ids) { - collection.find({}, function(err, cursor) { - cursor.toArray(function(err, items) { - // Should fail if called again (cursor should be closed) - cursor.toArray(function(err, items) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - - // Should fail if called again (cursor should be closed) - cursor.each(function(err, item) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example iterating over a query using the each function of the cursor. - * - * @_class cursor - * @_function each - * @ignore - */ -exports.shouldCorrectlyFailToArrayDueToFinishedEachOperation = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('test_to_a_after_each', function(err, collection) { - test.equal(null, err); - test.ok(collection instanceof Collection); - - // Insert a document in the collection - collection.insert({'a':1}, {safe:true}, function(err, ids) { - - // Grab a cursor - collection.find(function(err, cursor) { - - // Execute the each command, triggers for each document - cursor.each(function(err, item) { - - // If the item is null then the cursor is exhausted/empty and closed - if(item == null) { - - // Show that the cursor is closed - cursor.toArray(function(err, items) { - test.ok(err != null); - - // Let's close the db - test.done(); - db.close(); - }); - }; - }); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteCursorExplain = function(test) { - client.createCollection('test_explain', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, r) { - collection.find({'a':1}, function(err, cursor) { - cursor.explain(function(err, explaination) { - test.ok(explaination.cursor != null); - test.ok(explaination.n.constructor == Number); - test.ok(explaination.millis.constructor == Number); - test.ok(explaination.nscanned.constructor == Number); - - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteCursorCount = function(test) { - client.createCollection('test_count', function(err, collection) { - collection.find(function(err, cursor) { - cursor.count(function(err, count) { - test.equal(0, count); - - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 10; i++) { - collection.insert({'x':i}, {safe:true}, group()); - } - }, - - function finished() { - collection.find().count(function(err, count) { - test.equal(10, count); - test.ok(count.constructor == Number); - }); - - collection.find({}, {'limit':5}).count(function(err, count) { - test.equal(10, count); - }); - - collection.find({}, {'skip':5}).count(function(err, count) { - test.equal(10, count); - }); - - collection.find(function(err, cursor) { - cursor.count(function(err, count) { - test.equal(10, count); - - cursor.each(function(err, item) { - if(item == null) { - cursor.count(function(err, count2) { - test.equal(10, count2); - test.equal(count, count2); - // Let's close the db - test.done(); - }); - } - }); - }); - }); - - client.collection('acollectionthatdoesn', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - }); - }) - } - ) - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteSortOnCursor = function(test) { - client.createCollection('test_sort', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 5; i++) { - collection.insert({'a':i}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - cursor.sort(['a', 1], function(err, cursor) { - test.ok(cursor instanceof Cursor); - test.deepEqual(['a', 1], cursor.sortValue); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', 1, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.equal(0, doc.a); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', -1, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.equal(4, doc.a); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', "asc", function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.equal(0, doc.a); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort([['a', -1], ['b', 1]], function(err, cursor) { - test.ok(cursor instanceof Cursor); - test.deepEqual([['a', -1], ['b', 1]], cursor.sortValue); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', 1, function(err, cursor) { - cursor.sort('a', -1, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.equal(4, doc.a); - }); - }) - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', -1, function(err, cursor) { - cursor.sort('a', 1, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.equal(0, doc.a); - }); - }) - }); - }); - - collection.find(function(err, cursor) { - cursor.nextObject(function(err, doc) { - cursor.sort(['a'], function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', 25, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.ok(err instanceof Error); - test.equal("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]", err.message); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort(25, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.ok(err instanceof Error); - test.equal("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]", err.message); - // Let's close the db - test.done(); - }); - }); - }); - } - ); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyThrowErrorOnToArrayWhenMissingCallback = function(test) { - client.createCollection('test_to_array', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 2; i++) { - collection.save({'x':1}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - test.throws(function () { - cursor.toArray(); - }); - test.done(); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldThrowErrorOnEachWhenMissingCallback = function(test) { - client.createCollection('test_each', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 2; i++) { - collection.save({'x':1}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - test.throws(function () { - cursor.each(); - }); - test.done(); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyHandleLimitOnCursor = function(test) { - client.createCollection('test_cursor_limit', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 10; i++) { - collection.save({'x':1}, {safe:true}, group()); - } - }, - - function finished() { - collection.find().count(function(err, count) { - test.equal(10, count); - }); - - collection.find(function(err, cursor) { - cursor.limit(5, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(5, items.length); - // Let's close the db - test.done(); - }); - }); - }); - } - ); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyReturnErrorsOnIllegalLimitValues = function(test) { - client.createCollection('test_limit_exceptions', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, docs) {}); - collection.find(function(err, cursor) { - cursor.limit('not-an-integer', function(err, cursor) { - test.ok(err instanceof Error); - test.equal("limit requires an integer", err.message); - }); - }); - - collection.find(function(err, cursor) { - cursor.nextObject(function(err, doc) { - cursor.limit(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.close(function(err, cursor) { - cursor.limit(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlySkipRecordsOnCursor = function(test) { - client.createCollection('test_skip', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 10; i++) { - collection.insert({'x':i}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - cursor.count(function(err, count) { - test.equal(10, count); - }); - }); - - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(10, items.length); - - collection.find(function(err, cursor) { - cursor.skip(2, function(err, cursor) { - cursor.toArray(function(err, items2) { - test.equal(8, items2.length); - - // Check that we have the same elements - var numberEqual = 0; - var sliced = items.slice(2, 10); - - for(var i = 0; i < sliced.length; i++) { - if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1; - } - test.equal(8, numberEqual); - - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyReturnErrorsOnIllegalSkipValues = function(test) { - client.createCollection('test_skip_exceptions', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, docs) {}); - collection.find(function(err, cursor) { - cursor.skip('not-an-integer', function(err, cursor) { - test.ok(err instanceof Error); - test.equal("skip requires an integer", err.message); - }); - }); - - collection.find(function(err, cursor) { - cursor.nextObject(function(err, doc) { - cursor.skip(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.close(function(err, cursor) { - cursor.skip(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldReturnErrorsOnIllegalBatchSizes = function(test) { - client.createCollection('test_batchSize_exceptions', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, docs) {}); - collection.find(function(err, cursor) { - cursor.batchSize('not-an-integer', function(err, cursor) { - test.ok(err instanceof Error); - test.equal("batchSize requires an integer", err.message); - }); - }); - - collection.find(function(err, cursor) { - cursor.nextObject(function(err, doc) { - cursor.nextObject(function(err, doc) { - cursor.batchSize(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - }); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.close(function(err, cursor) { - cursor.batchSize(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyHandleChangesInBatchSizes = function(test) { - client.createCollection('test_not_multiple_batch_size', function(err, collection) { - var records = 6; - var batchSize = 2; - var docs = []; - for(var i = 0; i < records; i++) { - docs.push({'a':i}); - } - - collection.insert(docs, {safe:true}, function() { - collection.find({}, {batchSize : batchSize}, function(err, cursor) { - //1st - cursor.nextObject(function(err, items) { - //cursor.items should contain 1 since nextObject already popped one - test.equal(1, cursor.items.length); - test.ok(items != null); - - //2nd - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - test.ok(items != null); - - //test batch size modification on the fly - batchSize = 3; - cursor.batchSize(batchSize); - - //3rd - cursor.nextObject(function(err, items) { - test.equal(2, cursor.items.length); - test.ok(items != null); - - //4th - cursor.nextObject(function(err, items) { - test.equal(1, cursor.items.length); - test.ok(items != null); - - //5th - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - test.ok(items != null); - - //6th - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - test.ok(items != null); - - //No more - cursor.nextObject(function(err, items) { - test.ok(items == null); - test.ok(cursor.isClosed()); - - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyHandleBatchSize = function(test) { - client.createCollection('test_multiple_batch_size', function(err, collection) { - //test with the last batch that is a multiple of batchSize - var records = 4; - var batchSize = 2; - var docs = []; - for(var i = 0; i < records; i++) { - docs.push({'a':i}); - } - - collection.insert(docs, {safe:true}, function() { - collection.find({}, {batchSize : batchSize}, function(err, cursor) { - //1st - cursor.nextObject(function(err, items) { - test.equal(1, cursor.items.length); - test.ok(items != null); - - //2nd - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - test.ok(items != null); - - //3rd - cursor.nextObject(function(err, items) { - test.equal(1, cursor.items.length); - test.ok(items != null); - - //4th - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - test.ok(items != null); - - //No more - cursor.nextObject(function(err, items) { - test.ok(items == null); - test.ok(cursor.isClosed()); - - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldHandleWhenLimitBiggerThanBatchSize = function(test) { - client.createCollection('test_limit_greater_than_batch_size', function(err, collection) { - var limit = 4; - var records = 10; - var batchSize = 3; - var docs = []; - for(var i = 0; i < records; i++) { - docs.push({'a':i}); - } - - collection.insert(docs, {safe:true}, function() { - collection.find({}, {batchSize : batchSize, limit : limit}, function(err, cursor) { - //1st - cursor.nextObject(function(err, items) { - test.equal(2, cursor.items.length); - - //2nd - cursor.nextObject(function(err, items) { - test.equal(1, cursor.items.length); - - //3rd - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - - //4th - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - - //No more - cursor.nextObject(function(err, items) { - test.ok(items == null); - test.ok(cursor.isClosed()); - - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldHandleLimitLessThanBatchSize = function(test) { - client.createCollection('test_limit_less_than_batch_size', function(err, collection) { - var limit = 2; - var records = 10; - var batchSize = 4; - var docs = []; - for(var i = 0; i < records; i++) { - docs.push({'a':i}); - } - - collection.insert(docs, {safe:true}, function() { - collection.find({}, {batchSize : batchSize, limit : limit}, function(err, cursor) { - //1st - cursor.nextObject(function(err, items) { - test.equal(1, cursor.items.length); - - //2nd - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - - //No more - cursor.nextObject(function(err, items) { - test.ok(items == null); - test.ok(cursor.isClosed()); - - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldHandleSkipLimitChaining = function(test) { - client.createCollection('test_limit_skip_chaining', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 10; i++) { - collection.insert({'x':1}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(10, items.length); - - collection.find(function(err, cursor) { - cursor.limit(5, function(err, cursor) { - cursor.skip(3, function(err, cursor) { - cursor.toArray(function(err, items2) { - test.equal(5, items2.length); - - // Check that we have the same elements - var numberEqual = 0; - var sliced = items.slice(3, 8); - - for(var i = 0; i < sliced.length; i++) { - if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1; - } - test.equal(5, numberEqual); - - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyHandleLimitSkipChainingInline = function(test) { - client.createCollection('test_limit_skip_chaining_inline', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 10; i++) { - collection.insert({'x':1}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(10, items.length); - - collection.find(function(err, cursor) { - cursor.limit(5).skip(3).toArray(function(err, items2) { - test.equal(5, items2.length); - - // Check that we have the same elements - var numberEqual = 0; - var sliced = items.slice(3, 8); - - for(var i = 0; i < sliced.length; i++) { - if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1; - } - test.equal(5, numberEqual); - - // Let's close the db - test.done(); - }); - }); - }); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCloseCursorNoQuerySent = function(test) { - client.createCollection('test_close_no_query_sent', function(err, collection) { - collection.find(function(err, cursor) { - cursor.close(function(err, cursor) { - test.equal(true, cursor.isClosed()); - // Let's close the db - test.done(); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyRefillViaGetMoreCommand = function(test) { - var COUNT = 1000; - - client.createCollection('test_refill_via_get_more', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < COUNT; i++) { - collection.save({'a': i}, {safe:true}, group()); - } - }, - - function finished() { - collection.count(function(err, count) { - test.equal(COUNT, count); - }); - - var total = 0; - var i = 0; - collection.find({}, {}, function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - total = total + item.a; - } else { - test.equal(499500, total); - - collection.count(function(err, count) { - test.equal(COUNT, count); - }); - - collection.count(function(err, count) { - test.equal(COUNT, count); - - var total2 = 0; - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - total2 = total2 + item.a; - } else { - test.equal(499500, total2); - collection.count(function(err, count) { - test.equal(COUNT, count); - test.equal(total, total2); - // Let's close the db - test.done(); - }); - } - }); - }); - }); - } - }); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyRefillViaGetMoreAlternativeCollection = function(test) { - client.createCollection('test_refill_via_get_more_alt_coll', function(err, collection) { - - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 1000; i++) { - collection.save({'a': i}, {safe:true}, group()); - } - }, - - function finished() { - collection.count(function(err, count) { - test.equal(1000, count); - }); - - var total = 0; - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - total = total + item.a; - } else { - test.equal(499500, total); - - collection.count(function(err, count) { - test.equal(1000, count); - }); - - collection.count(function(err, count) { - test.equal(1000, count); - - var total2 = 0; - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - total2 = total2 + item.a; - } else { - test.equal(499500, total2); - collection.count(function(err, count) { - test.equal(1000, count); - test.equal(total, total2); - // Let's close the db - test.done(); - }); - } - }); - }); - }); - } - }); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCloseCursorAfterQueryHasBeenSent = function(test) { - client.createCollection('test_close_after_query_sent', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, r) { - collection.find({'a':1}, function(err, cursor) { - cursor.nextObject(function(err, item) { - cursor.close(function(err, cursor) { - test.equal(true, cursor.isClosed()); - // Let's close the db - test.done(); - }) - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteCursorCountWithFields = function(test) { - client.createCollection('test_count_with_fields', function(err, collection) { - collection.save({'x':1, 'a':2}, {safe:true}, function(err, doc) { - collection.find({}, {'fields':['a']}).toArray(function(err, items) { - test.equal(1, items.length); - test.equal(2, items[0].a); - test.equal(null, items[0].x); - }); - - collection.findOne({}, {'fields':['a']}, function(err, item) { - test.equal(2, item.a); - test.equal(null, item.x); - test.done(); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyCountWithFieldsUsingExclude = function(test) { - client.createCollection('test_count_with_fields_using_exclude', function(err, collection) { - collection.save({'x':1, 'a':2}, {safe:true}, function(err, doc) { - collection.find({}, {'fields':{'x':0}}).toArray(function(err, items) { - test.equal(1, items.length); - test.equal(2, items[0].a); - test.equal(null, items[0].x); - test.done(); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteEnsureIndexWithNoCallback = function(test) { - var docs = []; - - for(var i = 0; i < 1; i++) { - var d = new Date().getTime() + i*1000; - docs[i] = {createdAt:new Date(d)}; - } - - // Create collection - client.createCollection('shouldCorrectlyExecuteEnsureIndexWithNoCallback', function(err, collection) { - // ensure index of createdAt index - collection.ensureIndex({createdAt:1}) - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - // Find with sort - collection.find().sort(['createdAt', 'asc']).toArray(function(err, items) { - if (err) logger.error("error in collection_info.find: " + err); - test.equal(1, items.length); - test.done(); - }) - }) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyInsert5000RecordsWithDateAndSortCorrectlyWithIndex = function(test) { - var docs = []; - - for(var i = 0; i < 5000; i++) { - var d = new Date().getTime() + i*1000; - docs[i] = {createdAt:new Date(d)}; - } - - // Create collection - client.createCollection('shouldCorrectlyInsert5000RecordsWithDateAndSortCorrectlyWithIndex', function(err, collection) { - // ensure index of createdAt index - collection.ensureIndex({createdAt:1}, function(err, indexName) { - test.equal(null, err); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - // Find with sort - collection.find().sort(['createdAt', 'asc']).toArray(function(err, items) { - if (err) logger.error("error in collection_info.find: " + err); - test.equal(5000, items.length); - test.done(); - }) - }) - }); - }); -} - -/** - * An example showing the information returned by indexInformation - * - * @_class cursor - * @_function rewind - */ -exports['Should correctly rewind and restart cursor'] = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - var docs = []; - - // Insert 100 documents with some data - for(var i = 0; i < 100; i++) { - var d = new Date().getTime() + i*1000; - docs[i] = {'a':i, createdAt:new Date(d)}; - } - - // Create collection - db.createCollection('Should_correctly_rewind_and_restart_cursor', function(err, collection) { - test.equal(null, err); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - // Grab a cursor using the find - var cursor = collection.find({}); - // Fetch the first object off the cursor - cursor.nextObject(function(err, item) { - test.equal(0, item.a) - // Rewind the cursor, resetting it to point to the start of the query - cursor.rewind(); - - // Grab the first object again - cursor.nextObject(function(err, item) { - test.equal(0, item.a) - - db.close(); - test.done(); - }) - }) - }) - }); - }); -} - -/** - * @ignore - * @api private - */ -exports['Should correctly execute count on cursor'] = function(test) { - var docs = []; - - for(var i = 0; i < 1000; i++) { - var d = new Date().getTime() + i*1000; - docs[i] = {'a':i, createdAt:new Date(d)}; - } - - // Create collection - client.createCollection('Should_correctly_execute_count_on_cursor', function(err, collection) { - test.equal(null, err); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - var total = 0; - // Create a cursor for the content - var cursor = collection.find({}); - cursor.count(function(err, c) { - // Ensure each returns all documents - cursor.each(function(err, item) { - if(item != null) { - total++; - } else { - cursor.count(function(err, c) { - test.equal(1000, c); - test.equal(1000, total); - test.done(); - }) - } - }); - }) - }) - }); -} - -/** - * @ignore - * @api private - */ -exports['should be able to stream documents'] = function(test) { - var docs = []; - - for (var i = 0; i < 1000; i++) { - docs[i] = { a: i+1 }; - } - - // Create collection - client.createCollection('Should_be_able_to_stream_documents', function(err, collection) { - test.equal(null, err); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - var paused = 0 - , closed = 0 - , resumed = 0 - , i = 0 - , err - - var stream = collection.find().stream(); - - stream.on('data', function (doc) { - test.equal(true, !! doc); - test.equal(true, !! doc.a); - - if (paused > 0 && 0 === resumed) { - err = new Error('data emitted during pause'); - return done(); - } - - if (++i === 3) { - test.equal(false, stream.paused); - stream.pause(); - test.equal(true, stream.paused); - paused++; - - setTimeout(function () { - test.equal(true, stream.paused); - stream.resume(); - test.equal(false, stream.paused); - resumed++; - }, 20); - } - }); - - stream.on('error', function (er) { - err = er; - done(); - }); - - stream.on('close', function () { - closed++; - done(); - }); - - function done () { - test.equal(undefined, err); - test.equal(i, docs.length); - test.equal(1, closed); - test.equal(1, paused); - test.equal(1, resumed); - test.strictEqual(stream._cursor.isClosed(), true); - test.done(); - } - }) - }) -} - -/** - * @ignore - * @api private - */ -exports['immediately destroying a stream prevents the query from executing'] = function(test) { - var i = 0 - , docs = [{ b: 2 }, { b: 3 }] - , doneCalled = 0 - - client.createCollection('immediately_destroying_a_stream_prevents_the_query_from_executing', function(err, collection) { - test.equal(null, err); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - var stream = collection.find().stream(); - - stream.on('data', function () { - i++; - }) - stream.on('close', done); - stream.on('error', done); - - stream.destroy(); - - function done (err) { - test.equal(++doneCalled, 1); - test.equal(undefined, err); - test.strictEqual(0, i); - test.strictEqual(true, stream._destroyed); - test.done(); - } - }); - }); -} - -/** - * @ignore - * @api private - */ -exports['destroying a stream stops it'] = function(test) { - client.createCollection('destroying_a_stream_stops_it', function(err, collection) { - test.equal(null, err); - - var docs = []; - for (var ii = 0; ii < 10; ++ii) docs.push({ b: ii+1 }); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - var finished = 0 - , i = 0 - - var stream = collection.find().stream(); - - test.strictEqual(null, stream._destroyed); - test.strictEqual(true, stream.readable); - - stream.on('data', function (doc) { - if (++i === 5) { - stream.destroy(); - test.strictEqual(false, stream.readable); - } - }); - - stream.on('close', done); - stream.on('error', done); - - function done (err) { - ++finished; - setTimeout(function () { - test.strictEqual(undefined, err); - test.strictEqual(5, i); - test.strictEqual(1, finished); - test.strictEqual(true, stream._destroyed); - test.strictEqual(false, stream.readable); - test.strictEqual(true, stream._cursor.isClosed()); - test.done(); - }, 150) - } - }); - }); -} - -/** - * @ignore - * @api private - */ -exports['cursor stream errors']= function(test) { - var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - test.equal(null, err); - - client.createCollection('cursor_stream_errors', function(err, collection) { - test.equal(null, err); - - var docs = []; - for (var ii = 0; ii < 10; ++ii) docs.push({ b: ii+1 }); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - var finished = 0 - , closed = 0 - , i = 0 - - var stream = collection.find({}, { batchSize: 5 }).stream(); - - stream.on('data', function (doc) { - if (++i === 5) { - client.close(); - } - }); - - stream.on('close', function () { - closed++; - }); - - stream.on('error', done); - - function done (err) { - ++finished; - setTimeout(function () { - test.equal('no open connections', err.message); - test.equal(5, i); - test.equal(1, closed); - test.equal(1, finished); - test.equal(true, stream._destroyed); - test.equal(false, stream.readable); - test.equal(true, stream._cursor.isClosed()); - test.done(); - }, 150) - } - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports['cursor stream pipe']= function(test) { - client.createCollection('cursor_stream_pipe', function(err, collection) { - test.equal(null, err); - - var docs = []; - ;('Aaden Aaron Adrian Aditya Bob Joe').split(' ').forEach(function (name) { - docs.push({ name: name }); - }); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - var filename = '/tmp/_nodemongodbnative_stream_out.txt' - , out = fs.createWriteStream(filename) - - // hack so we don't need to create a stream filter just to - // stringify the objects (otherwise the created file would - // just contain a bunch of [object Object]) - var toString = Object.prototype.toString; - Object.prototype.toString = function () { - return JSON.stringify(this); - } - - var stream = collection.find().stream(); - stream.pipe(out); - - stream.on('error', done); - stream.on('close', done); - - function done (err) { - Object.prototype.toString = toString; - test.strictEqual(undefined, err); - var contents = fs.readFileSync(filename, 'utf8'); - test.ok(/Aaden/.test(contents)); - test.ok(/Aaron/.test(contents)); - test.ok(/Adrian/.test(contents)); - test.ok(/Aditya/.test(contents)); - test.ok(/Bob/.test(contents)); - test.ok(/Joe/.test(contents)); - fs.unlink(filename); - test.done(); - } - }); - }); -} - -/** - * A simple example showing the count function of the cursor. - * - * @_class cursor - * @_function count - * @ignore - */ -exports.shouldCorrectlyUseCursorCountFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Creat collection - db.createCollection('cursor_count_collection', function(err, collection) { - test.equal(null, err); - - // Insert some docs - collection.insert([{a:1}, {a:2}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Do a find and get the cursor count - collection.find().count(function(err, count) { - test.equal(null, err); - test.equal(2, count); - - db.close(); - test.done(); - }) - }); - }); - }); -} - -/** - * A simple example showing the use of sort on the cursor. - * - * @_class cursor - * @_function sort - * @ignore - */ -exports.shouldCorrectlyPeformSimpleSorts = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_sort_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Do normal ascending sort - collection.find().sort([['a', 1]]).nextObject(function(err, item) { - test.equal(null, err); - test.equal(1, item.a); - - // Do normal descending sort - collection.find().sort([['a', -1]]).nextObject(function(err, item) { - test.equal(null, err); - test.equal(3, item.a); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of limit on the cursor - * - * @_class cursor - * @_function limit - * @ignore - */ -exports.shouldCorrectlyPeformLimitOnCursor = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_limit_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Limit to only one document returned - collection.find().limit(1).toArray(function(err, items) { - test.equal(null, err); - test.equal(1, items.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of skip on the cursor - * - * @_class cursor - * @_function skip - * @ignore - */ -exports.shouldCorrectlyPeformSkipOnCursor = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_skip_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Skip one document - collection.find().skip(1).nextObject(function(err, item) { - test.equal(null, err); - test.equal(2, item.a); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of batchSize on the cursor, batchSize only regulates how many - * documents are returned for each batch using the getMoreCommand against the MongoDB server - * - * @_class cursor - * @_function batchSize - * @ignore - */ -exports.shouldCorrectlyPeformBatchSizeOnCursor = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_batch_size_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Do normal ascending sort - collection.find().batchSize(1).nextObject(function(err, item) { - test.equal(null, err); - test.equal(1, item.a); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of nextObject. - * - * @_class cursor - * @_function nextObject - * @ignore - */ -exports.shouldCorrectlyPeformNextObjectOnCursor = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_next_object_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Do normal ascending sort - collection.find().nextObject(function(err, item) { - test.equal(null, err); - test.equal(1, item.a); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursor explain function. - * - * @_class cursor - * @_function explain - * @ignore - */ -exports.shouldCorrectlyPeformSimpleExplainCursor = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_explain_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Do normal ascending sort - collection.find().explain(function(err, explaination) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursor streamRecords function. - * - * @_class cursor - * @_function streamRecords - * @ignore - */ -exports.shouldStreamDocumentsUsingTheStreamRecords = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 100; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_streamingRecords_function', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var stream = collection.find().streamRecords({fetchSize:1000}); - - // Execute find on all the documents - stream.on('end', function() { - db.close(); - test.done(); - }); - - stream.on('data', function(data) { - test.ok(data != null); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursor stream function. - * - * @_class cursor - * @_function stream - * @ignore - */ -exports.shouldStreamDocumentsUsingTheStreamFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 100; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_stream_function', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var stream = collection.find().stream(); - - // Execute find on all the documents - stream.on('close', function() { - db.close(); - test.done(); - }); - - stream.on('data', function(data) { - test.ok(data != null); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursor close function. - * - * @_class cursor - * @_function close - * @ignore - */ -exports.shouldStreamDocumentsUsingTheCloseFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 100; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_close_function_on_cursor', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var cursor = collection.find(); - - // Fetch the first object - cursor.nextObject(function(err, object) { - test.equal(null, err); - - // Close the cursor, this is the same as reseting the query - cursor.close(function(err, result) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursor close function. - * - * @_class cursor - * @_function isClosed - * @ignore - */ -exports.shouldStreamDocumentsUsingTheIsCloseFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 100; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_is_close_function_on_cursor', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var cursor = collection.find(); - - // Fetch the first object - cursor.nextObject(function(err, object) { - test.equal(null, err); - - // Close the cursor, this is the same as reseting the query - cursor.close(function(err, result) { - test.equal(null, err); - test.equal(true, cursor.isClosed()); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/cursorstream_test.js b/node_modules/mongodb/test/cursorstream_test.js deleted file mode 100644 index 270324e..0000000 --- a/node_modules/mongodb/test/cursorstream_test.js +++ /dev/null @@ -1,231 +0,0 @@ -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = require('../lib/mongodb').Db, - Cursor = require('../lib/mongodb').Cursor, - Step = require("../deps/step/lib/step"), - Collection = require('../lib/mongodb').Collection, - fs = require('fs'), - Server = require('../lib/mongodb').Server; - -var MONGODB = 'integration_tests'; -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple example showing the use of the cursorstream pause function. - * - * @_class cursorstream - * @_function pause - * @ignore - */ -exports.shouldStreamDocumentsUsingTheCursorStreamPauseFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 1; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_cursorstream_pause', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var stream = collection.find().stream(); - - // For each data item - stream.on("data", function(item) { - // Check if cursor is paused - test.equal(false, stream.paused); - // Pause stream - stream.pause(); - // Check if cursor is paused - test.equal(true, stream.paused); - - // Restart the stream after 1 miliscecond - setTimeout(function() { - stream.resume(); - // Check if cursor is paused - test.equal(false, stream.paused); - }, 1); - }); - - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursorstream resume function. - * - * @_class cursorstream - * @_function resume - * @ignore - */ -exports.shouldStreamDocumentsUsingTheCursorStreamResumeFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 1; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_cursorstream_resume', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var stream = collection.find().stream(); - - // For each data item - stream.on("data", function(item) { - // Check if cursor is paused - test.equal(false, stream.paused); - // Pause stream - stream.pause(); - // Check if cursor is paused - test.equal(true, stream.paused); - - // Restart the stream after 1 miliscecond - setTimeout(function() { - - // Resume the stream - stream.resume(); - - // Check if cursor is paused - test.equal(false, stream.paused); - }, 1); - }); - - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursorstream resume function. - * - * @_class cursorstream - * @_function destroy - * @ignore - */ -exports.shouldStreamDocumentsUsingTheCursorStreamDestroyFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 1; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_cursorstream_destroy', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var stream = collection.find().stream(); - - // For each data item - stream.on("data", function(item) { - // Destroy stream - stream.destroy(); - }); - - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/custom_pk_test.js b/node_modules/mongodb/test/custom_pk_test.js deleted file mode 100644 index c1b6c74..0000000 --- a/node_modules/mongodb/test/custom_pk_test.js +++ /dev/null @@ -1,107 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCreateRecordsWithCustomPKFactory = function(test) { - // Custom factory (need to provide a 12 byte array); - var CustomPKFactory = function() {} - CustomPKFactory.prototype = new Object(); - CustomPKFactory.createPk = function() { - return new ObjectID("aaaaaaaaaaaa"); - } - - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {ssl:useSSL}), {'pk':CustomPKFactory, native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - p_client.dropDatabase(function(err, done) { - p_client.createCollection('test_custom_key', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, doc) { - collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(1, items.length); - - p_client.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -exports.testConnectBadUrl = function(test) { - test.throws(function() { - connect('mango://localhost:27017/' + MONGODB, function(err, db) { - test.ok(false, 'Bad URL!'); - }); - }); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/db_test.js b/node_modules/mongodb/test/db_test.js deleted file mode 100644 index 68f3266..0000000 --- a/node_modules/mongodb/test/db_test.js +++ /dev/null @@ -1,1441 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - DBRef = require('../lib/mongodb/bson/db_ref').DBRef, - Code = require('../lib/mongodb/bson/code').Code, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleIllegalDbNames = function(test) { - // Assert rename - try { - new Db(5); - } catch(err) { - test.ok(err instanceof Error); - test.equal("database name must be a string", err.message); - } - - try { - new Db(""); - } catch(err) { - test.ok(err instanceof Error); - test.equal("database name cannot be the empty string", err.message); - } - - try { - new Db("te$t", function(err, collection) {}); - } catch(err) { - test.equal("database names cannot contain the character '$'", err.message); - } - - try { - new Db(".test", function(err, collection) {}); - } catch(err) { - test.equal("database names cannot contain the character '.'", err.message); - } - - try { - new Db("\\test", function(err, collection) {}); - } catch(err) { - test.equal("database names cannot contain the character '\\'", err.message); - } - - try { - new Db("\\test", function(err, collection) {}); - } catch(err) { - test.equal("database names cannot contain the character '\\'", err.message); - } - - try { - new Db("test test", function(err, collection) {}); - } catch(err) { - test.equal("database names cannot contain the character ' '", err.message); - } - - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformAutomaticConnect = function(test) { - var automatic_connect_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null), retryMiliSeconds:50}); - automatic_connect_client.open(function(err, automatic_connect_client) { - // Listener for closing event - var closeListener = function(has_error) { - // Let's insert a document - automatic_connect_client.collection('test_object_id_generation.data2', function(err, collection) { - // Insert another test document and collect using ObjectId - collection.insert({"name":"Patty", "age":34}, {safe:true}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]._id.toHexString().length == 24); - - collection.findOne({"name":"Patty"}, function(err, document) { - test.equal(ids[0]._id.toHexString(), document._id.toHexString()); - // Let's close the db - automatic_connect_client.close(); - test.done(); - }); - }); - }); - }; - - // Add listener to close event - automatic_connect_client.on("close", closeListener); - automatic_connect_client.close(); - }); -} - -/** - * An example that shows how to force close a db connection so it cannot be reused. - * - * @_class db - * @_function close - * @ignore - */ -exports.shouldCorrectlyFailOnRetryDueToAppCloseOfDb = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection - db.collection('shouldCorrectlyFailOnRetryDueToAppCloseOfDb', function(err, collection) { - - // Insert a document - collection.insert({a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - // Force close the connection - db.close(true, function(err, result) { - - // Attemp to insert should fail now with correct message 'db closed by application' - collection.insert({a:2}, {safe:true}, function(err, result) { - test.equal('db closed by application', err.message); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A whole bunch of examples on how to use eval on the server. - * - * @_class db - * @_function eval - * @ignore - */ -exports.shouldCorrectlyExecuteEvalFunctions = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Evaluate a function on the server with the parameter 3 passed in - db.eval('function (x) {return x;}', [3], function(err, result) { - test.equal(3, result); - }); - - // Evaluate a function on the server with the parameter 3 passed in no lock aquired for eval - // on server - db.eval('function (x) {return x;}', [3], {nolock:true}, function(err, result) { - test.equal(3, result); - }); - - // Evaluate a function on the server that writes to a server collection - db.eval('function (x) {db.test_eval.save({y:x});}', [5], function(err, result) { - // Locate the entry - client.collection('test_eval', function(err, collection) { - collection.findOne(function(err, item) { - test.equal(5, item.y); - }); - }); - }); - - // Evaluate a function with 2 parameters passed in - db.eval('function (x, y) {return x + y;}', [2, 3], function(err, result) { - test.equal(5, result); - }); - - // Evaluate a function with no parameters passed in - db.eval('function () {return 5;}', function(err, result) { - test.equal(5, result); - }); - - // Evaluate a statement - db.eval('2 + 3;', function(err, result) { - test.equal(5, result); - }); - - // Evaluate a statement using the code object - db.eval(new Code("2 + 3;"), function(err, result) { - test.equal(5, result); - }); - - // Evaluate a statement using the code object including a scope - db.eval(new Code("return i;", {'i':2}), function(err, result) { - test.equal(2, result); - }); - - // Evaluate a statement using the code object including a scope - db.eval(new Code("i + 3;", {'i':2}), function(err, result) { - test.equal(5, result); - test.done(); - }); - - // Evaluate an illegal statement - db.eval("5 ++ 5;", function(err, result) { - test.ok(err instanceof Error); - test.ok(err.message != null); - // Let's close the db - test.done(); - }); - - db.close(); - test.done(); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyDereferenceDbRef = function(test) { - client.createCollection('test_deref', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, ids) { - collection.remove({}, {safe:true}, function(err, result) { - collection.count(function(err, count) { - test.equal(0, count); - - // Execute deref a db reference - client.dereference(new DBRef("test_deref", new ObjectID()), function(err, result) { - collection.insert({'x':'hello'}, {safe:true}, function(err, ids) { - collection.findOne(function(err, document) { - test.equal('hello', document.x); - - client.dereference(new DBRef("test_deref", document._id), function(err, result) { - test.equal('hello', document.x); - - client.dereference(new DBRef("test_deref", 4), function(err, result) { - var obj = {'_id':4}; - - collection.insert(obj, {safe:true}, function(err, ids) { - client.dereference(new DBRef("test_deref", 4), function(err, document) { - - test.equal(obj['_id'], document._id); - collection.remove({}, {safe:true}, function(err, result) { - collection.insert({'x':'hello'}, {safe:true}, function(err, ids) { - client.dereference(new DBRef("test_deref", null), function(err, result) { - test.equal(null, result); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }) - }) - }) - }); -} - -/** - * An example of illegal and legal renaming of a collection - * - * @_class collection - * @_function rename - * @ignore - */ -exports.shouldCorrectlyRenameCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Open a couple of collections - db.createCollection('test_rename_collection', function(err, collection1) { - db.createCollection('test_rename_collection2', function(err, collection2) { - - // Attemp to rename a collection to a number - try { - collection1.rename(5, function(err, collection) {}); - } catch(err) { - test.ok(err instanceof Error); - test.equal("collection name must be a String", err.message); - } - - // Attemp to rename a collection to an empty string - try { - collection1.rename("", function(err, collection) {}); - } catch(err) { - test.ok(err instanceof Error); - test.equal("collection names cannot be empty", err.message); - } - - // Attemp to rename a collection to an illegal name including the character $ - try { - collection1.rename("te$t", function(err, collection) {}); - } catch(err) { - test.ok(err instanceof Error); - test.equal("collection names must not contain '$'", err.message); - } - - // Attemp to rename a collection to an illegal name starting with the character . - try { - collection1.rename(".test", function(err, collection) {}); - } catch(err) { - test.ok(err instanceof Error); - test.equal("collection names must not start or end with '.'", err.message); - } - - // Attemp to rename a collection to an illegal name ending with the character . - try { - collection1.rename("test.", function(err, collection) {}); - } catch(err) { - test.ok(err instanceof Error); - test.equal("collection names must not start or end with '.'", err.message); - } - - // Attemp to rename a collection to an illegal name with an empty middle name - try { - collection1.rename("tes..t", function(err, collection) {}); - } catch(err) { - test.equal("collection names cannot be empty", err.message); - } - - // Insert a couple of documents - collection1.insert([{'x':1}, {'x':2}], {safe:true}, function(err, docs) { - - // Attemp to rename the first collection to the second one, this will fail - collection1.rename('test_rename_collection2', function(err, collection) { - test.ok(err instanceof Error); - test.ok(err.message.length > 0); - - // Attemp to rename the first collection to a name that does not exist - // this will be succesful - collection1.rename('test_rename_collection3', function(err, collection) { - test.equal("test_rename_collection3", collection.collectionName); - - // Ensure that the collection is pointing to the new one - collection1.count(function(err, count) { - test.equal(2, count); - db.close(); - test.done(); - }); - }); - }); - }) - }); - }); - }); -} - -/** - * An example of a simple single server db connection - * - * @_class db - * @_function open - * @ignore - */ -exports.shouldCorrectlyOpenASimpleDbSingleServerConnection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - db.close(); - test.done(); - }); -} - -/** - * An example of a simple single server db connection and close function - * - * @_class db - * @_function close - * @ignore - */ -exports.shouldCorrectlyOpenASimpleDbSingleServerConnection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Close the connection with a callback that is optional - db.close(function(err, result) { - test.equal(null, err); - - test.done(); - }); - }); -} - -/** - * An example of retrieveing the information of all the collections. - * - * @_class db - * @_function collectionsInfo - * @ignore - */ -exports.shouldCorrectlyRetrieveCollectionInfo = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection('test_collections_info', function(err, r) { - test.equal(null, err); - - // Return the information of a single collection name - db.collectionsInfo("test_collections_info").toArray(function(err, items) { - test.equal(1, items.length); - - // Return the information of a all collections, using the callback format - db.collectionsInfo(function(err, cursor) { - - // Turn the cursor into an array of results - cursor.toArray(function(err, items) { - test.ok(items.length > 0); - - db.close(); - test.done(); - }); - }) - }); - }); - }); -} - -/** - * An example of retrieveing the collection names for a database. - * - * @_class db - * @_function collectionNames - * @ignore - */ -exports.shouldCorrectlyRetrieveCollectionInfo = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection('test_collections_info', function(err, r) { - test.equal(null, err); - - // Return the information of a single collection name - db.collectionNames("test_collections_info", function(err, items) { - test.equal(1, items.length); - - // Return the information of a all collections, using the callback format - db.collectionNames(function(err, items) { - test.ok(items.length > 0); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * An example of retrieving a collection from a db using the collection function. - * - * @_class db - * @_function collection - * @ignore - */ -exports.shouldCorrectlyAccessACollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Grab a collection without a callback no safe mode - var col1 = db.collection('test_correctly_access_collections'); - - // Grab a collection with a callback but no safe operation - db.collection('test_correctly_access_collections', function(err, col2) { - test.equal(null, err); - - // Grab a collection with a callback in safe mode, ensuring it exists (should fail as it's not created) - db.collection('test_correctly_access_collections', {safe:true}, function(err, col3) { - test.ok(err != null); - - // Create the collection - db.createCollection('test_correctly_access_collections', function(err, result) { - - // Retry to get the collection, should work as it's now created - db.collection('test_correctly_access_collections', {safe:true}, function(err, col3) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * An example of retrieving all collections for a db as Collection objects - * - * @_class db - * @_function collections - * @ignore - */ -exports.shouldCorrectlyRetrieveAllCollections = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create the collection - db.createCollection('test_correctly_access_collections', function(err, result) { - - // Retry to get the collection, should work as it's now created - db.collections(function(err, collections) { - test.equal(null, err); - test.ok(collections.length > 0); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleFailedConnection = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 25117, {auto_reconnect: false, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - test.ok(err != null) - test.done(); - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyResaveDBRef = function(test) { - client.dropCollection('test_resave_dbref', function() { - client.createCollection('test_resave_dbref', function(err, collection) { - test.ifError(err); - - collection.insert({'name': 'parent'}, {safe : true}, function(err, objs) { - test.ok(objs && objs.length == 1 && objs[0]._id != null); - var parent = objs[0]; - var child = {'name' : 'child', 'parent' : new DBRef("test_resave_dbref", parent._id)}; - - collection.insert(child, {safe : true}, function(err, objs) { - test.ifError(err); - - collection.findOne({'name' : 'child'}, function(err, child) { //Child deserialized - test.ifError(err); - test.ok(child != null); - - collection.save(child, {save : true}, function(err) { - test.ifError(err); //Child node with dbref resaved! - - collection.findOne({'parent' : new DBRef("test_resave_dbref", parent._id)}, - function(err, child) { - test.ifError(err); - test.ok(child != null);//!!!! Main test point! - test.done(); - }) - }); - }); - }); - }); - }); - }); -}, - -/** - * An example of dereferencing values. - * - * @_class db - * @_function dereference - * @ignore - */ -exports.shouldCorrectlyDereferenceDbRefExamples = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Get a second db - var secondDb = db.db('integration_tests_2'); - - // Create a dereference example - secondDb.createCollection('test_deref_examples', function(err, collection) { - - // Insert a document in the collection - collection.insert({'a':1}, {safe:true}, function(err, ids) { - - // Let's build a db reference and resolve it - var dbRef = new DBRef('test_deref_examples', ids[0]._id, 'integration_tests_2'); - - // Resolve it including a db resolve - db.dereference(dbRef, function(err, item) { - test.equal(1, item.a); - - // Let's build a db reference and resolve it - var dbRef = new DBRef('test_deref_examples', ids[0]._id); - - // Simple local resolve - secondDb.dereference(dbRef, function(err, item) { - test.equal(1, item.a); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * An example of using the logout command for the database. - * - * @_class db - * @_function logout - * @ignore - */ -exports.shouldCorrectlyLogoutFromTheDatabase = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Add a user to the database - db.addUser('user', 'name', function(err, result) { - test.equal(null, err); - - // Authenticate - db.authenticate('user', 'name', function(err, result) { - test.equal(true, result); - - // Logout the db - db.logout(function(err, result) { - test.equal(true, result); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * An example of using the authenticate command. - * - * @_class db - * @_function authenticate - * @ignore - */ -exports.shouldCorrectlyAuthenticateAgainstTheDatabase = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Add a user to the database - db.addUser('user', 'name', function(err, result) { - test.equal(null, err); - - // Authenticate - db.authenticate('user', 'name', function(err, result) { - test.equal(true, result); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * An example of adding a user to the database. - * - * @_class db - * @_function addUser - * @ignore - */ -exports.shouldCorrectlyAuthenticateAgainstTheDatabase = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Add a user to the database - db.addUser('user', 'name', function(err, result) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); -} - -/** - * An example of dereferencing values. - * - * @_class db - * @_function removeUser - * @ignore - */ -exports.shouldCorrectlyAddAndRemoveUser = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Add a user to the database - db.addUser('user', 'name', function(err, result) { - test.equal(null, err); - - // Authenticate - db.authenticate('user', 'name', function(err, result) { - test.equal(true, result); - - // Logout the db - db.logout(function(err, result) { - test.equal(true, result); - - // Remove the user from the db - db.removeUser('user', function(err, result) { - - // Authenticate - db.authenticate('user', 'name', function(err, result) { - test.equal(false, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the creation of a collection. - * - * @_class db - * @_function createCollection - * @ignore - */ -exports.shouldCorrectlyCreateACollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a capped collection with a maximum of 1000 documents - db.createCollection("a_simple_collection", {capped:true, size:10000, max:1000, safe:true}, function(err, collection) { - test.equal(null, err); - - // Insert a document in the capped collection - collection.insert({a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * A simple example executing a command against the server. - * - * @_class db - * @_function dropCollection - * @ignore - */ -exports.shouldCorrectlyExecuteACommandAgainstTheServer = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Execute ping against the server - db.command({ping:1}, function(err, result) { - test.equal(null, err); - - // Create a capped collection with a maximum of 1000 documents - db.createCollection("a_simple_create_drop_collection", {capped:true, size:10000, max:1000, safe:true}, function(err, collection) { - test.equal(null, err); - - // Insert a document in the capped collection - collection.insert({a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - // Drop the collection from this world - db.dropCollection("a_simple_create_drop_collection", function(err, result) { - test.equal(null, err); - - // Verify that the collection is gone - db.collectionNames("a_simple_create_drop_collection", function(err, names) { - test.equal(0, names.length); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example creating, dropping a collection and then verifying that the collection is gone. - * - * @_class db - * @_function command - * @ignore - */ -exports.shouldCorrectlyCreateDropAndVerifyThatCollectionIsGone = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Execute ping against the server - db.command({ping:1}, function(err, result) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); -} - -/** - * A simple example creating, dropping a collection and then verifying that the collection is gone. - * - * @_class db - * @_function renameCollection - * @ignore - */ -exports.shouldCorrectlyRenameACollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection("simple_rename_collection", {safe:true}, function(err, collection) { - test.equal(null, err); - - // Insert a document in the collection - collection.insert({a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - // Rename the collection - db.renameCollection("simple_rename_collection", "simple_rename_collection_2", function(err, collection2) { - test.equal(null, err); - - // Retrieve the number of documents from the collection - collection2.count(function(err, count) { - test.equal(1, count); - - // Verify that the collection is gone - db.collectionNames("simple_rename_collection", function(err, names) { - test.equal(0, names.length); - - // Verify that the new collection exists - db.collectionNames("simple_rename_collection_2", function(err, names) { - test.equal(1, names.length); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example using lastError on a single connection with a pool of 1. - * - * @_class db - * @_function lastError - * @ignore - */ -exports.shouldCorrectlyUseLastError = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection("simple_rename_collection", {safe:true}, function(err, collection) { - test.equal(null, err); - - // Insert a document in the collection - collection.insert({a:1}, function(err, result) { - test.equal(null, err); - - // Execute lastError - db.lastError(function(err, result) { - test.equal(null, err); - test.equal(null, result[0].err); - - // Pick a specific connection and execute lastError against it - var connection = db.serverConfig.checkoutWriter(); - // Execute lastError - db.lastError({}, {connection:connection}, function(err, result) { - test.equal(null, err); - test.equal(null, result[0].err); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example using previousError to return the list of all errors, might be deprecated in the future. - * - * @_class db - * @_function previousErrors - * @ignore - */ -exports.shouldCorrectlyUsePreviousError = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection("simple_previous_error_coll", {safe:true}, function(err, collection) { - test.equal(null, err); - - // Force a unique index - collection.ensureIndex({a:1}, {unique:true}, function(err, result) { - test.equal(null, err); - - // Force some errors - collection.insert([{a:1}, {a:1}, {a:1}, {a:2}], function(err, result) { - - // Pick a specific connection and execute lastError against it - var connection = db.serverConfig.checkoutWriter(); - - // Execute previousErrors - db.previousErrors({connection:connection}, function(err, result) { - test.equal(null, err); - test.equal(1, result.length); - test.ok(result[0].err != null); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example using resetErrorHistory to clean up the history of errors. - * - * @_class db - * @_function resetErrorHistory - * @ignore - */ -exports.shouldCorrectlyUseResetErrorHistory = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection("simple_reset_error_history_coll", {safe:true}, function(err, collection) { - test.equal(null, err); - - // Force a unique index - collection.ensureIndex({a:1}, {unique:true}, function(err, result) { - test.equal(null, err); - - // Force some errors - collection.insert([{a:1}, {a:1}, {a:1}, {a:2}], function(err, result) { - // Pick a specific connection and execute lastError against it - var connection = db.serverConfig.checkoutWriter(); - - // Reset the error history - db.resetErrorHistory({connection:connection}, function(err, result) { - - // Execute previousErrors and validate that there are no errors left - db.previousErrors({connection:connection}, function(err, result) { - test.equal(null, err); - test.equal(1, result.length); - test.equal(null, result[0].err); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A more complex createIndex using a compound unique index in the background and dropping duplicated documents - * - * @_class db - * @_function createIndex - */ -exports.shouldCreateComplexIndexOnTwoFields = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_complex_index_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - db.createIndex('more_complex_index_test', {a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Show that duplicate records got dropped - collection.find({}).toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - - // Peform a query, with explain to show we hit the query - collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { - test.equal(null, err); - test.ok(explanation[0].indexBounds.a != null); - test.ok(explanation[0].indexBounds.b != null); - - db.close(); - test.done(); - }); - }) - }); - }); - }); - }); -} - -/** - * A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents. - * - * @_class db - * @_function ensureIndex - */ -exports.shouldCreateComplexEnsureIndex = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_complex_ensure_index_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - db.ensureIndex('more_complex_ensure_index_test', {a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Show that duplicate records got dropped - collection.find({}).toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - - // Peform a query, with explain to show we hit the query - collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { - test.equal(null, err); - test.ok(explanation[0].indexBounds.a != null); - test.ok(explanation[0].indexBounds.b != null); - - db.close(); - test.done(); - }); - }) - }); - }); - }); - }); -} - -/** - * A Simple example of returning current cursor information in MongoDB - * - * @_class db - * @_function cursorInfo - */ -exports.shouldCorrectlyReturnCursorInformation = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('cursor_information_collection', function(err, collection) { - test.equal(null, err); - - // Create a bunch of documents so we can force the creation of a cursor - var docs = []; - for(var i = 0; i < 1000; i++) { - docs.push({a:'hello world hello world hello world hello world hello world hello world hello world hello world'}); - } - - // Insert a bunch of documents for the index - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - // Let's set a cursor - var cursor = collection.find({}, {batchSize:10}); - cursor.nextObject(function(err, item) { - test.equal(null, err); - - // Let's grab the information about the cursors on the database - db.cursorInfo(function(err, cursorInformation) { - test.ok(cursorInformation.totalOpen > 0); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * An examples showing the creation and dropping of an index - * - * @_class db - * @_function dropIndex - */ -exports.shouldCorrectlyCreateAndDropIndex = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('create_and_drop_an_index', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Drop the index - db.dropIndex("create_and_drop_an_index", "a_1_b_1", function(err, result) { - test.equal(null, err); - - // Verify that the index is gone - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.equal(null, indexInformation.a_1_b_1); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An example showing how to force a reindex of a collection. - * - * @_class db - * @_function reIndex - */ -exports.shouldCorrectlyForceReindexOnCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('create_and_drop_all_indexes', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Force a reindex of the collection - db.reIndex('create_and_drop_all_indexes', function(err, result) { - test.equal(null, err); - test.equal(true, result); - - // Verify that the index is gone - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An example showing the information returned by indexInformation - * - * @_class db - * @_function indexInformation - */ -exports.shouldCorrectlyShowTheResultsFromIndexInformation = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_index_information_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Fetch basic indexInformation for collection - db.indexInformation('more_index_information_test', function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); - - // Fetch full index information - collection.indexInformation({full:true}, function(err, indexInformation) { - test.deepEqual({ _id: 1 }, indexInformation[0].key); - test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An examples showing the dropping of a database - * - * @_class db - * @_function dropDatabase - */ -exports.shouldCorrectlyShowTheResultsFromIndexInformation = function(test) { - var db = new Db('integration_tests_to_drop', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('more_index_information_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Let's drop the database - db.dropDatabase(function(err, result) { - test.equal(null, err); - - // Get the admin database - db.admin().listDatabases(function(err, dbs) { - // Grab the databases - dbs = dbs.databases; - // Did we find the db - var found = false; - - // Check if we have the db in the list - for(var i = 0; i < dbs.length; i++) { - if(dbs[i].name == 'integration_tests_to_drop') found = true; - } - - // We should not find the databases - test.equal(false, found); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/error_test.js b/node_modules/mongodb/test/error_test.js deleted file mode 100644 index 4e7c399..0000000 --- a/node_modules/mongodb/test/error_test.js +++ /dev/null @@ -1,311 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -// Test the error reporting functionality -exports.shouldCorrectlyRetrieveErrorMessagesFromServer = function(test) { - // Just run with one connection in the pool - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize:1, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Open the db - error_client.open(function(err, error_client) { - error_client.resetErrorHistory(function() { - error_client.error(function(err, documents) { - test.equal(true, documents[0].ok); - test.equal(0, documents[0].n); - - // Force error on server - error_client.executeDbCommand({forceerror: 1}, function(err, r) { - test.equal(0, r.documents[0].ok); - test.ok(r.documents[0].errmsg.length > 0); - // Check for previous errors - error_client.previousErrors(function(err, documents) { - test.equal(true, documents[0].ok); - test.equal(1, documents[0].nPrev); - test.equal("forced error", documents[0].err); - - // Check for the last error - error_client.error(function(err, documents) { - test.equal("forced error", documents[0].err); - // Force another error - error_client.collection('test_error_collection', function(err, collection) { - collection.findOne({name:"Fred"}, function(err, document) { - // Check that we have two previous errors - error_client.previousErrors(function(err, documents) { - test.equal(true, documents[0].ok); - test.equal(2, documents[0].nPrev); - test.equal("forced error", documents[0].err); - - error_client.resetErrorHistory(function() { - error_client.previousErrors(function(err, documents) { - test.equal(true, documents[0].ok); - test.equal(-1, documents[0].nPrev); - - error_client.error(function(err, documents) { - test.equal(true, documents[0].ok); - test.equal(0, documents[0].n); - - // Let's close the db - error_client.close(); - - error_client.error(function(err, documents) { - test.ok(err instanceof Error); - test.equal('no open connections', err.message); - test.done(); - }); - }); - }) - }); - }); - }); - }); - }) - }); - }); - }); - }); - }); -} - -// Test the last status functionality of the driver -exports.shouldCorrectlyExecuteLastStatus = function(test) { - // Just run with one connection in the pool - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize:1, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Open the db - error_client.open(function(err, client) { - client.createCollection('test_last_status', function(err, collection) { - test.ok(collection instanceof Collection); - test.equal('test_last_status', collection.collectionName); - - // Get the collection - client.collection('test_last_status', function(err, collection) { - // Remove all the elements of the collection - collection.remove(function(err, result) { - // Check update of a document - collection.insert({i:1}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]._id.toHexString().length == 24); - - // Update the record - collection.update({i:1}, {"$set":{i:2}}, function(err, result) { - // Check for the last message from the server - client.lastStatus(function(err, status) { - test.equal(true, status[0].ok); - test.equal(true, status[0].updatedExisting); - // Check for failed update of document - collection.update({i:1}, {"$set":{i:500}}, function(err, result) { - client.lastStatus(function(err, status) { - test.equal(true, status[0].ok); - test.equal(false, status[0].updatedExisting); - - // Check safe update of a document - collection.insert({x:1}, function(err, ids) { - collection.update({x:1}, {"$set":{x:2}}, {'safe':true}, function(err, document) { - }); - - collection.update({x:1}, {"$set":{x:2}}, {'safe':true}); - - collection.update({y:1}, {"$set":{y:2}}, {'safe':true}, function(err, result) { - test.equal(0, result); - - // Let's close the db - error_client.close(); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports.shouldFailInsertDueToUniqueIndex = function(test) { - client.createCollection('test_failing_insert_due_to_unique_index', function(err, r) { - client.collection('test_failing_insert_due_to_unique_index', function(err, collection) { - collection.ensureIndex([['a', 1 ]], true, function(err, indexName) { - collection.insert({a:2}, {safe: true}, function(err, r) { - test.ok(err == null); - collection.insert({a:2}, {safe: true}, function(err, r) { - test.ok(err != null); - test.done(); - }) - }) - }) - }) - }) -} - -// Test the error reporting functionality -exports.shouldFailInsertDueToUniqueIndexStrict = function(test) { - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - error_client.open(function(err, error_client) { - error_client.dropCollection('test_failing_insert_due_to_unique_index_strict', function(err, r) { - error_client.createCollection('test_failing_insert_due_to_unique_index_strict', function(err, r) { - error_client.collection('test_failing_insert_due_to_unique_index_strict', function(err, collection) { - collection.ensureIndex([['a', 1 ]], true, function(err, indexName) { - collection.insert({a:2}, {safe:true}, function(err, r) { - test.ok(err == null); - collection.insert({a:2}, {safe:true}, function(err, r) { - test.ok(err != null); - error_client.close(); - test.done(); - }) - }) - }) - }) - }) - }); - }); -} - -exports['safe mode should pass the disconnected error to the callback'] = function (test) { - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - var name = 'test_safe_mode_when_disconnected'; - error_client.open(function(err, error_client) { - test.ok(err == null); - error_client.resetErrorHistory(function() { - error_client.dropCollection(name, function() { - error_client.createCollection(name, function(err, collection) { - test.ok(err == null); - collection.insert({ inserted: true }, { safe: true }, function (err) { - test.ok(err == null); - error_client.close(); - - collection.insert({ works: true }, { safe: true }, function (err) { - test.ok(err instanceof Error); - test.equal('no open connections', err.message); - - collection.update({ inserted: true }, { inserted: true, x: 1 }, { safe: true }, function (err) { - test.ok(err instanceof Error); - test.equal('no open connections', err.message); - - collection.remove({ inserted: true }, { safe: true }, function (err) { - test.ok(err instanceof Error); - test.equal('no open connections', err.message); - - collection.findOne({ works: true }, function (err) { - test.ok(err instanceof Error); - test.equal('no open connections', err.message); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports.shouldHandleAssertionError = function(test) { - client.createCollection('test_handle_assertion_error', function(err, r) { - client.collection('test_handle_assertion_error', function(err, collection) { - collection.insert({a:{lat:50, lng:10}}, {safe: true}, function(err, docs) { - test.ok(err == null); - - var query = {a:{$within:{$box:[[1,-10],[80,120]]}}}; - - // We don't have a geospatial index at this point - collection.findOne(query, function(err, docs) { - test.ok(err instanceof Error); - - collection.ensureIndex([['a', '2d' ]], true, function(err, indexName) { - test.ok(err == null); - - collection.findOne(query, function(err, doc) { - test.ok(err == null); - - var invalidQuery = {a:{$within:{$box:[[-10,-180],[10,180]]}}}; - - client.admin().serverInfo(function(err, result){ - collection.findOne(invalidQuery, function(err, doc) { - if(parseInt((result.version.replace(/\./g, ''))) < 200) { - test.ok(err instanceof Error); - } else { - test.equal(null, err); - test.equal(null, doc); - } - - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/exception_handling_test.js b/node_modules/mongodb/test/exception_handling_test.js deleted file mode 100644 index b7424cc..0000000 --- a/node_modules/mongodb/test/exception_handling_test.js +++ /dev/null @@ -1,101 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlyHandleThrownError = function(test) { - client.createCollection('shouldCorrectlyHandleThrownError', function(err, r) { - try { - client.collection('shouldCorrectlyHandleThrownError', function(err, collection) { - debug(someUndefinedVariable); - }); - } catch (err) { - test.ok(err != null); - test.done(); - } - }); -} - -exports.shouldCorrectlyHandleThrownErrorInRename = function(test) { - // Catch unhandled exception - process.on("uncaughtException", function(err) { - // Remove listener - process.removeAllListeners("uncaughtException"); - test.done() - }) - - // Execute code - client.createCollection('shouldCorrectlyHandleThrownErrorInRename', function(err, r) { - client.collection('shouldCorrectlyHandleThrownError', function(err, collection) { - collection.rename("shouldCorrectlyHandleThrownErrorInRename2", function(err, result) { - debug(someUndefinedVariable); - }) - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/find_test.js b/node_modules/mongodb/test/find_test.js deleted file mode 100644 index b828c2e..0000000 --- a/node_modules/mongodb/test/find_test.js +++ /dev/null @@ -1,1647 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Step = require('../deps/step/lib/step'), - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Code = require('../lib/mongodb/bson/code').Code, - Long = require('../lib/mongodb/bson/long').Long, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var POOL_SIZE = 4; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * Test a simple find - * @ignore - */ -exports.shouldCorrectlyPerformSimpleFind = function(test) { - client.createCollection('test_find_simple', function(err, r) { - var collection = client.collection('test_find_simple', function(err, collection) { - var doc1 = null; - var doc2 = null; - - // Insert some test documents - collection.insert([{a:2}, {b:3}], {safe:true}, function(err, docs) { - doc1 = docs[0]; - doc2 = docs[1] - - // Ensure correct insertion testing via the cursor and the count function - collection.find(function(err, cursor) { - cursor.toArray(function(err, documents) { - test.equal(2, documents.length); - - collection.count(function(err, count) { - test.equal(2, count); - - // Fetch values by selection - collection.find({'a': doc1.a}, function(err, cursor) { - cursor.toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal(doc1.a, documents[0].a); - // Let's close the db - test.done(); - }); - }); - }); - }) - }); - }); - }); - }); -} - -/** - * Test a simple find chained - * @ignore - */ -exports.shouldCorrectlyPeformSimpleChainedFind = function(test) { - client.createCollection('test_find_simple_chained', function(err, r) { - var collection = client.collection('test_find_simple_chained', function(err, collection) { - var doc1 = null; - var doc2 = null; - - // Insert some test documents - collection.insert([{a:2}, {b:3}], {safe:true}, function(err, docs) { - doc1 = docs[0]; - doc2 = docs[1] - - // Ensure correct insertion testing via the cursor and the count function - collection.find().toArray(function(err, documents) { - test.equal(2, documents.length); - - collection.count(function(err, count) { - test.equal(2, count); - - // Fetch values by selection - collection.find({'a': doc1.a}).toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal(doc1.a, documents[0].a); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * Test advanced find - * @ignore - */ -exports.shouldCorrectlyPeformAdvancedFinds = function(test) { - client.createCollection('test_find_advanced', function(err, r) { - var collection = client.collection('test_find_advanced', function(err, collection) { - var doc1 = null, doc2 = null, doc3 = null; - - // Insert some test documents - collection.insert([{a:1}, {a:2}, {b:3}], {safe:true}, function(err, docs) { - var doc1 = docs[0], doc2 = docs[1], doc3 = docs[2]; - - // Locate by less than - collection.find({'a':{'$lt':10}}).toArray(function(err, documents) { - test.equal(2, documents.length); - // Check that the correct documents are returned - var results = []; - // Check that we have all the results we want - documents.forEach(function(doc) { - if(doc.a == 1 || doc.a == 2) results.push(1); - }); - test.equal(2, results.length); - }); - - // Locate by greater than - collection.find({'a':{'$gt':1}}).toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal(2, documents[0].a); - }); - - // Locate by less than or equal to - collection.find({'a':{'$lte':1}}).toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal(1, documents[0].a); - }); - - // Locate by greater than or equal to - collection.find({'a':{'$gte':1}}).toArray(function(err, documents) { - test.equal(2, documents.length); - // Check that the correct documents are returned - var results = []; - // Check that we have all the results we want - documents.forEach(function(doc) { - if(doc.a == 1 || doc.a == 2) results.push(1); - }); - test.equal(2, results.length); - }); - - // Locate by between - collection.find({'a':{'$gt':1, '$lt':3}}).toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal(2, documents[0].a); - }); - - // Locate in clause - collection.find({'a':{'$in':[1,2]}}).toArray(function(err, documents) { - test.equal(2, documents.length); - // Check that the correct documents are returned - var results = []; - // Check that we have all the results we want - documents.forEach(function(doc) { - if(doc.a == 1 || doc.a == 2) results.push(1); - }); - test.equal(2, results.length); - }); - - // Locate in _id clause - collection.find({'_id':{'$in':[doc1['_id'], doc2['_id']]}}).toArray(function(err, documents) { - test.equal(2, documents.length); - // Check that the correct documents are returned - var results = []; - // Check that we have all the results we want - documents.forEach(function(doc) { - if(doc.a == 1 || doc.a == 2) results.push(1); - }); - test.equal(2, results.length); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * Test sorting of results - * @ignore - */ -exports.shouldCorrectlyPerformFindWithSort = function(test) { - client.createCollection('test_find_sorting', function(err, r) { - client.collection('test_find_sorting', function(err, collection) { - var doc1 = null, doc2 = null, doc3 = null, doc4 = null; - // Insert some test documents - collection.insert([{a:1, b:2}, - {a:2, b:1}, - {a:3, b:2}, - {a:4, b:1} - ], {safe:true}, function(err, docs) { - doc1 = docs[0]; - doc2 = docs[1]; - doc3 = docs[2]; - doc4 = docs[3] - - // Test sorting (ascending) - collection.find({'a': {'$lt':10}}, {'sort': [['a', 1]]}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(1, documents[0].a); - test.equal(2, documents[1].a); - test.equal(3, documents[2].a); - test.equal(4, documents[3].a); - - // Test sorting (descending) - collection.find({'a': {'$lt':10}}, {'sort': [['a', -1]]}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(4, documents[0].a); - test.equal(3, documents[1].a); - test.equal(2, documents[2].a); - test.equal(1, documents[3].a); - - // Test sorting (descending), sort is hash - collection.find({'a': {'$lt':10}}, {sort: {a: -1}}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(4, documents[0].a); - test.equal(3, documents[1].a); - test.equal(2, documents[2].a); - test.equal(1, documents[3].a); - - // Sorting using array of names, assumes ascending order - collection.find({'a': {'$lt':10}}, {'sort': ['a']}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(1, documents[0].a); - test.equal(2, documents[1].a); - test.equal(3, documents[2].a); - test.equal(4, documents[3].a); - - // Sorting using single name, assumes ascending order - collection.find({'a': {'$lt':10}}, {'sort': 'a'}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(1, documents[0].a); - test.equal(2, documents[1].a); - test.equal(3, documents[2].a); - test.equal(4, documents[3].a); - - // Sorting using single name, assumes ascending order, sort is hash - collection.find({'a': {'$lt':10}}, {sort: {'a':1}}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(1, documents[0].a); - test.equal(2, documents[1].a); - test.equal(3, documents[2].a); - test.equal(4, documents[3].a); - - collection.find({'a': {'$lt':10}}, {'sort': ['b', 'a']}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(2, documents[0].a); - test.equal(4, documents[1].a); - test.equal(1, documents[2].a); - test.equal(3, documents[3].a); - - // Sorting using empty array, no order guarantee should not blow up - collection.find({'a': {'$lt':10}}, {'sort': []}).toArray(function(err, documents) { - test.equal(4, documents.length); - - /* NONACTUAL */ - // Sorting using ordered hash - collection.find({'a': {'$lt':10}}, {'sort': {a:-1}}).toArray(function(err, documents) { - // Fail test if not an error - test.equal(4, documents.length); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Test the limit function of the db - * @ignore - */ -exports.shouldCorrectlyPerformFindWithLimit = function(test) { - client.createCollection('test_find_limits', function(err, r) { - client.collection('test_find_limits', function(err, collection) { - var doc1 = null, doc2 = null, doc3 = null, doc4 = null; - - // Insert some test documents - collection.insert([{a:1}, - {b:2}, - {c:3}, - {d:4} - ], {safe:true}, function(err, docs) { - doc1 = docs[0]; - doc2 = docs[1]; - doc3 = docs[2]; - doc4 = docs[3] - - // Test limits - collection.find({}, {'limit': 1}).toArray(function(err, documents) { - test.equal(1, documents.length); - }); - - collection.find({}, {'limit': 2}).toArray(function(err, documents) { - test.equal(2, documents.length); - }); - - collection.find({}, {'limit': 3}).toArray(function(err, documents) { - test.equal(3, documents.length); - }); - - collection.find({}, {'limit': 4}).toArray(function(err, documents) { - test.equal(4, documents.length); - }); - - collection.find({}, {}).toArray(function(err, documents) { - test.equal(4, documents.length); - }); - - collection.find({}, {'limit':99}).toArray(function(err, documents) { - test.equal(4, documents.length); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * Test find by non-quoted values (issue #128) - * @ignore - */ -exports.shouldCorrectlyFindWithNonQuotedValues = function(test) { - client.createCollection('test_find_non_quoted_values', function(err, r) { - client.collection('test_find_non_quoted_values', function(err, collection) { - // insert test document - collection.insert([{ a: 19, b: 'teststring', c: 59920303 }, - { a: "19", b: 'teststring', c: 3984929 }], {safe:true} , function(err, r) { - - collection.find({ a: 19 }).toArray(function(err, documents) { - test.equal(1, documents.length); - test.done(); - }); - }); - }); - }); -} - -/** - * Test for querying embedded document using dot-notation (issue #126) - * @ignore - */ -exports.shouldCorrectlyFindEmbeddedDocument = function(test) { - client.createCollection('test_find_embedded_document', function(err, r) { - client.collection('test_find_embedded_document', function(err, collection) { - // insert test document - collection.insert([{ a: { id: 10, value: 'foo' }, b: 'bar', c: { id: 20, value: 'foobar' }}, - { a: { id: 11, value: 'foo' }, b: 'bar2', c: { id: 20, value: 'foobar' }}], {safe:true}, function(err, r) { - - // test using integer value - collection.find({ 'a.id': 10 }).toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal('bar', documents[0].b); - }); - - // test using string value - collection.find({ 'a.value': 'foo' }).toArray(function(err, documents) { - // should yield 2 documents - test.equal(2, documents.length); - test.equal('bar', documents[0].b); - test.equal('bar2', documents[1].b); - test.done(); - }); - }); - }); - }); -} - -/** - * Find no records - * @ignore - */ -exports.shouldCorrectlyFindNoRecords = function(test) { - client.createCollection('test_find_one_no_records', function(err, r) { - client.collection('test_find_one_no_records', function(err, collection) { - collection.find({'a':1}, {}).toArray(function(err, documents) { - test.equal(0, documents.length); - // Let's close the db - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformFindByWhere = function(test) { - client.createCollection('test_where', function(err, collection) { - test.ok(collection instanceof Collection); - collection.insert([{'a':1}, {'a':2}, {'a':3}], {safe:true}, function(err, ids) { - collection.count(function(err, count) { - test.equal(3, count); - - // Let's test usage of the $where statement - collection.find({'$where':new Code('this.a > 2')}).count(function(err, count) { - test.equal(1, count); - }); - - collection.find({'$where':new Code('this.a > i', {i:1})}).count(function(err, count) { - test.equal(2, count); - - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformFindsWithHintTurnedOn = function(test) { - client.createCollection('test_hint', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, ids) { - client.createIndex(collection.collectionName, "a", function(err, indexName) { - collection.find({'a':1}, {'hint':'a'}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - collection.find({'a':1}, {'hint':['a']}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - collection.find({'a':1}, {'hint':{'a':1}}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - // Modify hints - collection.hint = 'a'; - test.equal(1, collection.hint['a']); - collection.find({'a':1}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - collection.hint = ['a']; - test.equal(1, collection.hint['a']); - collection.find({'a':1}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - collection.hint = {'a':1}; - test.equal(1, collection.hint['a']); - collection.find({'a':1}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - collection.hint = null; - test.ok(collection.hint == null); - collection.find({'a':1}).toArray(function(err, items) { - test.equal(1, items.length); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformFindByObjectID = function(test) { - client.createCollection('test_find_by_oid', function(err, collection) { - collection.save({'hello':'mike'}, {safe:true}, function(err, docs) { - test.ok(docs._id instanceof ObjectID || Object.prototype.toString.call(docs._id) === '[object ObjectID]'); - - collection.findOne({'_id':docs._id}, function(err, doc) { - test.equal('mike', doc.hello); - - var id = doc._id.toString(); - collection.findOne({'_id':new ObjectID(id)}, function(err, doc) { - test.equal('mike', doc.hello); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReturnDocumentWithOriginalStructure= function(test) { - client.createCollection('test_find_by_oid_with_subdocs', function(err, collection) { - var c1 = { _id: new ObjectID, comments: [], title: 'number 1' }; - var c2 = { _id: new ObjectID, comments: [], title: 'number 2' }; - var doc = { - numbers: [] - , owners: [] - , comments: [c1, c2] - , _id: new ObjectID - }; - - collection.insert(doc, {safe:true}, function(err, docs) { - collection.findOne({'_id':doc._id}, {safe:true,fields: undefined}, function(err, doc) { - if (err) console.error('error', err); - test.equal(2, doc.comments.length); - test.equal('number 1', doc.comments[0].title); - test.equal('number 2', doc.comments[1].title); - - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyRetrieveSingleRecord = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - client.createCollection('test_should_correctly_retrieve_one_record', function(err, collection) { - collection.insert({'a':0}, {safe:true}, function(err, r) { - p_client.collection('test_should_correctly_retrieve_one_record', function(err, usercollection) { - usercollection.findOne({'a': 0}, function(err, result) { - p_client.close(); - - test.done(); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleError = function(test) { - client.createCollection('test_find_one_error_handling', function(err, collection) { - // Try to fetch an object using a totally invalid and wrong hex string... what we're interested in here - // is the error handling of the findOne Method - try { - collection.findOne({"_id":ObjectID.createFromHexString('5e9bd59248305adf18ebc15703a1')}, function(err, result) {}); - } catch (err) { - test.done(); - } - }); -} - -/** - * Test field select with options - * @ignore - */ -exports.shouldCorrectlyPerformFindWithOptions = function(test) { - client.createCollection('test_field_select_with_options', function(err, r) { - var collection = client.collection('test_field_select_with_options', function(err, collection) { - var docCount = 25, docs = []; - - // Insert some test documents - while(docCount--) docs.push({a:docCount, b:docCount}); - collection.insert(docs, {safe:true}, function(err,retDocs) { - docs = retDocs; - - collection.find({},{ 'a' : 1},{ limit : 3, sort : [['a',-1]] }).toArray(function(err,documents){ - test.equal(3,documents.length); - documents.forEach(function(doc,idx){ - test.equal(undefined,doc.b); // making sure field select works - test.equal((24-idx),doc.a); // checking limit sort object with field select - }); - }); - - collection.find({},{},10,3).toArray(function(err,documents){ - test.equal(3,documents.length); - documents.forEach(function(doc,idx){ - test.equal(doc.a,doc.b); // making sure empty field select returns properly - test.equal((14-idx),doc.a); // checking skip and limit in args - }); - - test.done(); - }); - }); - }); - }); -} - -/** - * Test findAndModify a document - * @ignore - */ -exports.shouldCorrectlyFindAndModifyDocument = function(test) { - client.createCollection('test_find_and_modify_a_document', function(err, collection) { - // Test return new document on change - collection.insert({'a':1, 'b':2}, {safe:true}, function(err, doc) { - // Let's modify the document in place - collection.findAndModify({'a':1}, [['a', 1]], {'$set':{'b':3}}, {'new':true}, function(err, updated_doc) { - test.equal(1, updated_doc.a); - test.equal(3, updated_doc.b); - - // Test return old document on change - collection.insert({'a':2, 'b':2}, {safe:true}, function(err, doc) { - // Let's modify the document in place - collection.findAndModify({'a':2}, [['a', 1]], {'$set':{'b':3}}, {safe:true}, function(err, result) { - test.equal(2, result.a); - test.equal(2, result.b); - - // Test remove object on change - collection.insert({'a':3, 'b':2}, {safe:true}, function(err, doc) { - // Let's modify the document in place - collection.findAndModify({'a':3}, [], {'$set':{'b':3}}, {'new': true, remove: true}, function(err, updated_doc) { - test.equal(3, updated_doc.a); - test.equal(2, updated_doc.b); - - // Let's upsert! - collection.findAndModify({'a':4}, [], {'$set':{'b':3}}, {'new': true, upsert: true}, function(err, updated_doc) { - test.equal(4, updated_doc.a); - test.equal(3, updated_doc.b); - - // Test selecting a subset of fields - collection.insert({a: 100, b: 101}, {safe:true}, function (err, ids) { - collection.findAndModify({'a': 100}, [], {'$set': {'b': 5}}, {'new': true, fields: {b: 1}}, function (err, updated_doc) { - test.equal(2, Object.keys(updated_doc).length); - test.equal(ids[0]['_id'].toHexString(), updated_doc._id.toHexString()); - test.equal(5, updated_doc.b); - test.equal("undefined", typeof updated_doc.a); - test.done(); - }); - }); - }); - }) - }); - }) - }); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteFindOneWithAnInSearchTag = function(test) { - client.createCollection('shouldCorrectlyExecuteFindOneWithAnInSearchTag', function(err, collection) { - // Test return new document on change - collection.insert({'tags':[]}, {safe:true}, function(err, docs) { - // Fetch the id - var id = docs[0]._id - - Step( - function findFirst() { - var self = this; - - collection.findOne({_id:id}, function(err, doc) { - test.equal(null, err) - test.ok(doc != null); - - // Perform atomic push operation - collection.update({_id:id}, {'$push':{comments:{title:'1'}}}, {safe:true}, self); - }) - }, - - function findSecond(err, result) { - var self = this; - test.equal(1, result); - test.equal(null, err); - - collection.findOne({_id:id}, function(err, doc) { - test.equal(null, err) - test.ok(doc != null); - test.deepEqual(1, doc.comments.length); - - // Perform atomic push operation - collection.update({_id:id}, {'$push':{comments:{title:'2'}}}, {safe:true}, self); - }) - }, - - function findThird(err, result) { - var self = this; - test.equal(1, result); - test.equal(null, err); - - collection.findOne({_id:id}, function(err, doc) { - test.equal(null, err) - test.ok(doc != null); - test.deepEqual(2, doc.comments.length); - - // Perform atomic push operation - collection.update({_id:id}, {'$push':{comments:{title:'3'}}}, {safe:true}, self); - }) - }, - - function findFourth(err, result) { - var self = this; - test.equal(1, result); - test.equal(null, err); - - collection.findOne({_id:id}, function(err, doc) { - test.equal(null, err) - test.ok(doc != null); - test.deepEqual(3, doc.comments.length); - // Perform atomic push operation - collection.update({_id:id}, {'$pushAll':{comments:[{title:'4'}, {title:'5'}]}}, {safe:true}, self); - }) - }, - - function findFourth(err, result) { - var self = this; - test.equal(1, result); - test.equal(null, err); - - collection.findOne({_id:id}, function(err, doc) { - test.equal(null, err) - test.ok(doc != null); - test.deepEqual(5, doc.comments.length); - test.done(); - }) - } - ) - }) - }); -} - -/** - * @ignore - */ -exports['ShouldCorrectlyLocatePostAndIncValues'] = function(test) { - client.createCollection('shouldCorrectlyExecuteFindOneWithAnInSearchTag', function(err, collection) { - // Test return new document on change - collection.insert({title:'Tobi', - author:'Brian', - newTitle:'Woot', meta:{visitors:0}}, {safe:true}, function(err, docs) { - // Fetch the id - var id = docs[0]._id - - collection.update({_id:id}, {$inc:{ 'meta.visitors': 1 }}, {safe:true}, function(err, result) { - test.equal(1, result); - test.equal(null, err); - - collection.findOne({_id:id}, function(err, item) { - test.equal(1, item.meta.visitors); - test.done() - }) - }); - }); - }); -} - -/** - * Test findAndModify a document - * @ignore - */ -exports['Should Correctly Handle FindAndModify Duplicate Key Error'] = function(test) { - client.createCollection('FindAndModifyDuplicateKeyError', function(err, collection) { - collection.ensureIndex(['name', 1], {unique:true}, function(err, index) { - // Test return new document on change - collection.insert([{name:'test1'}, {name:'test2'}], {safe:true}, function(err, doc) { - // Let's modify the document in place - collection.findAndModify({name: 'test1'}, [], {$set: {name: 'test2'}}, {}, function(err, updated_doc) { - test.equal(null, updated_doc); - test.ok(err != null); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly return null when attempting to modify a non-existing document'] = function(test) { - client.createCollection('AttemptToFindAndModifyNonExistingDocument', function(err, collection) { - // Let's modify the document in place - collection.findAndModify({name: 'test1'}, [], {$set: {name: 'test2'}}, {}, function(err, updated_doc) { - test.equal(null, updated_doc); - test.ok(err == null || err.errmsg.match("No matching object found")) - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly handle chained skip and limit on find with toArray'] = function(test) { - client.createCollection('skipAndLimitOnFindWithToArray', function(err, collection) { - collection.insert([{a:1}, {b:2}, {c:3}], {safe:true}, function(err, result) { - - collection.find().skip(1).limit(1).toArray(function(err, items) { - test.equal(null, err); - test.equal(1, items.length); - test.equal(2, items[0].b) - test.done(); - }) - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly pass timeout options to cursor'] = function(test) { - client.createCollection('timeoutFalse', function(err, collection) { - collection.find({},{timeout:false},function(err, cursor) { - test.equal(false, cursor.timeout); - }); - collection.find({},{timeout:true},function(err, cursor) { - test.equal(true, cursor.timeout); - }); - collection.find({},{},function(err, cursor) { - test.equal(true, cursor.timeout); - }); - - test.done(); - }); -} - -/** - * Test findAndModify a document with strict mode enabled - * @ignore - */ -exports.shouldCorrectlyFindAndModifyDocumentWithDBStrict = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - p_client.createCollection('shouldCorrectlyFindAndModifyDocumentWithDBStrict', function(err, collection) { - // Test return old document on change - collection.insert({'a':2, 'b':2}, {safe:true}, function(err, doc) { - // Let's modify the document in place - collection.findAndModify({'a':2}, [['a', 1]], {'$set':{'b':3}}, {new:true}, function(err, result) { - test.equal(2, result.a) - test.equal(3, result.b) - p_client.close(); - test.done(); - }) - }); - }); - }); -} - -/** - * Test findAndModify a document that fails in first step before safe - * @ignore - */ -exports.shouldCorrectlyFindAndModifyDocumentThatFailsInFirstStep = function(test) { - client.createCollection('shouldCorrectlyFindAndModifyDocumentThatFailsInFirstStep', function(err, collection) { - // Set up an index to force duplicate index erro - collection.ensureIndex([['failIndex', 1]], {unique:true}, function(err, index) { - // Setup a new document - collection.insert({'a':2, 'b':2, 'failIndex':1}, function(err, doc) { - - // Let's attempt to upsert with a duplicate key error - collection.findAndModify({'c':2}, [['a', 1]], {'a':10, 'b':10, 'failIndex':1}, {safe:true, upsert:true}, function(err, result) { - test.equal(null, result); - test.ok(err.errmsg.match("duplicate key error index")); - test.done(); - }) - }); - }); - }); -} - -/** - * Test findAndModify a document that fails in first step before safe - * @ignore - */ -exports.shouldCorrectlyFindAndModifyDocumentThatFailsInSecondStepWithNoMatchingDocuments = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - p_client.createCollection('shouldCorrectlyFindAndModifyDocumentThatFailsInSecondStepWithNoMatchingDocuments', function(err, collection) { - // Test return old document on change - collection.insert({'a':2, 'b':2}, function(err, doc) { - - // Let's modify the document in place - collection.findAndModify({'a':2}, [['a', 1]], {'$set':{'b':3}}, {safe:{w:200, wtimeout:1000}}, function(err, result) { - test.equal(null, result); - test.ok(err != null); - p_client.close(); - test.done(); - }) - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly return new modified document'] = function(test) { - client.createCollection('Should_correctly_return_new_modified_document', function(err, collection) { - var id = new ObjectID(); - var doc = {_id:id, a:1, b:1, c:{a:1, b:1}}; - - collection.insert(doc, {safe:true}, function(err, result) { - test.ok(err == null); - - // Find and modify returning the new object - collection.findAndModify({_id:id}, [], {$set : {'c.c': 100}}, {new:true}, function(err, item) { - test.equal(doc._id.toString(), item._id.toString()); - test.equal(doc.a, item.a); - test.equal(doc.b, item.b); - test.equal(doc.c.a, item.c.a); - test.equal(doc.c.b, item.c.b); - test.equal(100, item.c.c); - test.done(); - }) - }); - }); -} - -/** - * Should correctly execute findAndModify that is breaking in prod - * @ignore - */ -exports.shouldCorrectlyExecuteFindAndModify = function(test) { - client.createCollection('shouldCorrectlyExecuteFindAndModify', function(err, collection) { - var self = {_id : new ObjectID()} - var _uuid = 'sddffdss' - - collection.findAndModify( - {_id: self._id, 'plays.uuid': _uuid}, - [], - {$set : {'plays.$.active': true}}, - {new: true, fields: {plays: 0, results: 0}, safe: true}, - function(err, contest) { - test.done(); - }) - }); -} - -/** - * @ignore - */ -exports['Should correctly return record with 64-bit id'] = function(test) { - client.createCollection('should_correctly_return_record_with_64bit_id', function(err, collection) { - var _lowerId = new ObjectID(); - var _higherId = new ObjectID(); - var lowerId = new Long.fromString('133118461172916224', 10); - var higherId = new Long.fromString('133118461172916225', 10); - - var lowerDoc = {_id:_lowerId, id: lowerId}; - var higherDoc = {_id:_higherId, id: higherId}; - - collection.insert([lowerDoc, higherDoc], {safe:true}, function(err, result) { - test.ok(err == null); - - // Select record with id of 133118461172916225 using $gt directive - collection.find({id: {$gt: lowerId}}, {}, function(err, cur) { - test.ok(err == null); - - cur.toArray(function(err, arr) { - test.ok(err == null); - test.equal(arr.length, 1, 'Selecting record via $gt directive on 64-bit integer should return a record with higher Id') - test.equal(arr[0].id.toString(), '133118461172916225', 'Returned Id should be equal to 133118461172916225') - test.done() - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly find a Document using findOne excluding _id field'] = function(test) { - client.createCollection('Should_Correctly_find_a_Document_using_findOne_excluding__id_field', function(err, collection) { - var doc = {_id : new ObjectID(), a:1, c:2} - // insert doc - collection.insert(doc, {safe:true}, function(err, result) { - // Get one document, excluding the _id field - collection.findOne({a:1}, {fields:{'_id': 0}}, function(err, item) { - test.equal(null, item._id); - test.equal(1, item.a); - test.equal(2, item.c); - - collection.find({a:1}, {fields:{'_id':0}}).toArray(function(err, items) { - var item = items[0] - test.equal(null, item._id); - test.equal(1, item.a); - test.equal(2, item.c); - test.done(); - }) - }) - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly execute find and findOne queries in the same way'] = function(test) { - client.createCollection('Should_correctly_execute_find_and_findOne_queries_in_the_same_way', function(err, collection) { - var doc = {_id : new ObjectID(), a:1, c:2, comments:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}; - // insert doc - collection.insert(doc, {safe:true}, function(err, result) { - - collection.find({_id: doc._id}, {comments: {$slice: -5}}).toArray(function(err, docs) { - test.equal(5, docs[0].comments.length) - - collection.findOne({_id: doc._id}, {comments: {$slice: -5}}, function(err, item) { - test.equal(5, item.comments.length) - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly execute find and findOne queries with selector set to null'] = function(test) { - client.createCollection('Should_correctly_execute_find_and_findOne_queries_in_the_same_way', function(err, collection) { - var doc = {_id : new ObjectID(), a:1, c:2, comments:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}; - // insert doc - collection.insert(doc, {safe:true}, function(err, result) { - - collection.find(null, {comments: {$slice: -5}}).toArray(function(err, docs) { - test.equal(5, docs[0].comments.length) - - collection.findOne(null, {comments: {$slice: -5}}, function(err, item) { - test.equal(5, item.comments.length) - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandlerErrorForFindAndModifyWhenNoRecordExists = function(test) { - client.createCollection('shouldCorrectlyHandlerErrorForFindAndModifyWhenNoRecordExists', function(err, collection) { - collection.findAndModify({'a':1}, [], {'$set':{'b':3}}, {'new': true}, function(err, updated_doc) { - test.equal(null, err); - test.equal(null, updated_doc); - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteFindAndModifyShouldGenerateCorrectBSON = function(test) { - var transaction = {}; - transaction.document = {}; - transaction.document.type = "documentType"; - transaction.document.id = new ObjectID(); - transaction.transactionId = new ObjectID(); - transaction.amount = 12.3333 - - var transactions = []; - transactions.push(transaction); - // Wrapping object - var wrapingObject = { - funds : { - remaining : 100.5 - }, - - transactions:transactions - } - - client.createCollection('shouldCorrectlyExecuteFindAndModify', function(err, collection) { - collection.insert(wrapingObject, {safe:true}, function(err, doc) { - test.equal(null, err); - - collection.findOne({_id:doc[0]._id, 'funds.remaining': {$gte: 3.0}, 'transactions.id': {$ne: transaction.transactionId}}, function(err, item) { - test.ok(item != null) - - collection.findAndModify({_id:doc[0]._id, 'funds.remaining': {$gte: 3.0}, 'transactions.id': {$ne: transaction.transactionId}}, [], {$push: {transactions: transaction}}, {new: true, safe: true}, function(err, result) { - test.done(); - }); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteMultipleFindsInParallel = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:10, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - p_client.createCollection('tasks', function(err, collection) { - var numberOfOperations = 0; - - // Test return old document on change - collection.insert({'a':2, 'b':2}, {safe:true}, function(err, doc) { - collection.find({"user_id":"4e9fc8d55883d90100000003","lc_status":{"$ne":"deleted"},"owner_rating":{"$exists":false}}, - {"skip":0,"limit":10,"sort":{"updated":-1}}, function(err, cursor) { - cursor.count(function(err, count) { - numberOfOperations = numberOfOperations + 1; - if(numberOfOperations == 2) { - test.done(); - p_client.close(); - } - }) - }); - - collection.find({"user_id":"4e9fc8d55883d90100000003","lc_status":{"$ne":"deleted"},"owner_rating":{"$exists":false}}, - {"skip":0,"limit":10,"sort":{"updated":-1}}, function(err, cursor) { - cursor.count(function(err, count) { - numberOfOperations = numberOfOperations + 1; - if(numberOfOperations == 2) { - test.done(); - p_client.close(); - } - }) - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReturnErrorFromMongodbOnFindAndModifyForcedError = function(test) { - client.createCollection('shouldCorrectlyReturnErrorFromMongodbOnFindAndModifyForcedError', function(err, collection) { - var q = { x: 1 }; - var set = { y:2, _id: new ObjectID() }; - var opts = { new: true, upsert: true }; - // Original doc - var doc = {_id: new ObjectID(), x:1}; - - // Insert original doc - collection.insert(doc, {safe:true}, function(err, result) { - collection.findAndModify(q, [], set, opts, function (err, res) { - test.ok(err != null); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteFindAndModifyUnderConcurrentLoad = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:10, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - var running = true; - - p_client.open(function(err, p_client) { - // Create a collection - p_client.collection("collection1", function(err, collection) { - // Wait a bit and then execute something that will throw a duplicate error - setTimeout(function() { - var id = new ObjectID(); - - collection.insert({_id:id, a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - collection.insert({_id:id, a:1}, {safe:true}, function(err, result) { - running = false; - test.done(); - p_client.close(); - }); - }); - }, 200); - }); - - p_client.collection("collection2", function(err, collection) { - // Keep hammering in inserts - var insert = function() { - process.nextTick(function() { - collection.insert({a:1}); - if(running) process.nextTick(insert); - }); - } - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyIterateOverCollection = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:1, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - var numberOfSteps = 0; - - // Open db connection - p_client.open(function(err, p_client) { - // Create a collection - p_client.createCollection('shouldCorrectlyIterateOverCollection', function(err, collection) { - for(var i = 0; i < 1000; i++) { - collection.insert({a:1, b:2, c:{d:3, f:'sfdsffffffffffffffffffffffffffffff'}}); - } - - collection.find({}, {}, function(err,cursor) { - cursor.count(function(err,count) { - cursor.each(function(err, obj) { - if (obj == null) { - p_client.close(); - test.equal(1000, numberOfSteps); - test.done(); - } else { - numberOfSteps = numberOfSteps + 1; - } - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyErrorOutFindAndModifyOnDuplicateRecord = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - p_client.createCollection('shouldCorrectlyErrorOutFindAndModifyOnDuplicateRecord', function(err, collection) { - // Test return old document on change - collection.insert([{'login':'user1'}, {'login':'user2'}], {safe:true}, function(err, docs) { - var id = docs[1]._id; - // Set an index - collection.ensureIndex('login', {unique:true}, function(err, result) { - // Attemp to modify document - collection.findAndModify({_id: id}, [], { $set: {login: 'user1'} }, {}, function(err, user){ - test.ok(err != null); - p_client.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * An example of using find with a very large in parameter - * - * @ignore - */ -exports.shouldPerformSimpleFindInArray = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_find_in_array', function(err, collection) { - test.equal(null, err); - - var docs = []; - for(var i = 0; i < 100; i++) docs.push({a:i}); - - // Insert some test documentations - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - // Find all the variables in a specific array - var inArray = []; - for(var i = 0; i < 100; i++) docs.push(i); - - // Fin all in - collection.find({a:{$in:docs}}).toArray(function(err, items) { - test.equal(null, err); - test.equal(100, items.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - - -/** - * A whole set of different ways to use the findAndModify command. - * - * The first findAndModify command modifies a document and returns the modified document back. - * The second findAndModify command removes the document. - * The second findAndModify command upserts a document and returns the new document. - * @_class collection - * @_function findAndModify - */ -exports.shouldPerformSimpleFindAndModifyOperations = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_find_and_modify_operations_', function(err, collection) { - test.equal(null, err); - - // Insert some test documentations - collection.insert([{a:1}, {b:1}, {c:1}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Simple findAndModify command returning the new document - collection.findAndModify({a:1}, [['a', 1]], {$set:{b1:1}}, {new:true}, function(err, doc) { - test.equal(null, err); - test.equal(1, doc.a); - test.equal(1, doc.b1); - - // Simple findAndModify command returning the new document and - // removing it at the same time - collection.findAndModify({b:1}, [['b', 1]], - {$set:{b:2}}, {remove:true}, function(err, doc) { - - // Verify that the document is gone - collection.findOne({b:1}, function(err, item) { - test.equal(null, err); - test.equal(null, item); - - // Simple findAndModify command performing an upsert and returning the new document - // executing the command safely - collection.findAndModify({d:1}, [['b', 1]], - {d:1, f:1}, {new:true, upsert:true, safe:true}, function(err, doc) { - test.equal(null, err); - test.equal(1, doc.d); - test.equal(1, doc.f); - - db.close(); - test.done(); - }) - }); - }); - }); - }); - }); - }); -} - -/** - * An example of using findAndRemove - * - * @_class collection - * @_function findAndRemove - */ -exports.shouldPerformSimpleFindAndModifyOperations = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_find_and_modify_operations_', function(err, collection) { - test.equal(null, err); - - // Insert some test documentations - collection.insert([{a:1}, {b:1}, {c:1}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Simple findAndModify command returning the new document and - // removing it at the same time - collection.findAndRemove({b:1}, [['b', 1]], function(err, doc) { - test.equal(null, err); - test.equal(1, doc.b); - - // Verify that the document is gone - collection.findOne({b:1}, function(err, item) { - test.equal(null, err); - test.equal(null, item); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple query using the find method on the collection. - * - * @_class collection - * @_function find - */ -exports.shouldPeformASimpleQuery = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_query', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.find().toArray(function(err, docs) { - test.equal(null, err); - test.equal(3, docs.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple query showing the explain for a query - * - * @_class collection - * @_function find - */ -exports.shouldPeformASimpleExplainQuery = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_explain_query', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.find({}, {explain:true}).toArray(function(err, docs) { - test.equal(null, err); - test.equal(1, docs.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple query showing skip and limit - * - * @_class collection - * @_function find - */ -exports.shouldPeformASimpleLimitSkipQuery = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_limit_skip_query', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.find({}, {skip:1, limit:1, fields:{b:1}}).toArray(function(err, docs) { - test.equal(null, err); - test.equal(1, docs.length); - test.equal(null, docs[0].a); - test.equal(2, docs[0].b); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple query using findOne - * - * @_class collection - * @_function findOne - */ -exports.shouldPeformASimpleLimitSkipFindOneQuery = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_limit_skip_find_one_query', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.findOne({a:2}, {fields:{b:1}}, function(err, doc) { - test.equal(null, err); - test.equal(null, doc.a); - test.equal(2, doc.b); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple query using find and fields - */ -exports.shouldPeformASimpleLimitSkipFindWithFields = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_find_with_fields', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.find({a:2}, ['b']).toArray(function(err, docs) { - test.equal(null, err); - test.equal(1, docs.length); - test.equal(null, docs[0].a); - test.equal(2, docs[0].b); - - // Peform a simple find and return all the documents - collection.find({a:2}, {b:1}).toArray(function(err, docs) { - test.equal(null, err); - test.equal(1, docs.length); - test.equal(null, docs[0].a); - test.equal(2, docs[0].b); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple query using find and fields - */ -exports.shouldPeformASimpleLimitSkipFindWithFields2 = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_find_with_fields_2', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.find({a:2}, {fields: ['b']}).toArray(function(err, docs) { - test.equal(null, err); - test.equal(1, docs.length); - test.equal(null, docs[0].a); - test.equal(2, docs[0].b); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/geo_search_test.js b/node_modules/mongodb/test/geo_search_test.js deleted file mode 100644 index e27979c..0000000 --- a/node_modules/mongodb/test/geo_search_test.js +++ /dev/null @@ -1,146 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Long = require('../lib/mongodb/bson/long').Long, - Step = require("../deps/step/lib/step"), - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * Example of a simple geoNear query across some documents - * - * @_class collection - * @_function geoNear - * @ignore - */ -exports.shouldCorrectlyPerformSimpleGeoNearCommand = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch the collection - db.collection("simple_geo_near_command", function(err, collection) { - - // Add a location based index - collection.ensureIndex({loc:"2d"}, function(err, result) { - - // Save a new location tagged document - collection.insert([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {safe:true}, function(err, result) { - - // Use geoNear command to find document - collection.geoNear(50, 50, {query:{a:1}, num:1}, function(err, docs) { - test.equal(1, docs.results.length); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Example of a simple geoHaystackSearch query across some documents - * - * @_class collection - * @_function geoHaystackSearch - * @ignore - */ -exports.shouldCorrectlyPerformSimpleGeoHaystackSearchCommand = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch the collection - db.collection("simple_geo_haystack_command", function(err, collection) { - - // Add a location based index - collection.ensureIndex({loc: "geoHaystack", type: 1}, {bucketSize: 1}, function(err, result) { - - // Save a new location tagged document - collection.insert([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {safe:true}, function(err, result) { - - // Use geoNear command to find document - collection.geoHaystackSearch(50, 50, {search:{a:1}, limit:1, maxDistance:100}, function(err, docs) { - test.equal(1, docs.results.length); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/gridstore/grid_store_file_test.js b/node_modules/mongodb/test/gridstore/grid_store_file_test.js deleted file mode 100644 index a715fb6..0000000 --- a/node_modules/mongodb/test/gridstore/grid_store_file_test.js +++ /dev/null @@ -1,947 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - ObjectID = require('../../lib/mongodb/bson/objectid').ObjectID, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - GridStore = mongodb.GridStore, - Chunk = mongodb.Chunk, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyFailDueToMissingChunks = function(test) { - var FILE = "empty.test.file"; - client.collection('fs.files', function(err, collection) { - collection.insert({filename: FILE, - "contentType" : "application/json; charset=UTF-8", - "length" : 91, - "chunkSize" : 262144, - "aliases" : null, - "metadata" : {}, - "md5" : "4e638392b289870da9291a242e474930"}, - {safe:true}, function(err, result) { - new mongodb.GridStore(client, FILE, "r").open(function (err, gs) { - gs.read(function(err, data) { - test.ok(err != null); - gs.close(function (){}); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteASmallPayload = function(test) { - var gridStore = new GridStore(client, "test_gs_small_write", "w"); - gridStore.open(function(err, gridStore) { - - gridStore.write("hello world!", function(err, gridStore) { - - gridStore.close(function(err, result) { - - client.collection('fs.files', function(err, collection) { - - collection.find({'filename':'test_gs_small_write'}, function(err, cursor) { - - cursor.toArray(function(err, items) { - test.equal(1, items.length); - var item = items[0]; - test.ok(item._id instanceof ObjectID || Object.prototype.toString.call(item._id) === '[object ObjectID]'); - - client.collection('fs.chunks', function(err, collection) { - var id = ObjectID.createFromHexString(item._id.toHexString()); - - collection.find({'files_id':id}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(1, items.length); - test.done(); - }) - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteSmallFileUsingABuffer = function(test) { - var gridStore = new GridStore(client, "test_gs_small_write_with_buffer", "w"); - gridStore.open(function(err, gridStore) { - var data = new Buffer("hello world", "utf8"); - - gridStore.write(data, function(err, gridStore) { - gridStore.close(function(err, result) { - client.collection('fs.files', function(err, collection) { - collection.find({'filename':'test_gs_small_write_with_buffer'}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(1, items.length); - var item = items[0]; - test.ok(item._id instanceof ObjectID || Object.prototype.toString.call(item._id) === '[object ObjectID]'); - - client.collection('fs.chunks', function(err, collection) { - collection.find({'files_id':item._id}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(1, items.length); - test.done(); - }) - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldSaveSmallFileToGridStore = function(test) { - var gridStore = new GridStore(client, "test_gs_small_file", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - client.collection('fs.files', function(err, collection) { - - collection.find({'filename':'test_gs_small_file'}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(1, items.length); - - // Read test of the file - GridStore.read(client, 'test_gs_small_file', function(err, data) { - test.equal('hello world!', data); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyOverwriteFile = function(test) { - var gridStore = new GridStore(client, "test_gs_overwrite", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - var gridStore2 = new GridStore(client, "test_gs_overwrite", "w"); - gridStore2.open(function(err, gridStore) { - gridStore2.write("overwrite", function(err, gridStore) { - gridStore2.close(function(err, result) { - - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_overwrite', function(err, data) { - test.equal('overwrite', data); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the seek method. - * - * @_class gridstore - * @_function seek - * @ignore - */ -exports.shouldCorrectlySeekWithBuffer = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a file and open it - var gridStore = new GridStore(db, "test_gs_seek_with_buffer", "w"); - gridStore.open(function(err, gridStore) { - // Write some content to the file - gridStore.write(new Buffer("hello, world!", "utf8"), function(err, gridStore) { - // Flush the file to GridFS - gridStore.close(function(result) { - - // Open the file in read mode - var gridStore2 = new GridStore(db, "test_gs_seek_with_buffer", "r"); - gridStore2.open(function(err, gridStore) { - // Seek to start - gridStore.seek(0, function(err, gridStore) { - // Read first character and verify - gridStore.getc(function(err, chr) { - test.equal('h', chr); - }); - }); - }); - - // Open the file in read mode - var gridStore3 = new GridStore(db, "test_gs_seek_with_buffer", "r"); - gridStore3.open(function(err, gridStore) { - // Seek to 7 characters from the beginning off the file and verify - gridStore.seek(7, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - }); - }); - }); - - // Open the file in read mode - var gridStore5 = new GridStore(db, "test_gs_seek_with_buffer", "r"); - gridStore5.open(function(err, gridStore) { - // Seek to -1 characters from the end off the file and verify - gridStore.seek(-1, GridStore.IO_SEEK_END, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('!', chr); - }); - }); - }); - - // Open the file in read mode - var gridStore6 = new GridStore(db, "test_gs_seek_with_buffer", "r"); - gridStore6.open(function(err, gridStore) { - // Seek to -6 characters from the end off the file and verify - gridStore.seek(-6, GridStore.IO_SEEK_END, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - }); - }); - }); - - // Open the file in read mode - var gridStore7 = new GridStore(db, "test_gs_seek_with_buffer", "r"); - gridStore7.open(function(err, gridStore) { - - // Seek forward 7 characters from the current read position and verify - gridStore.seek(7, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - - // Seek forward -1 characters from the current read position and verify - gridStore.seek(-1, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - - // Seek forward -4 characters from the current read position and verify - gridStore.seek(-4, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('o', chr); - - // Seek forward 3 characters from the current read position and verify - gridStore.seek(3, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('o', chr); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySeekWithString = function(test) { - var gridStore = new GridStore(client, "test_gs_seek", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(result) { - var gridStore2 = new GridStore(client, "test_gs_seek", "r"); - gridStore2.open(function(err, gridStore) { - gridStore.seek(0, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('h', chr); - }); - }); - }); - - var gridStore3 = new GridStore(client, "test_gs_seek", "r"); - gridStore3.open(function(err, gridStore) { - gridStore.seek(7, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - }); - }); - }); - - var gridStore4 = new GridStore(client, "test_gs_seek", "r"); - gridStore4.open(function(err, gridStore) { - gridStore.seek(4, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('o', chr); - }); - }); - }); - - var gridStore5 = new GridStore(client, "test_gs_seek", "r"); - gridStore5.open(function(err, gridStore) { - gridStore.seek(-1, GridStore.IO_SEEK_END, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('!', chr); - }); - }); - }); - - var gridStore6 = new GridStore(client, "test_gs_seek", "r"); - gridStore6.open(function(err, gridStore) { - gridStore.seek(-6, GridStore.IO_SEEK_END, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - }); - }); - }); - - var gridStore7 = new GridStore(client, "test_gs_seek", "r"); - gridStore7.open(function(err, gridStore) { - gridStore.seek(7, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - - gridStore.seek(-1, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - - gridStore.seek(-4, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('o', chr); - - gridStore.seek(3, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('o', chr); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyAppendToFile = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - var gridStore = new GridStore(fs_client, "test_gs_append", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(fs_client, "test_gs_append", "w+"); - gridStore2.open(function(err, gridStore) { - gridStore.write(" how are you?", function(err, gridStore) { - gridStore.close(function(err, result) { - - fs_client.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - - GridStore.read(fs_client, 'test_gs_append', function(err, data) { - test.equal("hello, world! how are you?", data); - - fs_client.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing how to rewind and overwrite the file. - * - * @_class gridstore - * @_function rewind - * @ignore - */ -exports.shouldCorrectlyRewingAndTruncateOnWrite = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Create a new file - var gridStore = new GridStore(db, fileId, "w"); - // Open the file - gridStore.open(function(err, gridStore) { - // Write to the file - gridStore.write("hello, world!", function(err, gridStore) { - // Flush the file to disk - gridStore.close(function(err, result) { - - // Reopen the file - gridStore = new GridStore(db, fileId, "w"); - gridStore.open(function(err, gridStore) { - // Write some more text to the file - gridStore.write('some text is inserted here', function(err, gridStore) { - - // Let's rewind to truncate the file - gridStore.rewind(function(err, gridStore) { - - // Write something from the start - gridStore.write('abc', function(err, gridStore) { - - // Flush the data to mongodb - gridStore.close(function(err, result) { - - // Verify that the new data was written - GridStore.read(db, fileId, function(err, data) { - test.equal("abc", data); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveEmptyFile = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - var gridStore = new GridStore(fs_client, "test_gs_save_empty_file", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("", function(err, gridStore) { - gridStore.close(function(err, result) { - fs_client.collection('fs.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - }); - }); - - fs_client.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - - fs_client.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the eof method. - * - * @_class gridstore - * @_function eof - * @ignore - */ -exports.shouldCorrectlyDetectEOF = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Open the file in write mode - var gridStore = new GridStore(db, 'test_gs_empty_file_eof', "w"); - gridStore.open(function(err, gridStore) { - // Flush the empty file to GridFS - gridStore.close(function(err, gridStore) { - - // Open the file in read mode - var gridStore2 = new GridStore(db, 'test_gs_empty_file_eof', "r"); - gridStore2.open(function(err, gridStore) { - // Verify that we are at the end of the file - test.equal(true, gridStore.eof()); - - db.close(); - test.done(); - }) - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldEnsureThatChunkSizeCannotBeChangedDuringRead = function(test) { - var gridStore = new GridStore(client, "test_gs_cannot_change_chunk_size_on_read", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(client, "test_gs_cannot_change_chunk_size_on_read", "r"); - gridStore2.open(function(err, gridStore) { - gridStore.chunkSize = 42; - test.equal(Chunk.DEFAULT_CHUNK_SIZE, gridStore.chunkSize); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldEnsureChunkSizeCannotChangeAfterDataHasBeenWritten = function(test) { - var gridStore = new GridStore(client, "test_gs_cannot_change_chunk_size_after_data_written", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.chunkSize = 42; - test.equal(Chunk.DEFAULT_CHUNK_SIZE, gridStore.chunkSize); - test.done(); - }); - }); -} - -/** - * checks if 8 bit values will be preserved in gridstore - * - * @ignore - */ -exports.shouldCorrectlyStore8bitValues = function(test) { - var gridStore = new GridStore(client, "test_gs_check_high_bits", "w"); - var data = new Buffer(255); - for(var i=0; i<255; i++){ - data[i] = i; - } - - gridStore.open(function(err, gridStore) { - gridStore.write(data, function(err, gridStore) { - gridStore.close(function(err, result) { - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_check_high_bits', function(err, fileData) { - // change testvalue into a string like "0,1,2,...,255" - test.equal(Array.prototype.join.call(data), - Array.prototype.join.call(new Buffer(fileData, "binary"))); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldAllowChangingChunkSize = function(test) { - var gridStore = new GridStore(client, "test_change_chunk_size", "w"); - gridStore.open(function(err, gridStore) { - gridStore.chunkSize = 42 - - gridStore.write('foo', function(err, gridStore) { - gridStore.close(function(err, result) { - var gridStore2 = new GridStore(client, "test_change_chunk_size", "r"); - gridStore2.open(function(err, gridStore) { - test.equal(42, gridStore.chunkSize); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldAllowChangingChunkSizeAtCreationOfGridStore = function(test) { - var gridStore = new GridStore(client, "test_change_chunk_size", "w", {'chunk_size':42}); - gridStore.open(function(err, gridStore) { - gridStore.write('foo', function(err, gridStore) { - gridStore.close(function(err, result) { - var gridStore2 = new GridStore(client, "test_change_chunk_size", "r"); - gridStore2.open(function(err, gridStore) { - test.equal(42, gridStore.chunkSize); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCalculateMD5 = function(test) { - var gridStore = new GridStore(client, "new-file", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(err, result) { - var gridStore2 = new GridStore(client, "new-file", "r"); - gridStore2.open(function(err, gridStore) { - test.equal("6f5902ac237024bdd0c176cb93063dc4", gridStore.md5); - gridStore.md5 = "can't do this"; - test.equal("6f5902ac237024bdd0c176cb93063dc4", gridStore.md5); - - var gridStore2 = new GridStore(client, "new-file", "w"); - gridStore2.open(function(err, gridStore) { - gridStore.close(function(err, result) { - var gridStore3 = new GridStore(client, "new-file", "r"); - gridStore3.open(function(err, gridStore) { - test.equal("d41d8cd98f00b204e9800998ecf8427e", gridStore.md5); - test.done(); - }); - }) - }) - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyUpdateUploadDate = function(test) { - var now = new Date(); - var originalFileUploadDate = null; - - var gridStore = new GridStore(client, "test_gs_upload_date", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(client, "test_gs_upload_date", "r"); - gridStore2.open(function(err, gridStore) { - test.ok(gridStore.uploadDate != null); - originalFileUploadDate = gridStore.uploadDate; - - gridStore2.close(function(err, result) { - var gridStore3 = new GridStore(client, "test_gs_upload_date", "w"); - gridStore3.open(function(err, gridStore) { - gridStore3.write('new data', function(err, gridStore) { - gridStore3.close(function(err, result) { - var fileUploadDate = null; - - var gridStore4 = new GridStore(client, "test_gs_upload_date", "r"); - gridStore4.open(function(err, gridStore) { - test.equal(originalFileUploadDate.getTime(), gridStore.uploadDate.getTime()); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveContentType = function(test) { - var ct = null; - - var gridStore = new GridStore(client, "test_gs_content_type", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(client, "test_gs_content_type", "r"); - gridStore2.open(function(err, gridStore) { - ct = gridStore.contentType; - test.equal(GridStore.DEFAULT_CONTENT_TYPE, ct); - - var gridStore3 = new GridStore(client, "test_gs_content_type", "w+"); - gridStore3.open(function(err, gridStore) { - gridStore.contentType = "text/html"; - gridStore.close(function(err, result) { - var gridStore4 = new GridStore(client, "test_gs_content_type", "r"); - gridStore4.open(function(err, gridStore) { - test.equal("text/html", gridStore.contentType); - test.done(); - }); - }) - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveContentTypeWhenPassedInAtGridStoreCreation = function(test) { - var gridStore = new GridStore(client, "test_gs_content_type_option", "w", {'content_type':'image/jpg'}); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(result) { - - var gridStore2 = new GridStore(client, "test_gs_content_type_option", "r"); - gridStore2.open(function(err, gridStore) { - test.equal('image/jpg', gridStore.contentType); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReportIllegalMode = function(test) { - var gridStore = new GridStore(client, "test_gs_unknown_mode", "x"); - gridStore.open(function(err, gridStore) { - test.ok(err instanceof Error); - test.equal("Illegal mode x", err.message); - test.done(); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveAndRetrieveFileMetadata = function(test) { - var gridStore = new GridStore(client, "test_gs_metadata", "w", {'content_type':'image/jpg'}); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(client, "test_gs_metadata", "r"); - gridStore2.open(function(err, gridStore) { - test.equal(null, gridStore.metadata); - - var gridStore3 = new GridStore(client, "test_gs_metadata", "w+"); - gridStore3.open(function(err, gridStore) { - gridStore.metadata = {'a':1}; - gridStore.close(function(err, result) { - - var gridStore4 = new GridStore(client, "test_gs_metadata", "r"); - gridStore4.open(function(err, gridStore) { - test.equal(1, gridStore.metadata.a); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldNotThrowErrorOnClose = function(test) { - var gridStore = new GridStore(client, "test_gs_metadata", "w", {'content_type':'image/jpg'}); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(client, "test_gs_metadata", "r"); - gridStore2.open(function(err, gridStore) { - gridStore.close(function(err, fo) { - test.ok(err == null); - test.ok(fo == null); - test.done(); - }) - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the tell method. - * - * @_class gridstore - * @_function tell - * @ignore - */ -exports.shouldCorrectlyExecuteGridstoreTell = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new file - var gridStore = new GridStore(db, "test_gs_tell", "w"); - // Open the file - gridStore.open(function(err, gridStore) { - // Write a string to the file - gridStore.write("hello, world!", function(err, gridStore) { - // Flush the file to GridFS - gridStore.close(function(err, result) { - - // Open the file in read only mode - var gridStore2 = new GridStore(db, "test_gs_tell", "r"); - gridStore2.open(function(err, gridStore) { - - // Read the first 5 characters - gridStore.read(5, function(err, data) { - test.equal("hello", data); - - // Get the current position of the read head - gridStore.tell(function(err, position) { - test.equal(5, position); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the seek method. - * - * @_class gridstore - * @_function getc - * @ignore - */ -exports.shouldCorrectlyRetrieveSingleCharacterUsingGetC = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a file and open it - var gridStore = new GridStore(db, "test_gs_getc_file", "w"); - gridStore.open(function(err, gridStore) { - // Write some content to the file - gridStore.write(new Buffer("hello, world!", "utf8"), function(err, gridStore) { - // Flush the file to GridFS - gridStore.close(function(result) { - - // Open the file in read mode - var gridStore2 = new GridStore(db, "test_gs_getc_file", "r"); - gridStore2.open(function(err, gridStore) { - - // Read first character and verify - gridStore.getc(function(err, chr) { - test.equal('h', chr); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/gridstore/grid_store_stream_test.js b/node_modules/mongodb/test/gridstore/grid_store_stream_test.js deleted file mode 100644 index d7eaec7..0000000 --- a/node_modules/mongodb/test/gridstore/grid_store_stream_test.js +++ /dev/null @@ -1,310 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - fs = require('fs'), - ObjectID = require('../../lib/mongodb/bson/objectid').ObjectID, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - GridStore = mongodb.GridStore, - Chunk = mongodb.Chunk, - Step = require("../../deps/step/lib/step"), - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteLargeFileStringAndReadBack = function(test) { - var db = client; - var fileId = new ObjectID(); - var gridStore = new GridStore(db, fileId, "w", {root:'fs'}); - gridStore.chunkSize = 5000; - - gridStore.open(function(err, gridStore) { - Step( - function writeData() { - var group = this.group(); - var d = ''; - for(var j = 0; j < 5000;j++) { - d = d + '+'; - } - - for(var i = 0; i < 15000; i += 5000) { - gridStore.write(d, false, group()); - } - }, - - function readAsStream() { - gridStore.close(function(err, result) { - var gotEnd = false; - var endLen = 0; - - var gridStore = new GridStore(db, fileId, "r"); - gridStore.open(function(err, gridStore) { - var stream = gridStore.stream(true); - - stream.on("data", function(chunk) { - endLen += chunk.length - // Test length of chunk - test.equal(5000, chunk.length); - // Check each chunk's data - for(var i = 0; i < 5000; i++) test.equal('+', String.fromCharCode(chunk[i])); - }); - - stream.on("end", function() { - gotEnd = true; - }); - - stream.on("close", function() { - test.equal(15000, endLen); - test.equal(true, gotEnd); - test.done(); - }); - }); - }); - } - ) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteLargeFileBufferAndReadBack = function(test) { - var db = client; - var fileId = new ObjectID(); - var gridStore = new GridStore(db, fileId, "w", {root:'fs'}); - gridStore.chunkSize = 5000; - - gridStore.open(function(err, gridStore) { - Step( - function writeData() { - var group = this.group(); - var d = new Buffer(5000); - for(var j = 0; j < 5000;j++) { - d[j] = 43; - } - - for(var i = 0; i < 15000; i += 5000) { - gridStore.write(d, false, group()); - } - }, - - function readAsStream() { - gridStore.close(function(err, result) { - var gotEnd = false; - var endLen = 0; - - var gridStore = new GridStore(db, fileId, "r"); - gridStore.open(function(err, gridStore) { - var stream = gridStore.stream(true); - - stream.on("data", function(chunk) { - endLen += chunk.length - // Test length of chunk - test.equal(5000, chunk.length); - // Check each chunk's data - for(var i = 0; i < 5000; i++) test.equal('+', String.fromCharCode(chunk[i])); - }); - - stream.on("end", function() { - gotEnd = true; - }); - - stream.on("close", function() { - test.equal(15000, endLen); - test.equal(true, gotEnd); - test.done(); - }); - }); - }); - } - ) - }); -} - -/** - * A simple example showing the usage of the stream method. - * - * @_class gridstore - * @_function stream - * @ignore - */ -exports.shouldCorrectlyReadFileUsingStream = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Open a file for reading - var gridStoreR = new GridStore(db, "test_gs_read_stream", "r"); - // Open a file for writing - var gridStoreW = new GridStore(db, "test_gs_read_stream", "w"); - // Read in the data of a file - var data = fs.readFileSync("./test/gridstore/test_gs_weird_bug.png"); - - var readLen = 0; - var gotEnd = 0; - - // Open the file we are writting to - gridStoreW.open(function(err, gs) { - // Write the file content - gs.write(data, function(err, gs) { - // Flush the file to GridFS - gs.close(function(err, result) { - - // Open the read file - gridStoreR.open(function(err, gs) { - - // Create a stream to the file - var stream = gs.stream(true); - - // Register events - stream.on("data", function(chunk) { - // Record the length of the file - readLen += chunk.length; - }); - - stream.on("end", function() { - // Record the end was called - ++gotEnd; - }); - - stream.on("close", function() { - // Verify the correctness of the read data - test.equal(data.length, readLen); - test.equal(1, gotEnd); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should return same data for streaming as for direct read'] = function(test) { - var gridStoreR = new GridStore(client, "test_gs_read_stream", "r"); - var gridStoreW = new GridStore(client, "test_gs_read_stream", "w", {chunkSize:56}); - // var data = fs.readFileSync("./test/gridstore/test_gs_weird_bug.png"); - var data = new Buffer(100); - for(var i = 0; i < 100; i++) { - data[i] = i; - } - - var readLen = 0; - var gotEnd = 0; - - gridStoreW.open(function(err, gs) { - gs.write(data, function(err, gs) { - gs.close(function(err, result) { - gridStoreR.open(function(err, gs) { - var chunks = []; - - var stream = gs.stream(true); - stream.on("data", function(chunk) { - readLen += chunk.length; - chunks.push(chunk); - }); - stream.on("end", function() { - ++gotEnd; - }); - stream.on("close", function() { - test.equal(data.length, readLen); - test.equal(1, gotEnd); - - // Read entire file in one go and compare - var gridStoreRead = new GridStore(client, "test_gs_read_stream", "r"); - gridStoreRead.open(function(err, gs) { - gridStoreRead.read(function(err, data2) { - // Put together all the chunks - var streamData = new Buffer(data.length); - var index = 0; - for(var i = 0; i < chunks.length; i++) { - chunks[i].copy(streamData, index, 0); - index = index + chunks[i].length; - } - - // Compare data - for(var i = 0; i < data.length; i++) { - test.equal(data2[i], data[i]) - test.equal(streamData[i], data[i]) - } - - test.done(); - }) - }) - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/gridstore/grid_store_test.js b/node_modules/mongodb/test/gridstore/grid_store_test.js deleted file mode 100644 index c32ef2e..0000000 --- a/node_modules/mongodb/test/gridstore/grid_store_test.js +++ /dev/null @@ -1,1351 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - fs = require('fs'), - ObjectID = require('../../lib/mongodb/bson/objectid').ObjectID, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - GridStore = mongodb.GridStore, - Chunk = mongodb.Chunk, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -// var MONGODB = 'ruby-test-db'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple example showing the usage of the Gridstore.exist method. - * - * @_class gridstore - * @_function GridStore.exist - * @ignore - */ -exports.shouldCorrectlyExecuteGridStoreExistsByObjectId = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Open a file for writing - var gridStore = new GridStore(db, null, "w"); - gridStore.open(function(err, gridStore) { - - // Writing some content to the file - gridStore.write("hello world!", function(err, gridStore) { - - // Flush the file to GridFS - gridStore.close(function(err, result) { - - // Check if the file exists using the id returned from the close function - GridStore.exist(db, result._id, function(err, result) { - test.equal(true, result); - }) - - // Show that the file does not exist for a random ObjectID - GridStore.exist(db, new ObjectID(), function(err, result) { - test.equal(false, result); - }); - - // Show that the file does not exist for a different file root - GridStore.exist(db, result._id, 'another_root', function(err, result) { - test.equal(false, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySafeFileAndReadFileByObjectId = function(test) { - var gridStore = new GridStore(client, null, "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - - // Let's read the file using object Id - GridStore.read(client, result._id, function(err, data) { - test.equal('hello world!', data); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteGridStoreExists = function(test) { - var gridStore = new GridStore(client, "foobar", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - GridStore.exist(client, 'foobar', function(err, result) { - test.equal(true, result); - }); - - GridStore.exist(client, 'does_not_exist', function(err, result) { - test.equal(false, result); - }); - - GridStore.exist(client, 'foobar', 'another_root', function(err, result) { - test.equal(false, result); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the eof method. - * - * @_class gridstore - * @_function GridStore.list - * @ignore - */ -exports.shouldCorrectlyExecuteGridStoreList = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Open a file for writing - var gridStore = new GridStore(db, "foobar2", "w"); - gridStore.open(function(err, gridStore) { - - // Write some content to the file - gridStore.write("hello world!", function(err, gridStore) { - // Flush to GridFS - gridStore.close(function(err, result) { - - // List the existing files - GridStore.list(db, function(err, items) { - var found = false; - items.forEach(function(filename) { - if(filename == 'foobar2') found = true; - }); - - test.ok(items.length >= 1); - test.ok(found); - }); - - // List the existing files but return only the file ids - GridStore.list(db, {id:true}, function(err, items) { - var found = false; - items.forEach(function(id) { - test.ok(typeof id == 'object'); - }); - - test.ok(items.length >= 1); - }); - - // List the existing files in a specific root collection - GridStore.list(db, 'fs', function(err, items) { - var found = false; - items.forEach(function(filename) { - if(filename == 'foobar2') found = true; - }); - - test.ok(items.length >= 1); - test.ok(found); - }); - - // List the existing files in a different root collection where the file is not located - GridStore.list(client, 'my_fs', function(err, items) { - var found = false; - items.forEach(function(filename) { - if(filename == 'foobar2') found = true; - }); - - test.ok(items.length >= 0); - test.ok(!found); - - // Write another file to GridFS - var gridStore2 = new GridStore(db, "foobar3", "w"); - gridStore2.open(function(err, gridStore) { - // Write the content - gridStore2.write('my file', function(err, gridStore) { - // Flush to GridFS - gridStore.close(function(err, result) { - - // List all the available files and verify that our files are there - GridStore.list(db, function(err, items) { - var found = false; - var found2 = false; - - items.forEach(function(filename) { - if(filename == 'foobar2') found = true; - if(filename == 'foobar3') found2 = true; - }); - - test.ok(items.length >= 2); - test.ok(found); - test.ok(found2); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPeformGridStoreReadLength = function(test) { - var gridStore = new GridStore(client, "test_gs_read_length", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_read_length', 5, function(err, data) { - test.equal('hello', data); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadFromFileWithOffset = function(test) { - var gridStore = new GridStore(client, "test_gs_read_with_offset", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(err, result) { - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_read_with_offset', 5, 7, function(err, data) { - test.equal('world', data); - }); - - GridStore.read(client, 'test_gs_read_with_offset', null, 7, function(err, data) { - test.equal('world!', data); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleMultipleChunkGridStore = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - var gridStore = new GridStore(fs_client, "test_gs_multi_chunk", "w"); - gridStore.open(function(err, gridStore) { - gridStore.chunkSize = 512; - var file1 = ''; var file2 = ''; var file3 = ''; - for(var i = 0; i < gridStore.chunkSize; i++) { file1 = file1 + 'x'; } - for(var i = 0; i < gridStore.chunkSize; i++) { file2 = file2 + 'y'; } - for(var i = 0; i < gridStore.chunkSize; i++) { file3 = file3 + 'z'; } - - gridStore.write(file1, function(err, gridStore) { - gridStore.write(file2, function(err, gridStore) { - gridStore.write(file3, function(err, gridStore) { - gridStore.close(function(err, result) { - fs_client.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(3, count); - - GridStore.read(fs_client, 'test_gs_multi_chunk', function(err, data) { - test.equal(512*3, data.length); - fs_client.close(); - - test.done(); - }); - }) - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the puts method. - * - * @_class gridstore - * @_function puts - * @ignore - */ -exports.shouldCorrectlyReadlinesAndPutLines = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Open a file for writing - var gridStore = new GridStore(db, "test_gs_puts_and_readlines", "w"); - gridStore.open(function(err, gridStore) { - - // Write a line to the file using the puts method - gridStore.puts("line one", function(err, gridStore) { - - // Flush the file to GridFS - gridStore.close(function(err, result) { - - // Read in the entire contents - GridStore.read(db, 'test_gs_puts_and_readlines', function(err, data) { - test.equal("line one\n", data.toString()); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleUnlinkingWeirdName = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - var gridStore = new GridStore(fs_client, "9476700.937375426_1271170118964-clipped.png", "w", {'root':'articles'}); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(err, result) { - fs_client.collection('articles.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - }) - }); - - fs_client.collection('articles.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - - // Unlink the file - GridStore.unlink(fs_client, '9476700.937375426_1271170118964-clipped.png', {'root':'articles'}, function(err, gridStore) { - fs_client.collection('articles.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - }) - }); - - fs_client.collection('articles.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - - fs_client.close(); - test.done(); - }) - }); - }); - }) - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the GridStore.unlink method. - * - * @_class gridstore - * @_function GridStore.unlink - * @ignore - */ -exports.shouldCorrectlyUnlink = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Open a new file for writing - var gridStore = new GridStore(db, "test_gs_unlink", "w"); - gridStore.open(function(err, gridStore) { - - // Write some content - gridStore.write("hello, world!", function(err, gridStore) { - - // Flush file to GridFS - gridStore.close(function(err, result) { - - // Verify the existance of the fs.files document - db.collection('fs.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - }) - }); - - // Verify the existance of the fs.chunks chunk document - db.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - - // Unlink the file (removing it) - GridStore.unlink(db, 'test_gs_unlink', function(err, gridStore) { - - // Verify that fs.files document is gone - db.collection('fs.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - }) - }); - - // Verify that fs.chunks chunk documents are gone - db.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - - db.close(); - test.done(); - }) - }); - }); - }) - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyUnlinkAnArrayOfFiles = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - var gridStore = new GridStore(fs_client, "test_gs_unlink_as_array", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(err, result) { - fs_client.collection('fs.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - }) - }); - - fs_client.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - - // Unlink the file - GridStore.unlink(fs_client, ['test_gs_unlink_as_array'], function(err, gridStore) { - fs_client.collection('fs.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - }) - }); - - fs_client.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - fs_client.close(); - - test.done(); - }) - }); - }); - }) - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteFileToGridStore= function(test) { - var gridStore = new GridStore(client, 'test_gs_writing_file', 'w'); - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - gridStore.writeFile('./test/gridstore/test_gs_weird_bug.png', function(err, doc) { - GridStore.read(client, 'test_gs_writing_file', function(err, fileData) { - test.equal(data.toString('hex'), fileData.toString('hex')); - test.equal(fileSize, fileData.length); - - // Ensure we have a md5 - var gridStore2 = new GridStore(client, 'test_gs_writing_file', 'r'); - gridStore2.open(function(err, gridStore2) { - test.ok(gridStore2.md5 != null) - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteFileToGridStoreUsingObjectId= function(test) { - var gridStore = new GridStore(client, null, 'w'); - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - gridStore.writeFile('./test/gridstore/test_gs_weird_bug.png', function(err, doc) { - - GridStore.read(client, doc._id, function(err, fileData) { - test.equal(data.toString('hex'), fileData.toString('hex')); - test.equal(fileSize, fileData.length); - - // Ensure we have a md5 - var gridStore2 = new GridStore(client, doc._id, 'r'); - gridStore2.open(function(err, gridStore2) { - test.ok(gridStore2.md5 != null) - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformWorkingFiledRead = function(test) { - var gridStore = new GridStore(client, "test_gs_working_field_read", "w"); - var data = fs.readFileSync("./test/gridstore/test_gs_working_field_read.pdf", 'binary'); - - gridStore.open(function(err, gridStore) { - gridStore.write(data, function(err, gridStore) { - gridStore.close(function(err, result) { - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_working_field_read', function(err, fileData) { - test.equal(data.length, fileData.length); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadAndWriteFile = function(test) { - var gridStore = new GridStore(client, "test_gs_weird_bug", "w"); - var data = fs.readFileSync("./test/gridstore/test_gs_weird_bug.png", 'binary'); - - gridStore.open(function(err, gridStore) { - gridStore.write(data, function(err, gridStore) { - gridStore.close(function(err, result) { - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_weird_bug', function(err, fileData) { - test.equal(data.length, fileData.length); - test.done(); - }); - }); - }); - }); -} - - -/** - * A simple example showing the usage of the read method. - * - * @_class gridstore - * @_function read - * @ignore - */ -exports.shouldCorrectlyWriteAndReadJpgImage = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Read in the content of a file - var data = fs.readFileSync('./test/gridstore/iya_logo_final_bw.jpg'); - // Create a new file - var gs = new GridStore(db, "test", "w"); - // Open the file - gs.open(function(err, gs) { - // Write the file to GridFS - gs.write(data, function(err, gs) { - // Flush to the GridFS - gs.close(function(err, gs) { - - // Define the file we wish to read - var gs2 = new GridStore(db, "test", "r"); - // Open the file - gs2.open(function(err, gs) { - // Set the pointer of the read head to the start of the gridstored file - gs2.seek(0, function() { - // Read the entire file - gs2.read(function(err, data2) { - // Compare the file content against the orgiinal - test.equal(data.toString('hex'), data2.toString('hex')); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadAndWriteBuffersMultipleChunks = function(test) { - var gridStore = new GridStore(client, null, 'w'); - // Force multiple chunks to be stored - gridStore.chunkSize = 5000; - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - - // Write the file using write - gridStore.write(data, function(err, doc) { - gridStore.close(function(err, doc) { - - // Read the file using readBuffer - new GridStore(client, doc._id, 'r').open(function(err, gridStore) { - gridStore.read(function(err, data2) { - test.equal(data.toString('base64'), data2.toString('base64')); - test.done(); - }) - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadAndWriteBuffersSingleChunks = function(test) { - var gridStore = new GridStore(client, null, 'w'); - // Force multiple chunks to be stored - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - - // Write the file using writeBuffer - gridStore.write(data, function(err, doc) { - gridStore.close(function(err, doc) { - - // Read the file using readBuffer - new GridStore(client, doc._id, 'r').open(function(err, gridStore) { - gridStore.read(function(err, data2) { - test.equal(data.toString('base64'), data2.toString('base64')); - test.done(); - }) - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadAndWriteBuffersUsingNormalWriteWithMultipleChunks = function(test) { - var gridStore = new GridStore(client, null, 'w'); - // Force multiple chunks to be stored - gridStore.chunkSize = 5000; - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - - // Write the buffer using the .write method that should use writeBuffer correctly - gridStore.write(data, function(err, doc) { - gridStore.close(function(err, doc) { - - // Read the file using readBuffer - new GridStore(client, doc._id, 'r').open(function(err, gridStore) { - gridStore.read(function(err, data2) { - test.equal(data.toString('base64'), data2.toString('base64')); - test.done(); - }) - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadAndWriteBuffersSingleChunksAndVerifyExistance = function(test) { - var gridStore = new GridStore(client, null, 'w'); - // Force multiple chunks to be stored - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - - // Write the file using writeBuffer - gridStore.write(data, function(err, doc) { - gridStore.close(function(err, doc) { - - // Read the file using readBuffer - GridStore.exist(client, doc._id, function(err, result) { - test.equal(null, err); - test.equal(true, result); - - client.close(); - test.done(); - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveDataByObjectID = function(test) { - var id = new ObjectID(); - var gridStore = new GridStore(client, id, 'w'); - - gridStore.open(function(err, gridStore) { - gridStore.write('bar', function(err, gridStore) { - gridStore.close(function(err, result) { - - GridStore.exist(client, id, function(err, result) { - test.equal(null, err); - test.equal(true, result); - - client.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCheckExistsByUsingRegexp = function(test) { - var gridStore = new GridStore(client, 'shouldCheckExistsByUsingRegexp.txt', 'w'); - - gridStore.open(function(err, gridStore) { - gridStore.write('bar', function(err, gridStore) { - gridStore.close(function(err, result) { - - GridStore.exist(client, /shouldCheck/, function(err, result) { - test.equal(null, err); - test.equal(true, result); - - client.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing opening a file using a filename, writing to it and saving it. - * - * @_class gridstore - * @_function open - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingFilename = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new instance of the gridstore - var gridStore = new GridStore(db, 'ourexamplefiletowrite.txt', 'w'); - - // Open the file - gridStore.open(function(err, gridStore) { - - // Write some data to the file - gridStore.write('bar', function(err, gridStore) { - test.equal(null, err); - - // Close (Flushes the data to MongoDB) - gridStore.close(function(err, result) { - test.equal(null, err); - - // Verify that the file exists - GridStore.exist(db, 'ourexamplefiletowrite.txt', function(err, result) { - test.equal(null, err); - test.equal(true, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing opening a file using an ObjectID, writing to it and saving it. - * - * @_class gridstore - * @_function open - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingObjectID = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Create a new instance of the gridstore - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the file - gridStore.open(function(err, gridStore) { - - // Write some data to the file - gridStore.write('bar', function(err, gridStore) { - test.equal(null, err); - - // Close (Flushes the data to MongoDB) - gridStore.close(function(err, result) { - test.equal(null, err); - - // Verify that the file exists - GridStore.exist(db, fileId, function(err, result) { - test.equal(null, err); - test.equal(true, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing how to write a file to Gridstore using file location path. - * - * @_class gridstore - * @_function writeFile - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingWriteFile = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Read the filesize of file on disk (provide your own) - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - // Read the buffered data for comparision reasons - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write the file to gridFS - gridStore.writeFile('./test/gridstore/test_gs_weird_bug.png', function(err, doc) { - - // Read back all the written content and verify the correctness - GridStore.read(db, fileId, function(err, fileData) { - test.equal(data.toString('hex'), fileData.toString('hex')) - test.equal(fileSize, fileData.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing how to write a file to Gridstore using a file handle. - * - * @_class gridstore - * @_function writeFile - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingWriteFileWithHandle = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Read the filesize of file on disk (provide your own) - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - // Read the buffered data for comparision reasons - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - // Open a file handle for reading the file - var fd = fs.openSync('./test/gridstore/test_gs_weird_bug.png', 'r', 0666); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write the file to gridFS using the file handle - gridStore.writeFile(fd, function(err, doc) { - - // Read back all the written content and verify the correctness - GridStore.read(db, fileId, function(err, fileData) { - test.equal(data.toString('hex'), fileData.toString('hex')); - test.equal(fileSize, fileData.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing how to use the write command with strings and Buffers. - * - * @_class gridstore - * @_function write - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingWriteWithStringsAndBuffers = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write a text string - gridStore.write('Hello world', function(err, gridStore) { - - // Write a buffer - gridStore.write(new Buffer('Buffer Hello world'), function(err, gridStore) { - - // Close the - gridStore.close(function(err, result) { - - // Read back all the written content and verify the correctness - GridStore.read(db, fileId, function(err, fileData) { - test.equal('Hello worldBuffer Hello world', fileData.toString()); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing how to use the write command with strings and Buffers. - * - * @_class gridstore - * @_function close - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingClose = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write a text string - gridStore.write('Hello world', function(err, gridStore) { - - // Close the - gridStore.close(function(err, result) { - test.equal(err, null); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing how to access the chunks collection object. - * - * @_class gridstore - * @_function chunkCollection - * @ignore - */ -exports.shouldCorrectlyAccessChunkCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Access the Chunk collection - gridStore.chunkCollection(function(err, collection) { - test.equal(err, null); - test.ok(collection instanceof Collection); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * A simple example showing how to use the instance level unlink command to delete a gridstore item. - * - * @_class gridstore - * @_function unlink - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingCloseAndThenUnlinkIt = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write a text string - gridStore.write('Hello world', function(err, gridStore) { - - // Close the - gridStore.close(function(err, result) { - test.equal(err, null); - - // Open the file again and unlin it - new GridStore(db, fileId, 'r').open(function(err, gridStore) { - - // Unlink the file - gridStore.unlink(function(err, result) { - test.equal(null, err); - - // Verify that the file no longer exists - GridStore.exist(db, fileId, function(err, result) { - test.equal(null, err); - test.equal(false, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing how to access the files collection object. - * - * @_class gridstore - * @_function collection - * @ignore - */ -exports.shouldCorrectlyAccessFilesCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Access the Chunk collection - gridStore.collection(function(err, collection) { - test.equal(err, null); - test.ok(collection instanceof Collection); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * A simple example showing reading back using readlines to split the text into lines by the seperator provided. - * - * @_class gridstore - * @_function GridStore.readlines - * @ignore - */ -exports.shouldCorrectlyPutACoupleOfLinesInGridStoreAndUseReadlines = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write one line to gridStore - gridStore.puts("line one", function(err, gridStore) { - - // Write second line to gridStore - gridStore.puts("line two", function(err, gridStore) { - - // Write third line to gridStore - gridStore.puts("line three", function(err, gridStore) { - - // Flush file to disk - gridStore.close(function(err, result) { - - // Read back all the lines - GridStore.readlines(db, fileId, function(err, lines) { - test.deepEqual(["line one\n", "line two\n", "line three\n"], lines); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing reading back using readlines to split the text into lines by the seperator provided. - * - * @_class gridstore - * @_function readlines - * @ignore - */ -exports.shouldCorrectlyPutACoupleOfLinesInGridStoreAndUseInstanceReadlines = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write one line to gridStore - gridStore.puts("line one", function(err, gridStore) { - - // Write second line to gridStore - gridStore.puts("line two", function(err, gridStore) { - - // Write third line to gridStore - gridStore.puts("line three", function(err, gridStore) { - - // Flush file to disk - gridStore.close(function(err, result) { - - // Open file for reading - gridStore = new GridStore(db, fileId, 'r'); - gridStore.open(function(err, gridStore) { - - // Read all the lines and verify correctness - gridStore.readlines(function(err, lines) { - test.deepEqual(["line one\n", "line two\n", "line three\n"], lines); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the read method. - * - * @_class gridstore - * @_function GridStore.read - * @ignore - */ -exports.shouldCorrectlyPutACoupleOfLinesInGridStoreRead = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new file - var gridStore = new GridStore(db, null, "w"); - // Read in the content from a file, replace with your own - var data = fs.readFileSync("./test/gridstore/test_gs_weird_bug.png"); - - // Open the file - gridStore.open(function(err, gridStore) { - // Write the binary file data to GridFS - gridStore.write(data, function(err, gridStore) { - // Flush the remaining data to GridFS - gridStore.close(function(err, result) { - - // Read in the whole file and check that it's the same content - GridStore.read(client, result._id, function(err, fileData) { - test.equal(data.length, fileData.length); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/gridstore/grid_test.js b/node_modules/mongodb/test/gridstore/grid_test.js deleted file mode 100644 index 7c0edb1..0000000 --- a/node_modules/mongodb/test/gridstore/grid_test.js +++ /dev/null @@ -1,189 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - GridStore = mongodb.GridStore, - Grid = mongodb.Grid, - Chunk = mongodb.Chunk, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple example showing the usage of the put method. - * - * @_class grid - * @_function put - * @ignore - */ -exports.shouldPutFileCorrectlyToGridUsingObjectId = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new grid instance - var grid = new Grid(db, 'fs'); - // Some data to write - var originalData = new Buffer('Hello world'); - // Write data to grid - grid.put(originalData, {}, function(err, result) { - // Fetch the content - grid.get(result._id, function(err, data) { - test.deepEqual(originalData.toString('hex'), data.toString('hex')); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * A simple example showing the usage of the get method. - * - * @_class grid - * @_function get - * @ignore - */ -exports.shouldPutAndGetFileCorrectlyToGridUsingObjectId = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new grid instance - var grid = new Grid(db, 'fs'); - // Some data to write - var originalData = new Buffer('Hello world'); - // Write data to grid - grid.put(originalData, {}, function(err, result) { - // Fetch the content - grid.get(result._id, function(err, data) { - test.deepEqual(originalData.toString('base64'), data.toString('base64')); - - // Should fail due to illegal objectID - grid.get('not an id', function(err, result) { - test.ok(err != null); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldFailToPutFileDueToDataObjectNotBeingBuffer = function(test) { - var grid = new Grid(client, 'fs'); - var originalData = 'Hello world'; - // Write data to grid - grid.put(originalData, {}, function(err, result) { - test.ok(err != null); - test.done(); - }) -} - -/** - * A simple example showing the usage of the delete method. - * - * @_class grid - * @_function delete - * @ignore - */ -exports.shouldCorrectlyWriteFileAndThenDeleteIt = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new grid instance - var grid = new Grid(client, 'fs'); - // Some data to write - var originalData = new Buffer('Hello world'); - // Write data to grid - grid.put(originalData, {}, function(err, result) { - - // Delete file - grid.delete(result._id, function(err, result2) { - test.equal(null, err); - test.equal(true, result2); - - // Fetch the content, showing that the file is gone - grid.get(result._id, function(err, data) { - test.ok(err != null); - test.equal(null, data); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/gridstore/iya_logo_final_bw.jpg b/node_modules/mongodb/test/gridstore/iya_logo_final_bw.jpg deleted file mode 100644 index 0f07b9e..0000000 Binary files a/node_modules/mongodb/test/gridstore/iya_logo_final_bw.jpg and /dev/null differ diff --git a/node_modules/mongodb/test/gridstore/readstream_test.js b/node_modules/mongodb/test/gridstore/readstream_test.js deleted file mode 100644 index ef0d869..0000000 --- a/node_modules/mongodb/test/gridstore/readstream_test.js +++ /dev/null @@ -1,239 +0,0 @@ -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = require('../../lib/mongodb').Db, - ObjectID = require('../../lib/mongodb').ObjectID, - Cursor = require('../../lib/mongodb').Cursor, - Step = require("../../deps/step/lib/step"), - Collection = require('../../lib/mongodb').Collection, - GridStore = require('../../lib/mongodb').GridStore, - fs = require('fs'), - Server = require('../../lib/mongodb').Server; - -var MONGODB = 'integration_tests'; -var useSSL = process.env['USE_SSL'] != null ? true : false; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple example showing the use of the readstream pause function. - * - * @_class readstream - * @_function pause - * @ignore - */ -exports.shouldStreamDocumentsUsingTheReadStreamPauseFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // File id - var fileId = new ObjectID(); - // Create a file - var file = new GridStore(db, fileId, "w"); - file.open(function(err, file) { - // Write some content and flush to disk - file.write('Hello world', function(err, file) { - file.close(function(err, result) { - - // Let's create a read file - file = new GridStore(db, fileId, "r"); - // Open the file - file.open(function(err, file) { - // Peform a find to get a cursor - var stream = file.stream(); - - // For each data item - stream.on("data", function(item) { - // Check if stream is paused - test.equal(false, stream.paused); - // Pause stream - stream.pause(); - // Check if cursor is paused - test.equal(true, stream.paused); - - // Restart the stream after 1 miliscecond - setTimeout(function() { - stream.resume(); - // Check if cursor is paused - test.equal(false, stream.paused); - }, 1); - }); - - // For each data item - stream.on("end", function(item) {}); - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the readstream resume function. - * - * @_class readstream - * @_function resume - * @ignore - */ -exports.shouldStreamDocumentsUsingTheReadStreamResumeFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // File id - var fileId = new ObjectID(); - // Create a file - var file = new GridStore(db, fileId, "w"); - file.open(function(err, file) { - // Write some content and flush to disk - file.write('Hello world', function(err, file) { - file.close(function(err, result) { - - // Let's create a read file - file = new GridStore(db, fileId, "r"); - // Open the file - file.open(function(err, file) { - // Peform a find to get a cursor - var stream = file.stream(); - - // For each data item - stream.on("data", function(item) { - // Check if stream is paused - test.equal(false, stream.paused); - // Pause stream - stream.pause(); - // Check if cursor is paused - test.equal(true, stream.paused); - - // Restart the stream after 1 miliscecond - setTimeout(function() { - stream.resume(); - // Check if cursor is paused - test.equal(false, stream.paused); - }, 1); - }); - - // For each data item - stream.on("end", function(item) {}); - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the readstream destroy function. - * - * @_class readstream - * @_function destroy - * @ignore - */ -exports.shouldStreamDocumentsUsingTheReadStreamDestroyFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // File id - var fileId = new ObjectID(); - // Create a file - var file = new GridStore(db, fileId, "w"); - file.open(function(err, file) { - // Write some content and flush to disk - file.write('Hello world', function(err, file) { - file.close(function(err, result) { - - // Let's create a read file - file = new GridStore(db, fileId, "r"); - // Open the file - file.open(function(err, file) { - // Peform a find to get a cursor - var stream = file.stream(); - - // For each data item - stream.on("data", function(item) { - // Destroy the stream - stream.destroy(); - }); - - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/gridstore/test_gs_weird_bug.png b/node_modules/mongodb/test/gridstore/test_gs_weird_bug.png deleted file mode 100644 index 1554dc3..0000000 Binary files a/node_modules/mongodb/test/gridstore/test_gs_weird_bug.png and /dev/null differ diff --git a/node_modules/mongodb/test/gridstore/test_gs_working_field_read.pdf b/node_modules/mongodb/test/gridstore/test_gs_working_field_read.pdf deleted file mode 100644 index 4b1247a..0000000 Binary files a/node_modules/mongodb/test/gridstore/test_gs_working_field_read.pdf and /dev/null differ diff --git a/node_modules/mongodb/test/index_test.js b/node_modules/mongodb/test/index_test.js deleted file mode 100644 index 5c43cdb..0000000 --- a/node_modules/mongodb/test/index_test.js +++ /dev/null @@ -1,699 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple createIndex using a simple single field index - * - * @_class collection - * @_function createIndex - */ -exports.shouldCreateASimpleIndexOnASingleField = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_index_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1}, {a:2}, {a:3}, {a:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.createIndex('a', function(err, indexName) { - test.equal("a_1", indexName); - - // Peform a query, with explain to show we hit the query - collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { - test.deepEqual([[2, 2]], explanation[0].indexBounds.a); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A more complex createIndex using a compound unique index in the background and dropping duplicated documents - * - * @_class collection - * @_function createIndex - */ -exports.shouldCreateComplexIndexOnTwoFields = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_complex_index_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.createIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Show that duplicate records got dropped - collection.find({}).toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - - // Peform a query, with explain to show we hit the query - collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { - test.equal(null, err); - test.ok(explanation[0].indexBounds.a != null); - test.ok(explanation[0].indexBounds.b != null); - - db.close(); - test.done(); - }); - }) - }); - }); - }); - }); -} - -/** - * A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents. - * - * @_class collection - * @_function ensureIndex - */ -exports.shouldCreateComplexEnsureIndex = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_complex_ensure_index_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Show that duplicate records got dropped - collection.find({}).toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - - // Peform a query, with explain to show we hit the query - collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { - test.equal(null, err); - test.ok(explanation[0].indexBounds.a != null); - test.ok(explanation[0].indexBounds.b != null); - - db.close(); - test.done(); - }); - }) - }); - }); - }); - }); -} - -/** - * An examples showing the information returned by indexInformation - * - * @_class collection - * @_function indexInformation - */ -exports.shouldCorrectlyShowTheResultsFromIndexInformation = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_index_information_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Fetch basic indexInformation for collection - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); - - // Fetch full index information - collection.indexInformation({full:true}, function(err, indexInformation) { - test.deepEqual({ _id: 1 }, indexInformation[0].key); - test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An examples showing the creation and dropping of an index - * - * @_class collection - * @_function dropIndex - */ -exports.shouldCorrectlyCreateAndDropIndex = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('create_and_drop_an_index', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Drop the index - collection.dropIndex("a_1_b_1", function(err, result) { - test.equal(null, err); - - // Verify that the index is gone - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.equal(null, indexInformation.a_1_b_1); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An examples showing the creation and dropping of an index - * - * @_class collection - * @_function dropIndexes - */ -exports.shouldCorrectlyCreateAndDropAllIndex = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('create_and_drop_all_indexes', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Create an additional index - collection.ensureIndex({c:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Drop the index - collection.dropAllIndexes(function(err, result) { - test.equal(null, err); - - // Verify that the index is gone - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.equal(null, indexInformation.a_1_b_1); - test.equal(null, indexInformation.c_1); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * An example showing how to force a reindex of a collection. - * - * @_class collection - * @_function reIndex - */ -exports.shouldCorrectlyForceReindexOnCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('create_and_drop_all_indexes', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Force a reindex of the collection - collection.reIndex(function(err, result) { - test.equal(null, err); - test.equal(true, result); - - // Verify that the index is gone - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExtractIndexInformation = function(test) { - client.createCollection('test_index_information', function(err, collection) { - collection.insert({a:1}, {safe:true}, function(err, ids) { - // Create an index on the collection - client.createIndex(collection.collectionName, 'a', function(err, indexName) { - test.equal("a_1", indexName); - // Let's fetch the index information - client.indexInformation(collection.collectionName, function(err, collectionInfo) { - test.ok(collectionInfo['_id_'] != null); - test.equal('_id', collectionInfo['_id_'][0][0]); - test.ok(collectionInfo['a_1'] != null); - test.deepEqual([["a", 1]], collectionInfo['a_1']); - - client.indexInformation(function(err, collectionInfo2) { - var count1 = 0, count2 = 0; - // Get count of indexes - for(var i in collectionInfo) { count1 += 1;} - for(var i in collectionInfo2) { count2 += 1;} - - // Tests - test.ok(count2 >= count1); - test.ok(collectionInfo2['_id_'] != null); - test.equal('_id', collectionInfo2['_id_'][0][0]); - test.ok(collectionInfo2['a_1'] != null); - test.deepEqual([["a", 1]], collectionInfo2['a_1']); - test.ok((collectionInfo[indexName] != null)); - test.deepEqual([["a", 1]], collectionInfo[indexName]); - - // Let's close the db - test.done(); - }); - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleMultipleColumnIndexes = function(test) { - client.createCollection('test_multiple_index_cols', function(err, collection) { - collection.insert({a:1}, function(err, ids) { - // Create an index on the collection - client.createIndex(collection.collectionName, [['a', -1], ['b', 1], ['c', -1]], function(err, indexName) { - test.equal("a_-1_b_1_c_-1", indexName); - // Let's fetch the index information - client.indexInformation(collection.collectionName, function(err, collectionInfo) { - var count1 = 0; - // Get count of indexes - for(var i in collectionInfo) { count1 += 1;} - - // Test - test.equal(2, count1); - test.ok(collectionInfo[indexName] != null); - test.deepEqual([['a', -1], ['b', 1], ['c', -1]], collectionInfo[indexName]); - - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleUniqueIndex = function(test) { - // Create a non-unique index and test inserts - client.createCollection('test_unique_index', function(err, collection) { - client.createIndex(collection.collectionName, 'hello', function(err, indexName) { - // Insert some docs - collection.insert([{'hello':'world'}, {'hello':'mike'}, {'hello':'world'}], {safe:true}, function(err, errors) { - // Assert that we have no erros - client.error(function(err, errors) { - test.equal(1, errors.length); - test.equal(null, errors[0].err); - - // Create a unique index and test that insert fails - client.createCollection('test_unique_index2', function(err, collection) { - client.createIndex(collection.collectionName, 'hello', {unique:true}, function(err, indexName) { - // Insert some docs - collection.insert([{'hello':'world'}, {'hello':'mike'}, {'hello':'world'}], {safe:true}, function(err, ids) { - test.ok(err != null); - test.equal(11000, err.code); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCreateSubfieldIndex = function(test) { - // Create a non-unique index and test inserts - client.createCollection('test_index_on_subfield', function(err, collection) { - collection.insert([{'hello': {'a':4, 'b':5}}, {'hello': {'a':7, 'b':2}}, {'hello': {'a':4, 'b':10}}], {safe:true}, function(err, ids) { - // Assert that we have no erros - client.error(function(err, errors) { - test.equal(1, errors.length); - test.ok(errors[0].err == null); - - // Create a unique subfield index and test that insert fails - client.createCollection('test_index_on_subfield2', function(err, collection) { - client.createIndex(collection.collectionName, 'hello.a', true, function(err, indexName) { - collection.insert([{'hello': {'a':4, 'b':5}}, {'hello': {'a':7, 'b':2}}, {'hello': {'a':4, 'b':10}}], {safe:true}, function(err, ids) { - // Assert that we have erros - test.ok(err != null); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyDropIndexes = function(test) { - client.createCollection('test_drop_indexes', function(err, collection) { - collection.insert({a:1}, {safe:true}, function(err, ids) { - // Create an index on the collection - client.createIndex(collection.collectionName, 'a', function(err, indexName) { - test.equal("a_1", indexName); - // Drop all the indexes - collection.dropAllIndexes(function(err, result) { - test.equal(true, result); - - collection.indexInformation(function(err, result) { - test.ok(result['a_1'] == null); - test.done(); - }) - }) - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleDistinctIndexes = function(test) { - client.createCollection('test_distinct_queries', function(err, collection) { - collection.insert([{'a':0, 'b':{'c':'a'}}, - {'a':1, 'b':{'c':'b'}}, - {'a':1, 'b':{'c':'c'}}, - {'a':2, 'b':{'c':'a'}}, {'a':3}, {'a':3}], {safe:true}, function(err, ids) { - collection.distinct('a', function(err, docs) { - test.deepEqual([0, 1, 2, 3], docs.sort()); - }); - - collection.distinct('b.c', function(err, docs) { - test.deepEqual(['a', 'b', 'c'], docs.sort()); - test.done(); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteEnsureIndex = function(test) { - client.createCollection('test_ensure_index', function(err, collection) { - // Create an index on the collection - client.ensureIndex(collection.collectionName, 'a', function(err, indexName) { - test.equal("a_1", indexName); - // Let's fetch the index information - client.indexInformation(collection.collectionName, function(err, collectionInfo) { - test.ok(collectionInfo['_id_'] != null); - test.equal('_id', collectionInfo['_id_'][0][0]); - test.ok(collectionInfo['a_1'] != null); - test.deepEqual([["a", 1]], collectionInfo['a_1']); - - client.ensureIndex(collection.collectionName, 'a', function(err, indexName) { - test.equal("a_1", indexName); - // Let's fetch the index information - client.indexInformation(collection.collectionName, function(err, collectionInfo) { - test.ok(collectionInfo['_id_'] != null); - test.equal('_id', collectionInfo['_id_'][0][0]); - test.ok(collectionInfo['a_1'] != null); - test.deepEqual([["a", 1]], collectionInfo['a_1']); - // Let's close the db - test.done(); - }); - }); - }); - }); - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyCreateAndUseSparseIndex = function(test) { - client.createCollection('create_and_use_sparse_index_test', function(err, r) { - client.collection('create_and_use_sparse_index_test', function(err, collection) { - - collection.ensureIndex({title:1}, {sparse:true}, function(err, indexName) { - collection.insert([{name:"Jim"}, {name:"Sarah", title:"Princess"}], {safe:true}, function(err, result) { - collection.find({title:{$ne:null}}).sort({title:1}).toArray(function(err, items) { - test.equal(1, items.length); - test.equal("Sarah", items[0].name); - - // Fetch the info for the indexes - collection.indexInformation({full:true}, function(err, indexInfo) { - test.equal(null, err); - test.equal(2, indexInfo.length); - test.done(); - }) - }) - }); - }) - }) - }) -} - -/** - * @ignore - */ -exports["Should correctly execute insert with keepGoing option on mongod >= 1.9.1"] = function(test) { - client.admin().serverInfo(function(err, result){ - if(parseInt((result.version.replace(/\./g, ''))) >= 191) { - client.createCollection('shouldCorrectlyExecuteKeepGoingWithMongodb191OrHigher', function(err, collection) { - collection.ensureIndex({title:1}, {unique:true}, function(err, indexName) { - collection.insert([{name:"Jim"}, {name:"Sarah", title:"Princess"}], {safe:true}, function(err, result) { - // Force keep going flag, ignoring unique index issue - collection.insert([{name:"Jim"}, {name:"Sarah", title:"Princess"}, {name:'Gump', title:"Gump"}], {safe:true, keepGoing:true}, function(err, result) { - collection.count(function(err, count) { - test.equal(3, count); - test.done(); - }) - }); - }); - }); - }); - } else { - test.done(); - } - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleGeospatialIndexes = function(test) { - client.admin().serverInfo(function(err, result){ - if(parseInt((result.version.replace(/\./g, ''))) >= 191) { - client.createCollection('geospatial_index_test', function(err, r) { - client.collection('geospatial_index_test', function(err, collection) { - collection.ensureIndex({loc:'2d'}, function(err, indexName) { - collection.insert({'loc': [-100,100]}, {safe:true}, function(err, result) { - test.equal(err,null); - collection.insert({'loc': [200,200]}, {safe:true}, function(err, result) { - err = err ? err : {}; - test.equal(err.err,"point not in interval of [ -180, 180 )"); - test.done(); - }); - }); - }); - }); - }); - } else { - test.done(); - } - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleGeospatialIndexesAlteredRange = function(test) { - client.admin().serverInfo(function(err, result){ - if(parseInt((result.version.replace(/\./g, ''))) >= 191) { - client.createCollection('geospatial_index_altered_test', function(err, r) { - client.collection('geospatial_index_altered_test', function(err, collection) { - collection.ensureIndex({loc:'2d'},{min:0,max:1024}, function(err, indexName) { - collection.insert({'loc': [100,100]}, {safe:true}, function(err, result) { - test.equal(err,null); - collection.insert({'loc': [200,200]}, {safe:true}, function(err, result) { - test.equal(err,null); - collection.insert({'loc': [-200,-200]}, {safe:true}, function(err, result) { - err = err ? err : {}; - test.equal(err.err,"point not in interval of [ 0, 1024 )"); - test.done(); - }); - }); - }); - }); - }); - }); - } else { - test.done(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/insert_test.js b/node_modules/mongodb/test/insert_test.js deleted file mode 100644 index 32da730..0000000 --- a/node_modules/mongodb/test/insert_test.js +++ /dev/null @@ -1,1132 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Script = require('vm'), - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Binary = require('../lib/mongodb/bson/binary').Binary, - Code = require('../lib/mongodb/bson/code').Code, - DBRef = require('../lib/mongodb/bson/db_ref').DBRef, - Timestamp = require('../lib/mongodb/bson/timestamp').Timestamp, - Long = require('../lib/mongodb/bson/long').Long, - Collection = mongodb.Collection, - Server = mongodb.Server, - Step = require("../deps/step/lib/step"), - ServerManager = require('./tools/server_manager').ServerManager; - -var MONGODB = 'integration_tests'; -var client = null; -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Module for parsing an ISO 8601 formatted string into a Date object. - * @ignore - */ -var ISODate = function (string) { - var match; - - if (typeof string.getTime === "function") - return string; - else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) { - var date = new Date(); - date.setUTCFullYear(Number(match[1])); - date.setUTCMonth(Number(match[3]) - 1 || 0); - date.setUTCDate(Number(match[5]) || 0); - date.setUTCHours(Number(match[7]) || 0); - date.setUTCMinutes(Number(match[8]) || 0); - date.setUTCSeconds(Number(match[10]) || 0); - date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0); - - if (match[13] && match[13] !== "Z") { - var h = Number(match[16]) || 0, - m = Number(match[17]) || 0; - - h *= 3600000; - m *= 60000; - - var offset = h + m; - if (match[15] == "+") - offset = -offset; - - new Date(date.valueOf() + offset); - } - - return date; - } else - throw new Error("Invalid ISO 8601 date given.", __filename); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple document insert example, not using safe mode to ensure document persistance on MongoDB - * - * @_class collection - * @_function insert - * @ignore - */ -exports.shouldCorrectlyPerformASimpleSingleDocumentInsertNoCallbackNoSafe = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection to insert document into - db.collection("simple_document_insert_collection_no_safe", function(err, collection) { - - // Insert a single document - collection.insert({hello:'world_no_safe'}); - - // Wait for a second before finishing up, to ensure we have written the item to disk - setTimeout(function() { - - // Fetch the document - collection.findOne({hello:'world_no_safe'}, function(err, item) { - test.equal(null, err); - test.equal('world_no_safe', item.hello); - test.done(); - db.close(); - }) - }, 1000); - }); - }); -} - -/** - * A batch document insert example, using safe mode to ensure document persistance on MongoDB - * - * @_class collection - * @_function insert - * @ignore - */ -exports.shouldCorrectlyPerformABatchDocumentInsertSafe = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection to insert document into - db.collection("batch_document_insert_collection_safe", function(err, collection) { - - // Insert a single document - collection.insert([{hello:'world_safe1'} - , {hello:'world_safe2'}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Fetch the document - collection.findOne({hello:'world_safe2'}, function(err, item) { - test.equal(null, err); - test.equal('world_safe2', item.hello); - test.done(); - db.close(); - }) - }); - }); - }); -} - -/** - * Example of inserting a document containing functions - * - * @_class collection - * @_function insert - * @ignore - */ -exports.shouldCorrectlyPerformASimpleDocumentInsertWithFunctionSafe = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection to insert document into - db.collection("simple_document_insert_with_function_safe", function(err, collection) { - - // Insert a single document - collection.insert({hello:'world' - , func:function() {}}, {safe:true, serializeFunctions:true}, function(err, result) { - test.equal(null, err); - - // Fetch the document - collection.findOne({hello:'world'}, function(err, item) { - test.equal(null, err); - test.ok("function() {}", item.code); - test.done(); - db.close(); - }) - }); - }); - }); -} - -/** - * Example of using keepGoing to allow batch insert to complete even when there are illegal documents in the batch - * - * @_class collection - * @_function insert - * @ignore - */ -exports["Should correctly execute insert with keepGoing option on mongod >= 1.9.1"] = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Only run the rest of the code if we have a mongodb server with version >= 1.9.1 - db.admin().serverInfo(function(err, result){ - - // Ensure we are running at least MongoDB v1.9.1 - if(parseInt((result.version.replace(/\./g, ''))) >= 191) { - - // Create a collection - client.createCollection('keepGoingExample', function(err, collection) { - - // Add an unique index to title to force errors in the batch insert - collection.ensureIndex({title:1}, {unique:true}, function(err, indexName) { - - // Insert some intial data into the collection - collection.insert([{name:"Jim"} - , {name:"Sarah", title:"Princess"}], {safe:true}, function(err, result) { - - // Force keep going flag, ignoring unique index issue - collection.insert([{name:"Jim"} - , {name:"Sarah", title:"Princess"} - , {name:'Gump', title:"Gump"}], {safe:true, keepGoing:true}, function(err, result) { - - // Count the number of documents left (should not include the duplicates) - collection.count(function(err, count) { - test.equal(3, count); - db.close(); - test.done(); - }) - }); - }); - }); - }); - } else { - db.close(); - test.done(); - } - }); - }); -} - -/** - * @ignore - */ -exports.shouldForceMongoDbServerToAssignId = function(test) { - /// Set up server with custom pk factory - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null), 'forceServerObjectId':true}); - db.open(function(err, client) { - client.createCollection('test_insert2', function(err, r) { - client.collection('test_insert2', function(err, collection) { - - Step( - function inserts() { - var group = this.group(); - - for(var i = 1; i < 1000; i++) { - collection.insert({c:i}, {safe:true}, group()); - } - }, - - function done(err, result) { - collection.insert({a:2}, {safe:true}, function(err, r) { - collection.insert({a:3}, {safe:true}, function(err, r) { - collection.count(function(err, count) { - test.equal(1001, count); - // Locate all the entries using find - collection.find(function(err, cursor) { - cursor.toArray(function(err, results) { - test.equal(1001, results.length); - test.ok(results[0] != null); - - client.close(); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - } - ) - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformSingleInsert = function(test) { - client.createCollection('shouldCorrectlyPerformSingleInsert', function(err, collection) { - collection.insert({a:1}, {safe:true}, function(err, result) { - collection.findOne(function(err, item) { - test.equal(1, item.a); - test.done(); - }) - }) - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformBasicInsert = function(test) { - client.createCollection('test_insert', function(err, r) { - client.collection('test_insert', function(err, collection) { - - Step( - function inserts() { - var group = this.group(); - - for(var i = 1; i < 1000; i++) { - collection.insert({c:i}, {safe:true}, group()); - } - }, - - function done(err, result) { - collection.insert({a:2}, {safe:true}, function(err, r) { - collection.insert({a:3}, {safe:true}, function(err, r) { - collection.count(function(err, count) { - test.equal(1001, count); - // Locate all the entries using find - collection.find(function(err, cursor) { - cursor.toArray(function(err, results) { - test.equal(1001, results.length); - test.ok(results[0] != null); - - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - } - ) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleMultipleDocumentInsert = function(test) { - client.createCollection('test_multiple_insert', function(err, r) { - var collection = client.collection('test_multiple_insert', function(err, collection) { - var docs = [{a:1}, {a:2}]; - - collection.insert(docs, {safe:true}, function(err, ids) { - ids.forEach(function(doc) { - test.ok(((doc['_id']) instanceof ObjectID || Object.prototype.toString.call(doc['_id']) === '[object ObjectID]')); - }); - - // Let's ensure we have both documents - collection.find(function(err, cursor) { - cursor.toArray(function(err, docs) { - test.equal(2, docs.length); - var results = []; - // Check that we have all the results we want - docs.forEach(function(doc) { - if(doc.a == 1 || doc.a == 2) results.push(1); - }); - test.equal(2, results.length); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteSaveInsertUpdate= function(test) { - client.createCollection('shouldCorrectlyExecuteSaveInsertUpdate', function(err, collection) { - collection.save({ email : 'save' }, {safe:true}, function() { - collection.insert({ email : 'insert' }, {safe:true}, function() { - collection.update( - { email : 'update' }, - { email : 'update' }, - { upsert: true, safe:true}, - - function() { - collection.find(function(e, c) { - c.toArray(function(e, a) { - test.equal(3, a.length) - test.done(); - }); - }); - } - ); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertAndRetrieveLargeIntegratedArrayDocument = function(test) { - client.createCollection('test_should_deserialize_large_integrated_array', function(err, collection) { - var doc = {'a':0, - 'b':['tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9', 'tmp10', 'tmp11', 'tmp12', 'tmp13', 'tmp14', 'tmp15', 'tmp16'] - }; - // Insert the collection - collection.insert(doc, {safe:true}, function(err, r) { - // Fetch and check the collection - collection.findOne({'a': 0}, function(err, result) { - test.deepEqual(doc.a, result.a); - test.deepEqual(doc.b, result.b); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertAndRetrieveDocumentWithAllTypes = function(test) { - client.createCollection('test_all_serialization_types', function(err, collection) { - var date = new Date(); - var oid = new ObjectID(); - var string = 'binstring' - var bin = new Binary() - for(var index = 0; index < string.length; index++) { - bin.put(string.charAt(index)) - } - - var motherOfAllDocuments = { - 'string': 'hello', - 'array': [1,2,3], - 'hash': {'a':1, 'b':2}, - 'date': date, - 'oid': oid, - 'binary': bin, - 'int': 42, - 'float': 33.3333, - 'regexp': /regexp/, - 'boolean': true, - 'long': date.getTime(), - 'where': new Code('this.a > i', {i:1}), - 'dbref': new DBRef('namespace', oid, 'integration_tests_') - } - - collection.insert(motherOfAllDocuments, {safe:true}, function(err, docs) { - collection.findOne(function(err, doc) { - // Assert correct deserialization of the values - test.equal(motherOfAllDocuments.string, doc.string); - test.deepEqual(motherOfAllDocuments.array, doc.array); - test.equal(motherOfAllDocuments.hash.a, doc.hash.a); - test.equal(motherOfAllDocuments.hash.b, doc.hash.b); - test.equal(date.getTime(), doc.long); - test.equal(date.toString(), doc.date.toString()); - test.equal(date.getTime(), doc.date.getTime()); - test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString()); - test.equal(motherOfAllDocuments.binary.value(), doc.binary.value()); - - test.equal(motherOfAllDocuments.int, doc.int); - test.equal(motherOfAllDocuments.long, doc.long); - test.equal(motherOfAllDocuments.float, doc.float); - test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString()); - test.equal(motherOfAllDocuments.boolean, doc.boolean); - test.equal(motherOfAllDocuments.where.code, doc.where.code); - test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i); - - test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace); - test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString()); - test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db); - test.done(); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertAndUpdateDocumentWithNewScriptContext= function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, db) { - //convience curried handler for functions of type 'a -> (err, result) - function getResult(callback){ - return function(error, result) { - test.ok(error == null); - return callback(result); - } - }; - - db.collection('users', getResult(function(user_collection){ - user_collection.remove({}, {safe:true}, function(err, result) { - //first, create a user object - var newUser = { name : 'Test Account', settings : {} }; - user_collection.insert([newUser], {safe:true}, getResult(function(users){ - var user = users[0]; - - var scriptCode = "settings.block = []; settings.block.push('test');"; - var context = { settings : { thisOneWorks : "somestring" } }; - - Script.runInNewContext(scriptCode, context, "testScript"); - - //now create update command and issue it - var updateCommand = { $set : context }; - - user_collection.update({_id : user._id}, updateCommand, {safe:true}, - getResult(function(updateCommand) { - // Fetch the object and check that the changes are persisted - user_collection.findOne({_id : user._id}, function(err, doc) { - test.ok(err == null); - test.equal("Test Account", doc.name); - test.equal("somestring", doc.settings.thisOneWorks); - test.equal("test", doc.settings.block[0]); - - // Let's close the db - db.close(); - test.done(); - }); - }) - ); - })); - }); - })); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySerializeDocumentWithAllTypesInNewContext = function(test) { - client.createCollection('test_all_serialization_types_new_context', function(err, collection) { - var date = new Date(); - var scriptCode = - "var string = 'binstring'\n" + - "var bin = new mongo.Binary()\n" + - "for(var index = 0; index < string.length; index++) {\n" + - " bin.put(string.charAt(index))\n" + - "}\n" + - "motherOfAllDocuments['string'] = 'hello';" + - "motherOfAllDocuments['array'] = [1,2,3];" + - "motherOfAllDocuments['hash'] = {'a':1, 'b':2};" + - "motherOfAllDocuments['date'] = date;" + - "motherOfAllDocuments['oid'] = new mongo.ObjectID();" + - "motherOfAllDocuments['binary'] = bin;" + - "motherOfAllDocuments['int'] = 42;" + - "motherOfAllDocuments['float'] = 33.3333;" + - "motherOfAllDocuments['regexp'] = /regexp/;" + - "motherOfAllDocuments['boolean'] = true;" + - "motherOfAllDocuments['long'] = motherOfAllDocuments['date'].getTime();" + - "motherOfAllDocuments['where'] = new mongo.Code('this.a > i', {i:1});" + - "motherOfAllDocuments['dbref'] = new mongo.DBRef('namespace', motherOfAllDocuments['oid'], 'integration_tests_');"; - - var context = { - motherOfAllDocuments : {}, - mongo:{ - ObjectID:ObjectID, - Binary:Binary, - Code:Code, - DBRef:DBRef - }, - date:date}; - - // Execute function in context - Script.runInNewContext(scriptCode, context, "testScript"); - // sys.puts(sys.inspect(context.motherOfAllDocuments)) - var motherOfAllDocuments = context.motherOfAllDocuments; - - collection.insert(context.motherOfAllDocuments, {safe:true}, function(err, docs) { - collection.findOne(function(err, doc) { - // Assert correct deserialization of the values - test.equal(motherOfAllDocuments.string, doc.string); - test.deepEqual(motherOfAllDocuments.array, doc.array); - test.equal(motherOfAllDocuments.hash.a, doc.hash.a); - test.equal(motherOfAllDocuments.hash.b, doc.hash.b); - test.equal(date.getTime(), doc.long); - test.equal(date.toString(), doc.date.toString()); - test.equal(date.getTime(), doc.date.getTime()); - test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString()); - test.equal(motherOfAllDocuments.binary.value(), doc.binary.value()); - - test.equal(motherOfAllDocuments.int, doc.int); - test.equal(motherOfAllDocuments.long, doc.long); - test.equal(motherOfAllDocuments.float, doc.float); - test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString()); - test.equal(motherOfAllDocuments.boolean, doc.boolean); - test.equal(motherOfAllDocuments.where.code, doc.where.code); - test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i); - test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace); - test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString()); - test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db); - - test.done(); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyDoToJsonForLongValue = function(test) { - client.createCollection('test_to_json_for_long', function(err, collection) { - test.ok(collection instanceof Collection); - - collection.insert([{value: Long.fromNumber(32222432)}], {safe:true}, function(err, ids) { - collection.findOne({}, function(err, item) { - test.equal(32222432, item.value); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertAndUpdateWithNoCallback = function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, poolSize: 1, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, client) { - client.createCollection('test_insert_and_update_no_callback', function(err, collection) { - // Insert the update - collection.insert({i:1}, {safe:true}) - // Update the record - collection.update({i:1}, {"$set":{i:2}}, {safe:true}) - - // Make sure we leave enough time for mongodb to record the data - setTimeout(function() { - // Locate document - collection.findOne({}, function(err, item) { - test.equal(2, item.i) - - client.close(); - test.done(); - }); - }, 100) - }) - }); -} - -/** - * @ignore - */ -exports.shouldInsertAndQueryTimestamp = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - db.createCollection('test_insert_and_query_timestamp', function(err, collection) { - // Insert the update - collection.insert({i:Timestamp.fromNumber(100), j:Long.fromNumber(200)}, {safe:true}, function(err, r) { - // Locate document - collection.findOne({}, function(err, item) { - test.ok(item.i instanceof Timestamp); - test.equal(100, item.i); - test.ok(typeof item.j == "number"); - test.equal(200, item.j); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertAndQueryUndefined = function(test) { - client.createCollection('test_insert_and_query_undefined', function(err, collection) { - // Insert the update - collection.insert({i:undefined}, {safe:true}, function(err, r) { - // Locate document - collection.findOne({}, function(err, item) { - test.equal(null, item.i) - - test.done(); - }); - }) - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlySerializeDBRefToJSON = function(test) { - var dbref = new DBRef("foo", ObjectID.createFromHexString("fc24a04d4560531f00000000"), null); - JSON.stringify(dbref); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformSafeInsert = function(test) { - var fixtures = [{ - name: "empty", array: [], bool: false, dict: {}, float: 0.0, string: "" - }, { - name: "not empty", array: [1], bool: true, dict: {x: "y"}, float: 1.0, string: "something" - }, { - name: "simple nested", array: [1, [2, [3]]], bool: true, dict: {x: "y", array: [1,2,3,4], dict: {x: "y", array: [1,2,3,4]}}, float: 1.5, string: "something simply nested" - }]; - - - client.createCollection('test_safe_insert', function(err, collection) { - Step( - function inserts() { - var group = this.group(); - - for(var i = 0; i < fixtures.length; i++) { - collection.insert(fixtures[i], {safe:true}, group()); - } - }, - - function done() { - collection.count(function(err, count) { - test.equal(3, count); - - collection.find().toArray(function(err, docs) { - test.equal(3, docs.length) - }); - }); - - - collection.find({}, {}, function(err, cursor) { - var counter = 0; - - cursor.each(function(err, doc) { - if(doc == null) { - test.equal(3, counter); - test.done(); - } else { - counter = counter + 1; - } - }); - }); - } - ) - }) -} - -/** - * @ignore - */ -exports.shouldThrowErrorIfSerializingFunction = function(test) { - client.createCollection('test_should_throw_error_if_serializing_function', function(err, collection) { - var func = function() { return 1}; - // Insert the update - collection.insert({i:1, z:func }, {safe:true, serializeFunctions:true}, function(err, result) { - collection.findOne({_id:result[0]._id}, function(err, object) { - test.equal(func.toString(), object.z.code); - test.equal(1, object.i); - test.done(); - }) - }) - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertDocumentWithUUID = function(test) { - client.collection("insert_doc_with_uuid", function(err, collection) { - collection.insert({_id : "12345678123456781234567812345678", field: '1'}, {safe:true}, function(err, result) { - test.equal(null, err); - - collection.find({_id : "12345678123456781234567812345678"}).toArray(function(err, items) { - test.equal(null, err); - test.equal(items[0]._id, "12345678123456781234567812345678") - test.equal(items[0].field, '1') - - // Generate a binary id - var binaryUUID = new Binary('00000078123456781234567812345678', Binary.SUBTYPE_UUID); - - collection.insert({_id : binaryUUID, field: '2'}, {safe:true}, function(err, result) { - collection.find({_id : binaryUUID}).toArray(function(err, items) { - test.equal(null, err); - test.equal(items[0].field, '2') - test.done(); - }); - }); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCallCallbackWithDbDriverInStrictMode = function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, poolSize: 1, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, client) { - client.createCollection('test_insert_and_update_no_callback_strict', function(err, collection) { - collection.insert({_id : "12345678123456781234567812345678", field: '1'}, {safe:true}, function(err, result) { - test.equal(null, err); - - collection.update({ '_id': "12345678123456781234567812345678" }, { '$set': { 'field': 0 }}, function(err, numberOfUpdates) { - test.equal(null, err); - test.equal(1, numberOfUpdates); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertDBRefWithDbNotDefined = function(test) { - client.createCollection('shouldCorrectlyInsertDBRefWithDbNotDefined', function(err, collection) { - var doc = {_id: new ObjectID()}; - var doc2 = {_id: new ObjectID()}; - var doc3 = {_id: new ObjectID()}; - collection.insert(doc, {safe:true}, function(err, result) { - // Create object with dbref - doc2.ref = new DBRef('shouldCorrectlyInsertDBRefWithDbNotDefined', doc._id); - doc3.ref = new DBRef('shouldCorrectlyInsertDBRefWithDbNotDefined', doc._id, MONGODB); - - collection.insert([doc2, doc3], {safe:true}, function(err, result) { - // Get all items - collection.find().toArray(function(err, items) { - test.equal("shouldCorrectlyInsertDBRefWithDbNotDefined", items[1].ref.namespace); - test.equal(doc._id.toString(), items[1].ref.oid.toString()); - test.equal(null, items[1].ref.db); - - test.equal("shouldCorrectlyInsertDBRefWithDbNotDefined", items[2].ref.namespace); - test.equal(doc._id.toString(), items[2].ref.oid.toString()); - test.equal(MONGODB, items[2].ref.db); - - test.done(); - }) - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertUpdateRemoveWithNoOptions = function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, db) { - db.collection('shouldCorrectlyInsertUpdateRemoveWithNoOptions', function(err, collection) { - collection.insert({a:1}); - collection.update({a:1}, {a:2}); - collection.remove({a:2}); - - collection.count(function(err, count) { - test.equal(0, count); - - db.close(); - test.done(); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteMultipleFetches = function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Search parameter - var to = 'ralph' - // Execute query - db.open(function(err, db) { - db.collection('shouldCorrectlyExecuteMultipleFetches', function(err, collection) { - collection.insert({addresses:{localPart:'ralph'}}, {safe:true}, function(err, result) { - // Let's find our user - collection.findOne({"addresses.localPart" : to}, function( err, doc ) { - test.equal(null, err); - test.equal(to, doc.addresses.localPart); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyFailWhenNoObjectToUpdate= function(test) { - client.createCollection('shouldCorrectlyExecuteSaveInsertUpdate', function(err, collection) { - collection.update({_id : new ObjectID()}, { email : 'update' }, {safe:true}, - function(err, result) { - test.equal(0, result); - test.done(); - } - ); - }); -} - -/** - * @ignore - */ -exports['Should correctly insert object and retrieve it when containing array and IsoDate'] = function(test) { - var doc = { - "_id" : new ObjectID("4e886e687ff7ef5e00000162"), - "str" : "foreign", - "type" : 2, - "timestamp" : ISODate("2011-10-02T14:00:08.383Z"), - "links" : [ - "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" - ] - } - - client.createCollection('Should_correctly_insert_object_and_retrieve_it_when_containing_array_and_IsoDate', function(err, collection) { - collection.insert(doc, {safe:true}, function(err, result) { - test.ok(err == null); - - collection.findOne(function(err, item) { - test.ok(err == null); - test.deepEqual(doc, item); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly insert object with timestamps'] = function(test) { - var doc = { - "_id" : new ObjectID("4e886e687ff7ef5e00000162"), - "str" : "foreign", - "type" : 2, - "timestamp" : new Timestamp(10000), - "links" : [ - "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" - ], - "timestamp2" : new Timestamp(33333), - } - - client.createCollection('Should_correctly_insert_object_with_timestamps', function(err, collection) { - collection.insert(doc, {safe:true}, function(err, result) { - test.ok(err == null); - - collection.findOne(function(err, item) { - test.ok(err == null); - test.deepEqual(doc, item); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should fail on insert due to key starting with $'] = function(test) { - var doc = { - "_id" : new ObjectID("4e886e687ff7ef5e00000162"), - "$key" : "foreign", - } - - client.createCollection('Should_fail_on_insert_due_to_key_starting_with', function(err, collection) { - collection.insert(doc, {safe:true}, function(err, result) { - test.ok(err != null); - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly allow for control of serialization of functions on command level'] = function(test) { - var doc = { - str : "String", - func : function() {} - } - - client.createCollection("Should_Correctly_allow_for_control_of_serialization_of_functions_on_command_level", function(err, collection) { - test.ok(err == null); - - collection.insert(doc, {safe:true}, function(err, result) { - - collection.update({str:"String"}, {$set:{c:1, d:function(){}}}, {safe:true, serializeFunctions:false}, function(err, result) { - test.equal(1, result); - - collection.findOne({str:"String"}, function(err, item) { - test.equal(null, item.d); - - // Execute a safe insert with replication to two servers - collection.findAndModify({str:"String"}, [['a', 1]], {'$set':{'f':function() {}}}, {new:true, safe: true, serializeFunctions:true}, function(err, result) { - test.ok(result.f instanceof Code) - test.done(); - }) - }) - }) - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly allow for control of serialization of functions on collection level'] = function(test) { - var doc = { - str : "String", - func : function() {} - } - - client.createCollection("Should_Correctly_allow_for_control_of_serialization_of_functions_on_collection_level", {serializeFunctions:true}, function(err, collection) { - test.ok(err == null); - - collection.insert(doc, {safe:true}, function(err, result) { - test.equal(null, err); - - collection.findOne({str : "String"}, function(err, item) { - test.ok(item.func instanceof Code); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly allow for using a Date object as _id'] = function(test) { - var doc = { - _id : new Date(), - str : 'hello' - } - - client.createCollection("Should_Correctly_allow_for_using_a_Date_object_as__id", {serializeFunctions:true}, function(err, collection) { - test.ok(err == null); - - collection.insert(doc, {safe:true}, function(err, result) { - test.equal(null, err); - - collection.findOne({str : "hello"}, function(err, item) { - test.ok(item._id instanceof Date); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly fail to update returning 0 results'] = function(test) { - client.createCollection("Should_Correctly_fail_to_update_returning_0_results", {serializeFunctions:true}, function(err, collection) { - test.ok(err == null); - - collection.update({a:1}, {$set: {a:1}}, {safe:true}, function(err, numberOfUpdated) { - test.equal(0, numberOfUpdated); - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly update two fields including a sub field'] = function(test) { - var doc = { - _id: new ObjectID(), - Prop1: 'p1', - Prop2: 'p2', - More: { - Sub1: 's1', - Sub2: 's2', - Sub3: 's3' - } - } - - client.createCollection("Should_Correctly_update_two_fields_including_a_sub_field", {}, function(err, collection) { - collection.insert(doc, {safe:true}, function(err, result) { - test.equal(null, err); - - // Update two fields - collection.update({_id:doc._id}, {$set:{Prop1:'p1_2', 'More.Sub2':'s2_2'}}, {safe:true}, function(err, numberOfUpdatedDocs) { - test.equal(null, err); - test.equal(1, numberOfUpdatedDocs); - - collection.findOne({_id:doc._id}, function(err, item) { - test.equal(null, err); - test.equal('p1_2', item.Prop1); - test.equal('s2_2', item.More.Sub2); - test.done(); - }) - }); - }) - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/logging_test.js b/node_modules/mongodb/test/logging_test.js deleted file mode 100644 index 2094c8d..0000000 --- a/node_modules/mongodb/test/logging_test.js +++ /dev/null @@ -1,93 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlyLogContent = function(test) { - var loggedOutput = false; - var logger = { - doDebug:true, - doError:true, - doLog:true, - - error:function(message, object) {}, - log:function(message, object) {}, - - debug:function(message, object) { - loggedOutput = true; - } - } - - var automatic_connect_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null), retryMiliSeconds:50, logger:logger}); - automatic_connect_client.open(function(err, automatic_connect_client) { - automatic_connect_client.close(); - test.equal(true, loggedOutput); - test.done(); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/manual_tests/grids_fs_compatibility_test.js b/node_modules/mongodb/test/manual_tests/grids_fs_compatibility_test.js deleted file mode 100644 index 4f1f738..0000000 --- a/node_modules/mongodb/test/manual_tests/grids_fs_compatibility_test.js +++ /dev/null @@ -1,20 +0,0 @@ -var Server = require("../../lib/mongodb").Server, - Db = require("../../lib/mongodb").Db, - ObjectID = require("../../lib/mongodb").ObjectID, - GridStore = require("../../lib/mongodb").GridStore; - -var options = { - auto_reconnect: true, - poolSize: 1, - socketOptions: { timeout:8000 } -}; - -var db = new Db("data", new Server( 'localhost', 27017, options)); -db.open(function(err, client){ - var id = new ObjectID(); - // Write a file into gridfs and then verify that it's readable - var gridStore = new GridStore(client, 'manual_test.jpg', "w"); - gridStore.writeFile('/Users/christiankvalheim/coding/projects/node-mongodb-native/test/gridstore/iya_logo_final_bw.jpg', function(err, result) { - db.close(); - }) -}); \ No newline at end of file diff --git a/node_modules/mongodb/test/manual_tests/hanging_queries_test.js b/node_modules/mongodb/test/manual_tests/hanging_queries_test.js deleted file mode 100644 index 09ac425..0000000 --- a/node_modules/mongodb/test/manual_tests/hanging_queries_test.js +++ /dev/null @@ -1,182 +0,0 @@ -var ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager; - -var mongo = require('../../lib/mongodb'), - // website = new mongo.Db('simplereach_website_production', new mongo.Server('localhost', 27017, {auto_reconnect:true, poolSize:5})), - // adserver = new mongo.Db('adserver', new mongo.Server('localhost', 27017, {auto_reconnect:true, poolSize:5})), - accounts = [], accountsCollection, contentCollection, count = 0; - -RS = new ReplicaSetManager({retries:120, secondary_count:1, passive_count:0, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new mongo.ReplSetServers( [ - new mongo.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongo.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongo.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, read_secondary:true, readPreference:mongo.Server.READ_SECONDARY_ONLY} - ); - - // Replica configuration - var replSet2 = new mongo.ReplSetServers( [ - new mongo.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongo.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongo.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, read_secondary:true, readPreference:mongo.Server.READ_SECONDARY_ONLY} - ); - - var adserver = new mongo.Db('adserver', replSet); - var website = new mongo.Db('simplereach_website_production', replSet2); - - website.on('error', function(err){ - console.log(err); process.exit(1); - }); - - adserver.on('error', function(err){ - console.log(err); process.exit(1); - }); - - /** - * loads content for accounts in the array - */ - function loadContent(){ - var account = accounts.shift(); - fields = ['account_id','avg_ctr','cat','channels','ckw','ctr','published','topics','url', 'updated_at', 'disabled'], - sort = [['published','desc']], - criteria = { account_id:account, $or:[ { end_date: null }, { end_date:{ $gte:new Date() }} ]}; - - if(account === undefined){ - process.exit(1); - // no more accounts to process - // the return here goes into limbo - return; - } - console.log('GETTING CONTENT'); - contentCollection.find(criteria, {fields:fields, limit:100000, sort:sort}, function(err, cursor){ - - cursor.each(function(err, doc) { - if(err){ console.log(err); process.exit(1); } - if(doc === null){ - //once this account is done, load the next - console.log('FINISHED ACCOUNT', account, 'WITH', count, 'ITEMS'); - count = 0; - process.nextTick(function() { - loadContent(); - }) - } else { - count += 1; - } - }); - }); - } - - /** - * loads content for accounts in the array - */ - function loadContentParallel(account, callback){ - var fields = ['account_id','avg_ctr','cat','channels','ckw','ctr','published','topics','url', 'updated_at', 'disabled'], - sort = [['published','desc']], - criteria = { account_id:account, $or:[ { end_date: null }, { end_date:{ $gte:new Date() }} ]}; - - if(account === undefined){ - process.exit(1); - - // no more accounts to process - // the return here goes into limbo - return; - } - console.log('GETTING CONTENT'); - contentCollection.find(criteria, {fields:fields, limit:100000, sort:sort}, function(err, cursor){ - cursor.each(function(err, doc) { - if(err){ - return callback(err, account); - } - - if(doc === null){ - //once this account is done, load the next - console.log('FINISHED ACCOUNT', account, 'WITH', count, 'ITEMS'); - count = 0; - callback(null, account); - } else { - count += 1; - } - }); - }); - } - - /** - * Loads account ids and pushes them onto an array - **/ - function loadAccountsParallel(){ - accountsCollection.find({active:{$ne:null}}, { fields:{'_id':1, 'a':1}}).toArray(function(err, accounts) { - // keep track of the number of accounts - var numberOfFinishedAccount = accounts.length; - - for(var i = 0; i < accounts.length; i++) { - loadContentParallel(accounts[i].a, function(err, result) { - numberOfFinishedAccount = numberOfFinishedAccount - 1; - - if(numberOfFinishedAccount == 0) process.exit(0); - }); - } - }); - } - - /** - * Loads account ids and pushes them onto an array - **/ - function loadAccounts(){ - accountsCollection.find({active:{$ne:null}}, { fields:{'_id':1, 'a':1}}, function(err, cursor) { - if(err){ console.log(err); process.exit(1); } - console.log('GETTING ACCOUNTS'); - cursor.each(function(err, doc){ - if(err){ console.log(err); process.exit(1); } - if(doc !== null){ - accounts.push(doc.a); - } else { - console.log('FOUND', accounts.length, 'ACCOUNTS'); - loadContent(); - } - }); - }); - } - - console.log('OPENING CONNECTION TO WEBSITE'); - website.open(function(err, wsClient){ - if(err){console.log(err); process.exit(1); } - console.log('OPENING CONNECTION TO ADSERVER'); - adserver.open(function(err, asClient){ - if(err){ console.log(err); process.exit(1); } - - // Get collections and remove the content - accountsCollection = asClient.collection('accounts'); - accountsCollection.remove(); - - contentCollection = asClient.collection('content'); - contentCollection.remove(); - - // insert a bunch of account docs to trigger flows - var accountDocs = []; - for(var i = 0; i < 1000; i++) { - accountDocs.push({a:i, active:true}); - } - - // insert a bunch of account docs to trigger flows - var contentDocs = []; - for(var i = 0; i < 1000; i++) { - var a_id = Math.floor(Math.random()*1000); - contentDocs.push({a:1, end_date:null, account_id:a_id}); - } - - // Just insert some test data - accountsCollection.insert(accountDocs, {safe:{w:2, wtimout:1000}}, function(err, r) { - contentCollection.insert(contentDocs, {safe:{w:2, wtimout:1000}}, function(err, r) { - // process.exit(0); - loadAccounts(); - // loadAccountsParallel(); - }); - }); - }); - }); -}); - diff --git a/node_modules/mongodb/test/manual_tests/issue_replicaset_test.js b/node_modules/mongodb/test/manual_tests/issue_replicaset_test.js deleted file mode 100644 index ed5692b..0000000 --- a/node_modules/mongodb/test/manual_tests/issue_replicaset_test.js +++ /dev/null @@ -1,43 +0,0 @@ -var mongodb = require("../../lib/mongodb"), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 4, - socketOptions: { keepAlive: 100, timeout:6000 } -}; - -var userObjects = []; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({'user_id':i}); -} - -// Manual config -// mongod --rest --replSet mlocal --oplogSize 8 --dbpath=./d1 -// mongod --port 27018 --rest --replSet mlocal --dbpath=./d2 -// mongod --port=27019 --rest --replSet mlocal --dbpath=./d3 -// {"_id" : "mlocal", "members" : [{"_id" : 0,"host" : "localhost:27017"},{"_id" : 1,"host" : "localhost:27018"},{"_id" : 2,"host" : "localhost:27019","arbiterOnly" : true}]} - -// Replica configuration -var replSet = new mongodb.ReplSetServers( [ - new mongodb.Server( 'localhost', 27017, { auto_reconnect: true } ), - new mongodb.Server( 'localhost', 27018, { auto_reconnect: true } ), - new mongodb.Server( 'localhost', 27019, { auto_reconnect: true } ) - ], - {rs_name:'mlocal'} -); - -var queryCount = 0; -var users; -var db = new mongodb.Db("data", replSet); -db.on("error", function(err) { - console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") - console.dir(err) -}) - -db.open(function(err, client){ - // Just close the connection - db.close(); -}); diff --git a/node_modules/mongodb/test/manual_tests/manual_larger_queries.js b/node_modules/mongodb/test/manual_tests/manual_larger_queries.js deleted file mode 100644 index 09aceeb..0000000 --- a/node_modules/mongodb/test/manual_tests/manual_larger_queries.js +++ /dev/null @@ -1,137 +0,0 @@ -var mongodb = require("../../lib/mongodb"), - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 4, - socketOptions: { keepAlive: 100, timeout:30000 } -}; - -var userObjects = []; -var counter = 0; -var counter2 = 0; -var maxUserId = 10000; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({a:true, b:true}); -} - -RS = new ReplicaSetManager({retries:120, secondary_count:1, passive_count:0, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new mongodb.ReplSetServers( [ - new mongodb.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, read_secondary:true, readPreference:mongodb.Server.READ_SECONDARY} - ); - - var collA; - var collB; - - var db = new mongodb.Db("data", replSet); - db.open(function(err, client){ - console.log("Connected"); - if(err != null) { - console.dir(err); - return; - } - - var userCollection = client.collection('users'); - var accountCollection = client.collection('accounts'); - - // Generate a bunch of fake accounts - var accountDocs = []; - for(var i = 0; i < 10000; i++) { - accountDocs.push({ - account_id:i, - 'somedata': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata2': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata3': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata4': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata5': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata6': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata7': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata8': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata9': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad' - }) - } - - // Generate a bunch of false users - var userDocs = []; - for(var i = 0; i < maxUserId; i++) { - // Generate a random number of account ids - var numberOfAccounts = Math.floor(Math.random(10000)); - // Generate an array of random numbers - var accountIds = []; - for(var j = 0; j < numberOfAccounts; j++) { - numberOfAccounts.push(Math.floor(Math.random(10000))); - } - - // Generate a user - userDocs.push({ - user_id:i, - ids:accountIds, - 'somedata': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata2': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata3': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata4': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata5': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata6': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata7': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata8': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata9': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad' - }) - } - - // Insert all the docs - userCollection.insert(userDocs, {safe:true}, function(err, result) { - console.dir(err); - - accountCollection.insert(accountDocs, {safe:true}, function(err, result) { - console.dir(err); - - var timeoutFunc = function() { - lookup(function(err, result) { - console.log("-------------------------------------------- lookedup :: " + counter); - counter = counter + 1; - process.nextTick(timeoutFunc, 1); - }); - } - - process.nextTick(timeoutFunc, 1); - }); - }); - }); - - function lookup(cb){ - // Locate a random user - db.collection('users', function(err, userCollection) { - - userCollection.findOne({user_id:Math.floor(Math.random(maxUserId))}, function(err, user) { - if(err == null && user != null) { - console.log("-------------------------------------------- findOne"); - - // Fetch all the accounts - db.collection('accounts', function(err, accountCollection) { - - accountCollection.find({account_id:{$in:user.ids}}).toArray(function(err, accounts) { - if(err == null && accounts != null) { - console.log("-------------------------------------------- findAccounts :: " + accounts.length); - cb(null, null); - } else { - console.log("-------------------------------------------- findAccounts ERROR"); - cb(err, null); - } - }); - }); - } else { - console.log("-------------------------------------------- findOne ERROR"); - cb(err, null); - } - }); - }); - } -}); \ No newline at end of file diff --git a/node_modules/mongodb/test/manual_tests/manual_lock.js b/node_modules/mongodb/test/manual_tests/manual_lock.js deleted file mode 100644 index 33da8be..0000000 --- a/node_modules/mongodb/test/manual_tests/manual_lock.js +++ /dev/null @@ -1,84 +0,0 @@ -var mongodb = require("../../lib/mongodb"), - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 4, - socketOptions: { keepAlive: 100, timeout:30000 } -}; - -var userObjects = []; -var counter = 0; -var counter2 = 0; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({a:true, b:true}); -} - -RS = new ReplicaSetManager({retries:120, secondary_count:1, passive_count:0, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new mongodb.ReplSetServers( [ - new mongodb.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var collA; - var collB; - - var db = new mongodb.Db("data", replSet); - db.open(function(err, client){ - console.log("Connected"); - client.collection("collA", function(err, coll){ - collA = coll; - - coll.insert(userObjects, {safe:true}, function(err, result) { - - client.collection("collB", function(err, coll){ - collB = coll; - - coll.insert(userObjects, {safe:true}, function(err, result) { - - var timeoutFunc = function() { - lookup(function(err, result) { - console.log("-------------------------------------------- lookedup") - process.nextTick(timeoutFunc, 1); - }) - } - - process.nextTick(timeoutFunc, 1); - }); - }); - }); - }); - }); - - function lookup(cb){ - var a, b; - var waiting = 2; - - collA.findOne({ a: true }, function(err, result){ - a = result; - waiting--; - if(waiting === 0){ - console.log("---------------------------------------------------------------------- collA :: " + counter); - counter = counter + 1; - cb(null, [a, b]); - } - }); - - collB.findOne({ b: true }, function(err, result){ - b = result; - waiting--; - if(waiting === 0){ - console.log("---------------------------------------------------------------------- collB :: " + counter); - counter = counter + 1; - cb(null, [a, b]); - } - }); - } -}); \ No newline at end of file diff --git a/node_modules/mongodb/test/manual_tests/replicaset_test.js b/node_modules/mongodb/test/manual_tests/replicaset_test.js deleted file mode 100644 index fc61965..0000000 --- a/node_modules/mongodb/test/manual_tests/replicaset_test.js +++ /dev/null @@ -1,70 +0,0 @@ -var mongodb = require("../../lib/mongodb"), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 4, - socketOptions: { keepAlive: 100, timeout:6000 } -}; - -var userObjects = []; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({'user_id':i}); -} - -RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new mongodb.ReplSetServers( [ - new mongodb.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var queryCount = 0; - var users; - var db = new mongodb.Db("data", replSet); - db.on("error", function(err) { - console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") - console.dir(err) - }) - - db.open(function(err, client){ - if(err){ - console.log("[%s] %s", new Date, err.stack || err); - return; - } - - if(users){ - console.log("[%s] Reconnected?!", new Date); - return; - } - - client.collection("users", function(err, coll){ - coll.insert(userObjects, {safe:true}, function(err, result) { - users = coll; - query(); - }) - }); - }); - - function query(){ - var current = queryCount++; - console.log("[%s] #%s querying all users", new Date, current); - // setTimeout(query, 32 * 1000); - setTimeout(query, 7 * 1000); - users.find().count(function(err, all){ - if(err){ - console.log("[%s] #%s %s", new Date, current, err.stack || err); - }else{ - console.log("[%s] #%s found %s users", new Date, current, all); - } - }); - } -}); - - diff --git a/node_modules/mongodb/test/manual_tests/server_load.js b/node_modules/mongodb/test/manual_tests/server_load.js deleted file mode 100644 index 5640234..0000000 --- a/node_modules/mongodb/test/manual_tests/server_load.js +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env node -var mongo = require("../../lib/mongodb"); -var express = require("express"); -var ObjectID = mongo.ObjectID; -var DBRef = mongo.DBRef; -var util = require("util"); - -var app = express.createServer(); - -app.configure(function() { - app.set('dbconnection', { - "port": 27017, - "host": "localhost" - }); -}); - -app.renderResponse = function(res, err, data, allCount) { - res.header('Content-Type', 'application/json'); - - if(err == null) { - if(typeof allCount == "undefined") { - res.send({data: data, success: true}); - } else { - res.send({allCount: allCount, data: data, success: true}); - } - } else { - util.log(util.inspect(err)); - console.log(err.stack); - res.send({success: false, error:err.message}); - } -}; - -app.use(express.bodyParser()); -app.use(app.router); -app.use(express.logger()); -app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); - -var isISO8601 = function(dString) { - var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))?/; - if (dString.toString().match(new RegExp(regexp))) { - return true; - } - else - { - return false; - } -}; - - -var decodeField = function(value) { - if(value == null) - return null; - - if(typeof value == "object" && value['namespace'] && value['oid']) { - if(/^[0-9a-fA-F]{24}$/.test(value['oid'])) - return new DBRef(value['namespace'], new ObjectID(value['oid'])); - else - return new DBRef(value['namespace'], value['oid']); - } - - if(isISO8601(value)) - return new Date(value); - - return value; -}; - -var deepDecode = function(obj) { - for(var i in obj) - { - if(obj[i] == null) { - // do nothing - } - else if(i == "_id" && /^[0-9a-fA-F]{24}$/.test(obj[i])) { - obj[i] = new ObjectID(obj[i]); - } - else if(typeof obj[i] == "object" && typeof obj[i]['namespace'] == "undefined" && typeof obj[i]['oid'] == "undefined") { - deepDecode(obj[i]); - } - else { - obj[i] = decodeField(obj[i]); - } - } -}; - -db = null; -var openConnection = function(dbname, config, callback) { - if(db) { - callback(null, db); - } - else { - var target; - target = new mongo.Server(config.host, config.port, {'auto_reconnect':true, 'poolSize':4}); - db = new mongo.Db(dbname, target, {native_parser:false}); - db.open(callback); - } -} - -var listCommand = function (target, spec, options, next){ - deepDecode(spec); - openConnection(target.db, target.connection, function(err,db) { - if(err) { next(err); return; } - // open collection - db.collection(target.collection, function(err, collection) { - - if(spec._id) { - collection.findOne(spec, options, function(err, doc){ - next(err, doc); - }); - } - else - { - // console.dir(options) - options['limit'] = 10; - - collection.find(spec, options, function(err, cursor) - { - - cursor.toArray(function(err, docs) - { - next(err, docs); - //db.close(); - }); - }); - } - }); - }); -} - -app.get('/:db/:collection/:id?', function(req, res, next) -{ - var spec = req.query.query? JSON.parse(req.query.query) : {}; - spec = req.query.spec? JSON.parse(req.query.spec) : spec; - - if(req.params.id) - spec._id = req.params.id; - - // JSON decode options - var options = req.query.options?JSON.parse(req.query.options) : {}; - - listCommand({ - connection: app.set("dbconnection"), - db: req.params.db, - collection: req.params.collection - }, - spec, - options, - function(err, docs, allCount) { - app.renderResponse(res, err, docs, allCount); - }); -}); - -app.listen(9999, '127.0.0.1'); \ No newline at end of file diff --git a/node_modules/mongodb/test/manual_tests/simple_test.js b/node_modules/mongodb/test/manual_tests/simple_test.js deleted file mode 100644 index 55b561e..0000000 --- a/node_modules/mongodb/test/manual_tests/simple_test.js +++ /dev/null @@ -1,23 +0,0 @@ -var Db = require('../../lib/mongodb').Db, - Server = require('../../lib/mongodb').Server; - -var _db = new Db('mydb', new Server('localhost', 27017, {auto_reconnect: true, poolSize: 2})); -_db.open(function(err, db) { - - db.collection('coll1', function(err, coll) { - var expireDate = new Date(); - expireDate.setHours(expireDate.getHours() + 24); - coll.remove({valid_to: {$lt: expireDate}}, {safe: true}, function(err) { - console.log('Deleted the items'); - }); - }); - - db.collection('coll2', function(err, coll) { - coll.find({}, {}, function(err, cursor) { - console.log('Turning the cursor into an array'); - cursor.toArray(function(err, docs) { - console.log('Got the array'); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/mongodb/test/manual_tests/single_test.js b/node_modules/mongodb/test/manual_tests/single_test.js deleted file mode 100644 index 662b921..0000000 --- a/node_modules/mongodb/test/manual_tests/single_test.js +++ /dev/null @@ -1,61 +0,0 @@ -var mongodb = require("../../lib/mongodb"), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 1, - // socketOptions: { keepAlive: 100, timeout:8000 } - socketOptions: { timeout:8000 } -}; - -var userObjects = []; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({'user_id':i}); -} - -var queryCount = 0; -var replSet = new mongodb.Server( 'localhost', 27017, options); - -var users; -var db = new mongodb.Db("data", replSet); -db.on("error", function(err) { - console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") - console.dir(err) -}) - -db.open(function(err, client){ - if(err){ - console.log("[%s] %s", new Date, err.stack || err); - return; - } - - if(users){ - console.log("[%s] Reconnected?!", new Date); - return; - } - - client.collection("users", function(err, coll){ - coll.remove({}, {safe:true}, function(err) { - coll.insert(userObjects, {safe:true}, function(err, result) { - users = coll; - query(); - }) - }); - }); -}); - -function query(){ - var current = queryCount++; - console.log("[%s] #%s querying all users", new Date, current); - // setTimeout(query, 32 * 1000); - setTimeout(query, 7 * 1000); - users.find().count(function(err, all){ - if(err){ - console.log("[%s] #%s %s", new Date, current, err.stack || err); - }else{ - console.log("[%s] #%s found %s users", new Date, current, all); - } - }); -} \ No newline at end of file diff --git a/node_modules/mongodb/test/manual_tests/test.js b/node_modules/mongodb/test/manual_tests/test.js deleted file mode 100644 index 006668b..0000000 --- a/node_modules/mongodb/test/manual_tests/test.js +++ /dev/null @@ -1,83 +0,0 @@ -var mongodb = require("./lib/mongodb"), - ReplicaSetManager = require('./test/tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 4, - socketOptions: { keepAlive: 100, timeout:30000 } -}; - -var userObjects = []; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({'user_id':i}); -} - -// var replSet = new mongodb.ReplSetServers([ -// new mongodb.Server("mongo-1", 27017, options), -// new mongodb.Server("mongo-2", 27017, options), -// new mongodb.Server("mongo-3", 27017, options) -// ]); - -RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new mongodb.ReplSetServers( [ - new mongodb.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - // {rs_name:RS.name, strategy:'ping'} - // {rs_name:RS.name, strategy:'statistical'} - ); - - var users; - var db = new mongodb.Db("data", replSet); - db.open(function(err, client){ - if(err){ - console.log("[%s] %s", new Date, err.stack || err); - return; - } - - if(users){ - console.log("[%s] Reconnected?!", new Date); - return; - } - - client.collection("users", function(err, coll){ - console.log("Connected"); - coll.insert(userObjects, {safe:true}, function(err, result) { - users = coll; - query(); - }) - }); - // client.collection("users", function(err, users){ - // console.log("Connected"); - // db.users = users; - // query(); - // }); - }); - - function query(){ - console.log("[%s] querying all users", new Date); - // setTimeout(query, 70 * 60 * 1000); - setTimeout(query, 32 * 1000); - db.collection('users', function(err, coll) { - if(err){ - console.log("[0] :: [%s] %s", new Date, err.stack || err); - } - - coll.find().count(function(err, all){ - if(err){ - console.log("[1] :: [%s] %s", new Date, err.stack || err); - }else{ - console.log("[2] :: [%s] found %s users", new Date, all); - } - }); - }) - } -}); - - diff --git a/node_modules/mongodb/test/map_reduce_test.js b/node_modules/mongodb/test/map_reduce_test.js deleted file mode 100644 index 032f4d8..0000000 --- a/node_modules/mongodb/test/map_reduce_test.js +++ /dev/null @@ -1,517 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Code = require('../lib/mongodb/bson/code').Code, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A whole lot of different wayt to execute the group command - * - * @_class collection - * @_function group - */ -exports.shouldCorrectlyExecuteGroupFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection - db.createCollection('test_group', function(err, collection) { - - // Peform a simple group by on an empty collection - collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) { - test.deepEqual([], results); - - // Trigger some inserts on the collection - collection.insert([{'a':2}, {'b':5}, {'a':1}], {safe:true}, function(err, ids) { - - // Perform a group count - collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }" - , function(err, results) { - test.equal(3, results[0].count); - - // Pefrom a group count using the eval method - collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }" - , false, function(err, results) { - test.equal(3, results[0].count); - - // Group with a conditional - collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }" - , function(err, results) { - // Results - test.equal(1, results[0].count); - - // Group with a conditional using the EVAL method - collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }" - , false, function(err, results) { - // Results - test.equal(1, results[0].count); - - // Insert some more test data - collection.insert([{'a':2}, {'b':3}], {safe:true}, function(err, ids) { - - // Do a Group by field a - collection.group(['a'], {}, {"count":0}, "function (obj, prev) { prev.count++; }" - , function(err, results) { - // Results - test.equal(2, results[0].a); - test.equal(2, results[0].count); - test.equal(null, results[1].a); - test.equal(2, results[1].count); - test.equal(1, results[2].a); - test.equal(1, results[2].count); - - // Do a Group by field a - collection.group({'a':true}, {}, {"count":0}, function (obj, prev) { prev.count++; } - , true, function(err, results) { - // Results - test.equal(2, results[0].a); - test.equal(2, results[0].count); - test.equal(null, results[1].a); - test.equal(2, results[1].count); - test.equal(1, results[2].a); - test.equal(1, results[2].count); - - // Correctly handle illegal function - collection.group([], {}, {}, "5 ++ 5", function(err, results) { - test.ok(err instanceof Error); - test.ok(err.message != null); - - // Use a function to select the keys used to group by - var keyf = function(doc) { return {a: doc.a}; }; - collection.group(keyf, {a: {$gt: 0}}, {"count": 0, "value": 0} - , function(obj, prev) { prev.count++; prev.value += obj.a; }, true, function(err, results) { - // Results - results.sort(function(a, b) { return b.count - a.count; }); - test.equal(2, results[0].count); - test.equal(2, results[0].a); - test.equal(4, results[0].value); - test.equal(1, results[1].count); - test.equal(1, results[1].a); - test.equal(1, results[1].value); - - // Correctly handle illegal function when using the EVAL method - collection.group([], {}, {}, "5 ++ 5", false, function(err, results) { - test.ok(err instanceof Error); - test.ok(err.message != null); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldCorrectlyExecuteGroupFunctionWithFinalizeFunction = function(test) { - client.createCollection('test_group2', function(err, collection) { - collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", true, function(err, results) { - test.deepEqual([], results); - - // Trigger some inserts - collection.insert([{'a':2}, {'b':5, 'a':0}, {'a':1}, {'c':2, 'a':0}], {safe:true}, function(err, ids) { - collection.group([], {}, {count: 0, running_average: 0} - , function (doc, out) { - out.count++; - out.running_average += doc.a; - } - , function(out) { - out.average = out.running_average / out.count; - }, true, function(err, results) { - test.equal(3, results[0].running_average) - test.equal(0.75, results[0].average) - test.done(); - }); - }); - }); - }); -} - -/** - * A simple map reduce example - * - * @_class collection - * @_function mapReduce - */ -exports.shouldPerformSimpleMapReduceFunctions = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection - db.createCollection('test_map_reduce_functions', function(err, collection) { - - // Insert some documents to perform map reduce over - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - - // Map function - var map = function() { emit(this.user_id, 1); }; - // Reduce function - var reduce = function(k,vals) { return 1; }; - - // Peform the map reduce - collection.mapReduce(map, reduce, function(err, collection) { - // Mapreduce returns the temporary collection with the results - collection.findOne({'_id':1}, function(err, result) { - test.equal(1, result.value); - - collection.findOne({'_id':2}, function(err, result) { - test.equal(1, result.value); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple map reduce example using the inline output type on MongoDB > 1.7.6 - * - * @_class collection - * @_function mapReduce - */ -exports.shouldPerformMapReduceFunctionInline = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Parse version of server if available - db.admin().serverInfo(function(err, result){ - - // Only run if the MongoDB version is higher than 1.7.6 - if(parseInt((result.version.replace(/\./g, ''))) >= 176) { - - // Create a test collection - db.createCollection('test_map_reduce_functions_inline', function(err, collection) { - - // Insert some test documents - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - - // Map function - var map = function() { emit(this.user_id, 1); }; - // Reduce function - var reduce = function(k,vals) { return 1; }; - - // Execute map reduce and return results inline - collection.mapReduce(map, reduce, {out : {inline: 1}}, function(err, results) { - test.equal(2, results.length); - - db.close(); - test.done(); - }); - }); - }); - } else { - test.done(); - } - }); - }); -} - -/** -* Mapreduce different test with a provided scope containing a javascript function. -* -* @_class collection -* @_function mapReduce -*/ -exports.shouldPerformMapReduceInContext = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection - client.createCollection('test_map_reduce_functions_scope', function(err, collection) { - - // Insert some test documents - collection.insert([{'user_id':1, 'timestamp':new Date()} - , {'user_id':2, 'timestamp':new Date()}], {safe:true}, function(err, r) { - - // Map function - var map = function(){ - emit(test(this.timestamp.getYear()), 1); - } - - // Reduce function - var reduce = function(k, v){ - count = 0; - for(i = 0; i < v.length; i++) { - count += v[i]; - } - return count; - } - - // Javascript function available in the map reduce scope - var t = function(val){ return val+1; } - - // Execute the map reduce with the custom scope - collection.mapReduce(map, reduce, {scope:{test:new Code(t.toString())} - , out: {replace:'replacethiscollection'}}, function(err, collection) { - - // Find all entries in the map-reduce collection - collection.find().toArray(function(err, results) { - test.equal(2, results[0].value) - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** -* Mapreduce tests -* @ignore -*/ -exports.shouldPerformMapReduceWithStringFunctions = function(test) { - client.createCollection('test_map_reduce', function(err, collection) { - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - // String functions - var map = "function() { emit(this.user_id, 1); }"; - var reduce = "function(k,vals) { return 1; }"; - - collection.mapReduce(map, reduce, function(err, collection) { - collection.findOne({'_id':1}, function(err, result) { - test.equal(1, result.value); - }); - - collection.findOne({'_id':2}, function(err, result) { - test.equal(1, result.value); - test.done(); - }); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldPerformMapReduceWithParametersBeingFunctions = function(test) { - client.createCollection('test_map_reduce_with_functions_as_arguments', function(err, collection) { - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - // String functions - var map = function() { emit(this.user_id, 1); }; - var reduce = function(k,vals) { return 1; }; - - collection.mapReduce(map, reduce, function(err, collection) { - collection.findOne({'_id':1}, function(err, result) { - test.equal(1, result.value); - }); - collection.findOne({'_id':2}, function(err, result) { - test.equal(1, result.value); - test.done(); - }); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldPerformMapReduceWithCodeObjects = function(test) { - client.createCollection('test_map_reduce_with_code_objects', function(err, collection) { - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - // String functions - var map = new Code("function() { emit(this.user_id, 1); }"); - var reduce = new Code("function(k,vals) { return 1; }"); - - collection.mapReduce(map, reduce, function(err, collection) { - collection.findOne({'_id':1}, function(err, result) { - test.equal(1, result.value); - }); - collection.findOne({'_id':2}, function(err, result) { - test.equal(1, result.value); - test.done(); - }); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldPerformMapReduceWithOptions = function(test) { - client.createCollection('test_map_reduce_with_options', function(err, collection) { - collection.insert([{'user_id':1}, {'user_id':2}, {'user_id':3}], {safe:true}, function(err, r) { - // String functions - var map = new Code("function() { emit(this.user_id, 1); }"); - var reduce = new Code("function(k,vals) { return 1; }"); - - collection.mapReduce(map, reduce, {'query': {'user_id':{'$gt':1}}}, function(err, collection) { - collection.count(function(err, count) { - test.equal(2, count); - - collection.findOne({'_id':2}, function(err, result) { - test.equal(1, result.value); - }); - collection.findOne({'_id':3}, function(err, result) { - test.equal(1, result.value); - test.done(); - }); - }); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldHandleMapReduceErrors = function(test) { - client.createCollection('test_map_reduce_error', function(err, collection) { - collection.insert([{'user_id':1}, {'user_id':2}, {'user_id':3}], {safe:true}, function(err, r) { - // String functions - var map = new Code("function() { throw 'error'; }"); - var reduce = new Code("function(k,vals) { throw 'error'; }"); - - collection.mapReduce(map, reduce, {'query': {'user_id':{'$gt':1}}}, function(err, r) { - test.ok(err != null); - test.done(); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldCorrectlyReturnNestedKeys = function(test) { - var start = new Date().setTime(new Date().getTime() - 10000); - var end = new Date().setTime(new Date().getTime() + 10000); - - var keys = { - "data.lastname": true - }; - - var condition = { - "data.date": { - $gte: start, - $lte: end - } - }; - - condition = {} - - var initial = { - count : 0 - }; - - var reduce = function(doc, output) { - output.count++; - } - - // Execute the group - client.createCollection('data', function(err, collection) { - collection.insert({ - data: { - lastname:'smith', - date:new Date() - } - }, {safe:true}, function(err, result) { - - // Execute the group - collection.group(keys, condition, initial, reduce, true, function(err, r) { - test.equal(1, r[0].count) - test.equal('smith', r[0]['data.lastname']); - test.done(); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/multiple_dbs_on_connection_pool_test.js b/node_modules/mongodb/test/multiple_dbs_on_connection_pool_test.js deleted file mode 100644 index 5e1fa24..0000000 --- a/node_modules/mongodb/test/multiple_dbs_on_connection_pool_test.js +++ /dev/null @@ -1,256 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - ServerManager = require('../test/tools/server_manager').ServerManager, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyEmitErrorOnAllDbsOnPoolClose = function(test) { - if(process.platform !== 'linux') { - var db = new Db('tests', new Server("127.0.0.1", 27027, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // All inserted docs - var docs = []; - var errs = []; - var insertDocs = []; - var numberOfCloses = 0; - - // Start server - var serverManager = new ServerManager({auth:false, purgedirectories:true, journal:false, start_port:27027}) - serverManager.start(false, function() { - db.on("close", function(err) { - numberOfCloses = numberOfCloses + 1; - }) - - db.open(function(err, db) { - db.createCollection('shouldCorrectlyErrorOnAllDbs', function(err, collection) { - test.equal(null, err); - - collection.insert({a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - // Open a second db - var db2 = db.db('tests_2'); - // Add a close handler - db2.on("close", function(err) { - numberOfCloses = numberOfCloses + 1; - }); - - db.serverConfig.connectionPool.openConnections[0].connection.destroy(); - - // Kill server and end test - serverManager.stop(9, function() { - test.equal(2, numberOfCloses) - test.done(); - }); - }); - }); - }); - }); - } else { - test.done(); - } -} - -/** - * Test the auto connect functionality of the db - * - * @ignore - */ -exports.shouldCorrectlyUseSameConnectionsForTwoDifferentDbs = function(test) { - var second_test_database = new Db(MONGODB + "_2", new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null), retryMiliSeconds:50}); - // Just create second database - second_test_database.open(function(err, second_test_database) { - // Close second database - second_test_database.close(); - // Let's grab a connection to the different db resusing our connection pools - var secondDb = client.db(MONGODB + "_2"); - secondDb.createCollection('shouldCorrectlyUseSameConnectionsForTwoDifferentDbs', function(err, collection) { - // Insert a dummy document - collection.insert({a:20}, {safe: true}, function(err, r) { - test.equal(null, err); - - // Query it - collection.findOne({}, function(err, item) { - test.equal(20, item.a); - - // Use the other db - client.createCollection('shouldCorrectlyUseSameConnectionsForTwoDifferentDbs', function(err, collection) { - // Insert a dummy document - collection.insert({b:20}, {safe: true}, function(err, r) { - test.equal(null, err); - - // Query it - collection.findOne({}, function(err, item) { - test.equal(20, item.b); - - // Drop the second db - secondDb.dropDatabase(function(err, item) { - test.equal(null, err); - test.done(); - }) - }) - }); - }); - }) - }); - }); - }); -} - -/** - * Test the auto connect functionality of the db - * - * @ignore - */ -exports.shouldCorrectlyUseSameConnectionsForTwoDifferentDbs = function(test) { - var second_test_database = new Db(MONGODB + "_2", new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null), retryMiliSeconds:50}); - // Just create second database - second_test_database.open(function(err, second_test_database) { - // Close second database - second_test_database.close(); - // Let's grab a connection to the different db resusing our connection pools - var secondDb = client.db(MONGODB + "_2"); - secondDb.createCollection('shouldCorrectlyUseSameConnectionsForTwoDifferentDbs', function(err, collection) { - // Insert a dummy document - collection.insert({a:20}, {safe: true}, function(err, r) { - test.equal(null, err); - - // Query it - collection.findOne({}, function(err, item) { - test.equal(20, item.a); - - // Use the other db - client.createCollection('shouldCorrectlyUseSameConnectionsForTwoDifferentDbs', function(err, collection) { - // Insert a dummy document - collection.insert({b:20}, {safe: true}, function(err, r) { - test.equal(null, err); - - // Query it - collection.findOne({}, function(err, item) { - test.equal(20, item.b); - - // Drop the second db - secondDb.dropDatabase(function(err, item) { - test.equal(null, err); - test.done(); - }) - }) - }); - }); - }) - }); - }); - }); -} - -/** - * Simple example connecting to two different databases sharing the socket connections below. - * - * @_class db - * @_function db - */ -exports.shouldCorrectlyShareConnectionPoolsAcrossMultipleDbInstances = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Reference a different database sharing the same connections - // for the data transfer - var secondDb = db.db("integration_tests_2"); - - // Fetch the collections - var multipleColl1 = db.collection("multiple_db_instances"); - var multipleColl2 = secondDb.collection("multiple_db_instances"); - - // Write a record into each and then count the records stored - multipleColl1.insert({a:1}, {safe:true}, function(err, result) { - multipleColl2.insert({a:1}, {safe:true}, function(err, result) { - - // Count over the results ensuring only on record in each collection - multipleColl1.count(function(err, count) { - test.equal(1, count); - - multipleColl2.count(function(err, count) { - test.equal(1, count); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/objectid_test.js b/node_modules/mongodb/test/objectid_test.js deleted file mode 100644 index ef51288..0000000 --- a/node_modules/mongodb/test/objectid_test.js +++ /dev/null @@ -1,351 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyGenerateObjectID = function(test) { - var number_of_tests_done = 0; - - client.collection('test_object_id_generation.data', function(err, collection) { - // Insert test documents (creates collections and test fetch by query) - collection.insert({name:"Fred", age:42}, {safe:true}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]['_id'].toHexString().length == 24); - // Locate the first document inserted - collection.findOne({name:"Fred"}, function(err, document) { - test.equal(ids[0]['_id'].toHexString(), document._id.toHexString()); - number_of_tests_done++; - }); - }); - - // Insert another test document and collect using ObjectId - collection.insert({name:"Pat", age:21}, {safe:true}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]['_id'].toHexString().length == 24); - // Locate the first document inserted - collection.findOne(ids[0]['_id'], function(err, document) { - test.equal(ids[0]['_id'].toHexString(), document._id.toHexString()); - number_of_tests_done++; - }); - }); - - // Manually created id - var objectId = new ObjectID(null); - // Insert a manually created document with generated oid - collection.insert({"_id":objectId, name:"Donald", age:95}, {safe:true}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]['_id'].toHexString().length == 24); - test.equal(objectId.toHexString(), ids[0]['_id'].toHexString()); - // Locate the first document inserted - collection.findOne(ids[0]['_id'], function(err, document) { - test.equal(ids[0]['_id'].toHexString(), document._id.toHexString()); - test.equal(objectId.toHexString(), document._id.toHexString()); - number_of_tests_done++; - }); - }); - }); - - var intervalId = setInterval(function() { - if(number_of_tests_done == 3) { - clearInterval(intervalId); - test.done(); - } - }, 100); -} - -/** - * Generate 12 byte binary string representation using a second based timestamp or - * default value - * - * @_class objectid - * @_function getTimestamp - * @ignore - */ -exports.shouldCorrectlyGenerate12ByteStringFromTimestamp = function(test) { - // Get a timestamp in seconds - var timestamp = Math.floor(new Date().getTime()/1000); - // Create a date with the timestamp - var timestampDate = new Date(timestamp*1000); - - // Create a new ObjectID with a specific timestamp - var objectId = new ObjectID(timestamp); - - // Get the timestamp and validate correctness - test.equal(timestampDate.toString(), objectId.getTimestamp().toString()); - test.done(); -} - -/** - * Generate a 24 character hex string representation of the ObjectID - * - * @_class objectid - * @_function toHexString - * @ignore - */ -exports.shouldCorrectlyRetrieve24CharacterHexStringFromToString = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Verify that the hex string is 24 characters long - test.equal(24, objectId.toHexString().length); - test.done(); -} - -/** - * Get and set the generation time for an ObjectID - * - * @_class objectid - * @_function generationTime - * @ignore - */ -exports.shouldCorrectlyGetAndSetObjectIDUsingGenerationTimeProperty = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Get the generation time - var generationTime = objectId.generationTime; - // Add 1000 miliseconds to the generation time - objectId.generationTime = generationTime + 1000; - - // Create a timestamp - var timestampDate = new Date(); - timestampDate.setTime((generationTime + 1000) * 1000); - - // Get the timestamp and validate correctness - test.equal(timestampDate.toString(), objectId.getTimestamp().toString()); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyRetrieve24CharacterHexStringFromToString = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Verify that the hex string is 24 characters long - test.equal(24, objectId.toString().length); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyRetrieve24CharacterHexStringFromToString = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Verify that the hex string is 24 characters long - test.equal(24, objectId.toJSON().length); - test.done(); -} - -/** - * Convert a ObjectID into a hex string representation and then back to an ObjectID - * - * @_class objectid - * @_function ObjectID.createFromHexString - * @ignore - */ -exports.shouldCorrectlyTransformObjectIDToAndFromHexString = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Convert the object id to a hex string - var originalHex = objectId.toHexString(); - // Create a new ObjectID using the createFromHexString function - var newObjectId = new ObjectID.createFromHexString(originalHex) - // Convert the new ObjectID back into a hex string using the toHexString function - var newHex = newObjectId.toHexString(); - // Compare the two hex strings - test.equal(originalHex, newHex); - test.done(); -} - -/** - * Compare two different ObjectID's using the equals method - * - * @_class objectid - * @_function equals - * @ignore - */ -exports.shouldCorrectlyTransformObjectIDToAndFromHexString = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Create a new ObjectID Based on the first ObjectID - var objectId2 = new ObjectID(objectId.id); - // Create another ObjectID - var objectId3 = new ObjectID(); - // objectId and objectId2 should be the same - test.ok(objectId.equals(objectId2)); - // objectId and objectId2 should be different - test.ok(!objectId.equals(objectId3)); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCreateOIDNotUsingObjectID = function(test) { - client.createCollection('test_non_oid_id', function(err, collection) { - var date = new Date(); - date.setUTCDate(12); - date.setUTCFullYear(2009); - date.setUTCMonth(11 - 1); - date.setUTCHours(12); - date.setUTCMinutes(0); - date.setUTCSeconds(30); - - collection.insert({'_id':date}, {safe:true}, function(err, ids) { - collection.find({'_id':date}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(("" + date), ("" + items[0]._id)); - - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyGenerateObjectIDFromTimestamp = function(test) { - var timestamp = Math.floor(new Date().getTime()/1000); - var objectID = new ObjectID(timestamp); - var time2 = objectID.generationTime; - test.equal(timestamp, time2); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCreateAnObjectIDAndOverrideTheTimestamp = function(test) { - var timestamp = 1000; - var objectID = new ObjectID(); - var id1 = objectID.id; - // Override the timestamp - objectID.generationTime = timestamp - var id2 = objectID.id; - // Check the strings - test.equal(id1.substr(4), id2.substr(4)); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertWithObjectId = function(test) { - client.createCollection('shouldCorrectlyInsertWithObjectId', function(err, collection) { - collection.insert({}, {safe:true}, function(err, ids) { - setTimeout(function() { - collection.insert({}, {safe:true}, function(err, ids) { - collection.find().toArray(function(err, items) { - var compareDate = new Date(); - - // Date 1 - var date1 = new Date(); - date1.setTime(items[0]._id.generationTime * 1000); - // Date 2 - var date2 = new Date(); - date2.setTime(items[1]._id.generationTime * 1000); - - // Compare - test.equal(compareDate.getFullYear(), date1.getFullYear()); - test.equal(compareDate.getDate(), date1.getDate()); - test.equal(compareDate.getMonth(), date1.getMonth()); - test.equal(compareDate.getHours(), date1.getHours()); - - test.equal(compareDate.getFullYear(), date2.getFullYear()); - test.equal(compareDate.getDate(), date2.getDate()); - test.equal(compareDate.getMonth(), date2.getMonth()); - test.equal(compareDate.getHours(), date2.getHours()); - // Let's close the db - test.done(); - }); - }); - }, 2000); - }); - }); -} - -/** - * Show the usage of the Objectid createFromTime function - * - * @_class objectid - * @_function ObjectID.createFromTime - * @ignore - */ -exports.shouldCorrectlyTransformObjectIDToAndFromHexString = function(test) { - var objectId = ObjectID.createFromTime(1); - test.equal("000000010000000000000000", objectId.toHexString()); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/raw_test.js b/node_modules/mongodb/test/raw_test.js deleted file mode 100644 index c08f9a2..0000000 --- a/node_modules/mongodb/test/raw_test.js +++ /dev/null @@ -1,397 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlySaveDocumentsAndReturnAsRaw = function(test) { - client.createCollection('shouldCorrectlySaveDocumentsAndReturnAsRaw', function(err, collection) { - // Insert some documents - collection.insert([{a:1}, {b:2000}, {c:2.3}], {safe:true}, function(err, result) { - // You have to pass at least query + fields before passing options - collection.find({}, null, {raw:true}).toArray(function(err, items) { - var objects = []; - for(var i = 0; i < items.length; i++) { - test.ok(items[i] instanceof Buffer); - objects.push(client.bson.deserialize(items[i])); - } - - test.equal(1, objects[0].a); - test.equal(2000, objects[1].b); - test.equal(2.3, objects[2].c); - - // Execute findOne - collection.findOne({a:1}, {raw:true}, function(err, item) { - test.ok(item instanceof Buffer); - var object = client.bson.deserialize(item); - test.equal(1, object.a) - test.done(); - }) - }) - }) - }); -} - -exports.shouldCorrectlyRemoveDocumentAndReturnRaw = function(test) { - client.createCollection('shouldCorrectlyRemoveDocumentAndReturnRaw', function(err, collection) { - // Insert some documents - collection.insert([{a:1}, {b:2000}, {c:2.3}], {safe:true}, function(err, result) { - // Let's create a raw delete command - var queryObject = {b:2000}; - // Create raw bson buffer - var rawQueryObject = new Buffer(client.bson.calculateObjectSize(queryObject)); - client.bson.serializeWithBufferAndIndex(queryObject, false, rawQueryObject, 0); - - // Update the document and return the raw new document - collection.remove(rawQueryObject, {safe:true}, function(err, numberOfDeleted) { - test.equal(1, numberOfDeleted); - - collection.findOne({b:2000}, function(err, item) { - test.equal(null, item) - test.done(); - }); - }); - }); - }); -} - -exports.shouldCorrectlyUpdateDocumentAndReturnRaw = function(test) { - client.createCollection('shouldCorrectlyUpdateDocumentAndReturnRaw', function(err, collection) { - // Insert some documents - collection.insert([{a:1}, {b:2000}, {c:2.3}], {safe:true}, function(err, result) { - // Let's create a raw delete command - var selectorObject = {b:2000}; - // Create raw bson buffer - var rawSelectorObject = new Buffer(client.bson.calculateObjectSize(selectorObject)); - client.bson.serializeWithBufferAndIndex(selectorObject, false, rawSelectorObject, 0); - // Let's create a raw delete command - var updateObject = {"$set":{c:2}}; - // Create raw bson buffer - var rawUpdateObject = new Buffer(client.bson.calculateObjectSize(updateObject)); - client.bson.serializeWithBufferAndIndex(updateObject, false, rawUpdateObject, 0); - // Update the document and return the raw new document - collection.update(rawSelectorObject, rawUpdateObject, {safe:true}, function(err, numberOfUpdated) { - test.equal(1, numberOfUpdated); - - // Query the document - collection.find({}, {}, {raw:true}).toArray(function(err, items) { - var objects = []; - for(var i = 0; i < items.length; i++) { - test.ok(items[i] instanceof Buffer); - objects.push(client.bson.deserialize(items[i])); - } - - test.equal(1, objects[0].a); - test.equal(2.3, objects[1].c); - test.equal(2000, objects[2].b); - test.equal(2, objects[2].c); - test.done(); - }) - }); - }); - }); -} - -exports.shouldCorreclyInsertRawDocumentAndRetrieveThem = function(test) { - client.createCollection('shouldCorreclyInsertRawDocumentAndRetrieveThem', function(err, collection) { - // Create serialized insert objects - var id = new ObjectID(); - var inputObjects = [{_id:id}, {a:1}, {b:2}, {c:4}] - var serializedObjects = []; - - // Serialize all object - for(var i = 0; i < inputObjects.length; i++) { - // Create raw bson buffer - var rawObject = new Buffer(client.bson.calculateObjectSize(inputObjects[i])); - client.bson.serializeWithBufferAndIndex(inputObjects[i], false, rawObject, 0); - serializedObjects.push(rawObject); - } - - // Insert all raw objects - collection.insert(serializedObjects, {safe:true}, function(err, result) { - test.equal(null, err); - - // Query the document - collection.find({}, {}, {raw:true}).toArray(function(err, items) { - var objects = []; - for(var i = 0; i < items.length; i++) { - test.ok(items[i] instanceof Buffer); - objects.push(client.bson.deserialize(items[i])); - } - - test.equal(id.toHexString(), objects[0]._id.toHexString()); - test.equal(1, objects[1].a); - test.equal(2, objects[2].b); - test.equal(4, objects[3].c); - test.done(); - }) - }); - }); -} - -exports.shouldCorrectlyPeformQueryUsingRaw = function(test) { - client.createCollection('shouldCorrectlyPeformQueryUsingRaw', function(err, collection) { - collection.insert([{a:1}, {b:2}, {b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Let's create a raw query object - var queryObject = {b:3}; - // Create raw bson buffer - var rawQueryObject = new Buffer(client.bson.calculateObjectSize(queryObject)); - client.bson.serializeWithBufferAndIndex(queryObject, false, rawQueryObject, 0); - - // Let's create a raw fields object - var fieldsObject = {}; - // Create raw bson buffer - var rawFieldsObject = new Buffer(client.bson.calculateObjectSize(fieldsObject)); - client.bson.serializeWithBufferAndIndex(fieldsObject, false, rawFieldsObject, 0); - - collection.find(rawQueryObject, rawFieldsObject, {raw:true}).toArray(function(err, items) { - test.equal(1, items.length); - test.ok(items[0] instanceof Buffer); - if(items[0] == null) console.dir(items) - var object = client.bson.deserialize(items[0]); - test.equal(3, object.b) - - collection.findOne(rawQueryObject, rawFieldsObject, {raw:true}, function(err, item) { - test.equal(null, err); - test.ok(item != null); - var object = client.bson.deserialize(item); - test.equal(3, object.b) - test.done(); - }); - }); - }) - }); -} - -exports.shouldCorrectlyThrowErrorsWhenIllegalySizedMessages = function(test) { - client.createCollection('shouldCorrectlyThrowErrorsWhenIllegalySizedMessages', function(err, collection) { - var illegalBuffer = new Buffer(20); - try { - collection.insert(illegalBuffer, {safe:true}, function(err, result) {}); - } catch (err) { - test.ok(err.toString().indexOf("insert") != -1); - } - - try { - collection.update(illegalBuffer, {}, function(){}) - } catch(err) { - test.ok(err.toString().indexOf("update spec") != -1); - } - - try { - collection.update({}, illegalBuffer, function(){}) - } catch(err) { - test.ok(err.toString().indexOf("update document") != -1); - } - - try { - collection.remove(illegalBuffer, function(){}) - } catch(err) { - test.ok(err.toString().indexOf("delete") != -1); - } - - try { - collection.find(illegalBuffer).toArray(function() {}) - } catch(err) { - test.ok(err.toString().indexOf("query selector") != -1); - } - - try { - collection.find({}, illegalBuffer).toArray(function() {}) - } catch(err) { - test.ok(err.toString().indexOf("query fields") != -1); - } - - try { - collection.findOne(illegalBuffer, function() {}) - } catch(err) { - test.ok(err.toString().indexOf("query selector") != -1); - } - - try { - collection.findOne({}, illegalBuffer, function() {}) - } catch(err) { - test.ok(err.toString().indexOf("query fields") != -1); - test.done(); - } - }); -} - -exports.shouldCorrectlyPeformQueryUsingRawSettingRawAtCollectionLevel = function(test) { - client.createCollection('shouldCorrectlyPeformQueryUsingRawSettingRawAtCollectionLevel', function(err, collection) { - collection.insert([{a:1}, {b:2}, {b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Let's create a raw query object - var queryObject = {b:3}; - // Create raw bson buffer - var rawQueryObject = new Buffer(client.bson.calculateObjectSize(queryObject)); - client.bson.serializeWithBufferAndIndex(queryObject, false, rawQueryObject, 0); - - // Let's create a raw fields object - var fieldsObject = {}; - // Create raw bson buffer - var rawFieldsObject = new Buffer(client.bson.calculateObjectSize(fieldsObject)); - client.bson.serializeWithBufferAndIndex(fieldsObject, false, rawFieldsObject, 0); - - client.collection('shouldCorrectlyPeformQueryUsingRaw', {raw:true}, function(err, collection) { - collection.find(rawQueryObject, rawFieldsObject).toArray(function(err, items) { - test.equal(1, items.length); - test.ok(items[0] instanceof Buffer); - var object = client.bson.deserialize(items[0]); - test.equal(3, object.b) - - collection.findOne(rawQueryObject, rawFieldsObject, {raw:true}, function(err, item) { - test.equal(null, err); - test.ok(item != null); - var object = client.bson.deserialize(item); - test.equal(3, object.b) - test.done(); - }); - }); - }); - }) - }); -} - -exports.shouldCorreclyInsertRawDocumentAndRetrieveThemSettingRawAtCollectionLevel = function(test) { - client.createCollection('shouldCorreclyInsertRawDocumentAndRetrieveThemSettingRawAtCollectionLevel', {raw:true}, function(err, collection) { - // Create serialized insert objects - var id = new ObjectID(); - var inputObjects = [{_id:id}, {a:1}, {b:2}, {c:4}] - var serializedObjects = []; - - // Serialize all object - for(var i = 0; i < inputObjects.length; i++) { - // Create raw bson buffer - var rawObject = new Buffer(client.bson.calculateObjectSize(inputObjects[i])); - client.bson.serializeWithBufferAndIndex(inputObjects[i], false, rawObject, 0); - serializedObjects.push(rawObject); - } - - // Insert all raw objects - collection.insert(serializedObjects, {safe:true}, function(err, result) { - test.equal(null, err); - - // Query the document - collection.find({}, {}).toArray(function(err, items) { - var objects = []; - for(var i = 0; i < items.length; i++) { - test.ok(items[i] instanceof Buffer); - objects.push(client.bson.deserialize(items[i])); - } - - test.equal(id.toHexString(), objects[0]._id.toHexString()); - test.equal(1, objects[1].a); - test.equal(2, objects[2].b); - test.equal(4, objects[3].c); - test.done(); - }) - }); - }); -} - -exports.shouldCorrectlyUpdateDocumentAndReturnRawSettingRawAtCollectionLevel = function(test) { - client.createCollection('shouldCorrectlyUpdateDocumentAndReturnRawSettingRawAtCollectionLevel', {raw:true}, function(err, collection) { - // Insert some documents - collection.insert([{a:1}, {b:2000}, {c:2.3}], {safe:true}, function(err, result) { - // Let's create a raw delete command - var selectorObject = {b:2000}; - // Create raw bson buffer - var rawSelectorObject = new Buffer(client.bson.calculateObjectSize(selectorObject)); - client.bson.serializeWithBufferAndIndex(selectorObject, false, rawSelectorObject, 0); - // Let's create a raw delete command - var updateObject = {"$set":{c:2}}; - // Create raw bson buffer - var rawUpdateObject = new Buffer(client.bson.calculateObjectSize(updateObject)); - client.bson.serializeWithBufferAndIndex(updateObject, false, rawUpdateObject, 0); - // Update the document and return the raw new document - collection.update(rawSelectorObject, rawUpdateObject, {safe:true}, function(err, numberOfUpdated) { - test.equal(1, numberOfUpdated); - - // Query the document - collection.find({}, {}).toArray(function(err, items) { - var objects = []; - for(var i = 0; i < items.length; i++) { - test.ok(items[i] instanceof Buffer); - objects.push(client.bson.deserialize(items[i])); - } - - test.equal(1, objects[0].a); - test.equal(2.3, objects[1].c); - test.equal(2000, objects[2].b); - test.equal(2, objects[2].c); - test.done(); - }) - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/reaper_test.js b/node_modules/mongodb/test/reaper_test.js deleted file mode 100644 index 4aa86c3..0000000 --- a/node_modules/mongodb/test/reaper_test.js +++ /dev/null @@ -1,88 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlySaveUnicodeContainingDocument = function(test) { - var reaperClient = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, ssl:useSSL}), {reaper:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - reaperClient.open(function(err, reaperClient) { - reaperClient._lastReaperTimestamp = (new Date().getTime() - 1000000); - var con = reaperClient.serverConfig.checkoutReader(); - // Prime the reaper with a bogus call - reaperClient._callBackStore._notReplied["3"] = {start: (new Date().getTime() - 50000), 'raw': false, chained:null, connection:con}; - reaperClient._callBackStore.once("3", function(err, result) { - reaperClient.close(); - test.done(); - }) - - reaperClient.collection("test", {safe:true}, function(err, col) { - // Does not matter - }); - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/regexp_test.js b/node_modules/mongodb/test/regexp_test.js deleted file mode 100644 index 213e6ae..0000000 --- a/node_modules/mongodb/test/regexp_test.js +++ /dev/null @@ -1,126 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlyInsertSimpleRegExpDocument = function(test) { - var regexp = /foobar/i; - - client.createCollection('test_regex', function(err, collection) { - collection.insert({'b':regexp}, {safe:true}, function(err, ids) { - collection.find({}, {'fields': ['b']}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(("" + regexp), ("" + items[0].b)); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -exports.shouldCorrectlyInsertSimpleUTF8Regexp = function(test) { - var regexp = /foobaré/; - - client.createCollection('test_utf8_regex', function(err, collection) { - collection.insert({'b':regexp}, {safe:true}, function(err, ids) { - collection.find({}, {'fields': ['b']}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(("" + regexp), ("" + items[0].b)); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -exports.shouldCorrectlyFindDocumentsByRegExp = function(test) { - // Serialized regexes contain extra trailing chars. Sometimes these trailing chars contain / which makes - // the original regex invalid, and leads to segmentation fault. - client.createCollection('test_regex_serialization', function(err, collection) { - collection.insert({keywords: ["test", "segmentation", "fault", "regex", "serialization", "native"]}, {safe:true}, function(err, r) { - - var count = 20, - run = function(i) { - // search by regex - collection.findOne({keywords: {$all: [/ser/, /test/, /seg/, /fault/, /nat/]}}, function(err, item) { - test.equal(6, item.keywords.length); - if (i === 0) { - test.done() - } - }); - }; - // loop a few times to catch the / in trailing chars case - while (count--) { - run(count); - } - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/remove_test.js b/node_modules/mongodb/test/remove_test.js deleted file mode 100644 index 440d0bf..0000000 --- a/node_modules/mongodb/test/remove_test.js +++ /dev/null @@ -1,171 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * An example removing all documents in a collection not using safe mode - * - * @_class collection - * @_function remove - * @ignore - */ -exports.shouldRemoveAllDocumentsNoSafe = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection to insert document into - db.collection("remove_all_documents_no_safe", function(err, collection) { - - // Insert a bunch of documents - collection.insert([{a:1}, {b:2}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Remove all the document - collection.remove(); - - // Wait for a second to ensure command went through - setTimeout(function() { - - // Fetch all results - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(0, items.length); - db.close(); - test.done(); - }); - }, 1000); - }); - }) - }); -} - -/** - * An example removing a subset of documents using safe mode to ensure removal of documents - * - * @_class collection - * @_function remove - * @ignore - */ -exports.shouldRemoveSubsetOfDocumentsSafeMode = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection to insert document into - db.collection("remove_subset_of_documents_safe", function(err, collection) { - - // Insert a bunch of documents - collection.insert([{a:1}, {b:2}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Remove all the document - collection.remove({a:1}, {safe:true}, function(err, numberOfRemovedDocs) { - test.equal(null, err); - test.equal(1, numberOfRemovedDocs); - db.close(); - test.done(); - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyClearOutCollection = function(test) { - client.createCollection('test_clear', function(err, r) { - client.collection('test_clear', function(err, collection) { - collection.insert({i:1}, {safe:true}, function(err, ids) { - collection.insert({i:2}, {safe:true}, function(err, ids) { - collection.count(function(err, count) { - test.equal(2, count); - // Clear the collection - collection.remove({}, {safe:true}, function(err, result) { - test.equal(2, result); - - collection.count(function(err, count) { - test.equal(0, count); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/replicaset/connect_test.js b/node_modules/mongodb/test/replicaset/connect_test.js deleted file mode 100644 index e10def9..0000000 --- a/node_modules/mongodb/test/replicaset/connect_test.js +++ /dev/null @@ -1,518 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server; - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 3000); - } else { - return callback(null); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -/** - * @ignore - */ -exports.shouldThrowErrorDueToSharedConnectionUsage = function(test) { - var replSet = new ReplSetServers([ - new Server('localhost', 28390, { auto_reconnect: true } ), - new Server('localhost', 28391, { auto_reconnect: true } ), - new Server('localhost', 28392, { auto_reconnect: true } ) - ] - ); - - try { - var db = new Db(MONGODB, replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - var db1 = new Db(MONGODB, replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - } catch(err) { - test.done(); - } -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleErrorWhenNoServerUpInReplicaset = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server('localhost', 28390, { auto_reconnect: true } ), - new Server('localhost', 28391, { auto_reconnect: true } ), - new Server('localhost', 28392, { auto_reconnect: true } ) - ] - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.ok(err != null); - test.done(); - }); -} - -/** - * Simple replicaset connection setup, requires a running replicaset on the correct ports - * - * @_class db - * @_function open - */ -exports.shouldCorrectlyConnectWithDefaultReplicasetNoOption = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server('localhost', 30000, { auto_reconnect: true } ), - new Server('localhost', 30001, { auto_reconnect: true } ), - new Server('localhost', 30002, { auto_reconnect: true } ) - ] - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.equal(null, err); - test.done(); - p_db.close(); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyConnectWithDefaultReplicasetNoOption = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ] - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.equal(null, err); - test.done(); - p_db.close(); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyConnectWithDefaultReplicaset = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.equal(null, err); - test.done(); - p_db.close(); - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyConnectWithDefaultReplicasetAndSocketOptionsSet = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {socketOptions:{keepAlive:100}} - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.equal(null, err); - test.equal(100, db.serverConfig.checkoutWriter().socketOptions.keepAlive) - test.done(); - p_db.close(); - }) -} - -/** - * @ignore - */ -exports.shouldEmitCloseNoCallback = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], {} - ); - - new Db('integration_test_', replSet).open(function(err, db) { - test.equal(null, err); - var dbCloseCount = 0, serverCloseCount = 0; - db.on('close', function() { ++dbCloseCount; }); - db.close(); - - setTimeout(function() { - test.equal(dbCloseCount, 1); - test.done(); - }, 2000); - }) -} - -/** - * @ignore - */ -exports.shouldEmitCloseWithCallback = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], {} - ); - - new Db('integration_test_', replSet).open(function(err, db) { - test.equal(null, err); - var dbCloseCount = 0; - db.on('close', function() { ++dbCloseCount; }); - - db.close(function() { - // Let all events fire. - process.nextTick(function() { - test.equal(dbCloseCount, 0); - test.done(); - }); - }); - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyPassErrorWhenWrongReplicaSet = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name + "-wrong"} - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.notEqual(null, err); - test.done(); - }) -} - -/** - * @ignore - */ -exports.shouldConnectWithPrimarySteppedDown = function(test) { - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Step down primary server - RS.stepDownPrimary(function(err, result) { - // Wait for new primary to pop up - ensureConnection(test, retries, function(err, p_db) { - - new Db('integration_test_', replSet).open(function(err, p_db) { - test.ok(err == null); - test.equal(true, p_db.serverConfig.isConnected()); - - p_db.close(); - test.done(); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldConnectWithThirdNodeKilled = function(test) { - RS.getNodeFromPort(RS.ports[2], function(err, node) { - if(err != null) debug("shouldConnectWithThirdNodeKilled :: " + inspect(err)); - - RS.kill(node, function(err, result) { - if(err != null) debug("shouldConnectWithThirdNodeKilled :: " + inspect(err)); - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Wait for new primary to pop up - ensureConnection(test, retries, function(err, p_db) { - new Db('integration_test_', replSet).open(function(err, p_db) { - test.ok(err == null); - test.equal(true, p_db.serverConfig.isConnected()); - - p_db.close(); - test.done(); - }) - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldConnectWithSecondaryNodeKilled = function(test) { - RS.killSecondary(function(node) { - - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= caught error") - console.dir(err) - if(err.stack != null) console.log(err.stack) - test.done(); - }) - - db.open(function(err, p_db) { - test.ok(err == null); - test.equal(true, p_db.serverConfig.isConnected()); - - // Close and cleanup - p_db.close(); - test.done(); - }) - }); -} - -/** - * @ignore - */ -exports.shouldConnectWithPrimaryNodeKilled = function(test) { - RS.killPrimary(function(node) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var db = new Db('integration_test_', replSet); - ensureConnection(test, retries, function(err, p_db) { - if(err != null && err.stack != null) console.log(err.stack) - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyBeAbleToUsePortAccessors = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldCorrectlyBeAbleToUsePortAccessors :: " + inspect(err)); - test.equal(replSet.host, p_db.serverConfig.primary.host); - test.equal(replSet.port, p_db.serverConfig.primary.port); - - p_db.close(); - test.done(); - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyConnect = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Replica configuration - var replSet2 = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var db = new Db('integration_test_', replSet ); - db.open(function(err, p_db) { - if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err)); - test.equal(true, p_db.serverConfig.isConnected()); - - // Test primary - RS.primary(function(err, primary) { - if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err)); - - test.notEqual(null, primary); - test.equal(primary, p_db.serverConfig.primary.host + ":" + p_db.serverConfig.primary.port); - - // Perform tests - RS.secondaries(function(err, items) { - if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err)); - - // Test if we have the right secondaries - test.deepEqual(items.sort(), p_db.serverConfig.allSecondaries.map(function(item) { - return item.host + ":" + item.port; - }).sort()); - - // Test if we have the right arbiters - RS.arbiters(function(err, items) { - if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err)); - - test.deepEqual(items.sort(), p_db.serverConfig.arbiters.map(function(item) { - return item.host + ":" + item.port; - }).sort()); - // Force new instance - var db2 = new Db('integration_test_', replSet2 ); - db2.open(function(err, p_db2) { - if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err)); - - test.equal(true, p_db2.serverConfig.isConnected()); - // Close top instance - db.close(); - db2.close(); - test.done(); - }); - }); - }); - }) - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; diff --git a/node_modules/mongodb/test/replicaset/count_test.js b/node_modules/mongodb/test/replicaset/count_test.js deleted file mode 100644 index 071c7c5..0000000 --- a/node_modules/mongodb/test/replicaset/count_test.js +++ /dev/null @@ -1,208 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server; - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports.shouldRetrieveCorrectCountAfterInsertionReconnect = function(test) { - // debug("=========================================== shouldRetrieveCorrectCountAfterInsertionReconnect") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - // Drop collection on replicaset - p_db.dropCollection('testsets', function(err, r) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - // Recreate collection on replicaset - p_db.createCollection('testsets', function(err, collection) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - // Insert a dummy document - collection.insert({a:20}, {safe: {w:2, wtimeout: 10000}}, function(err, r) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - // Execute a count - collection.count(function(err, c) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - test.equal(1, c); - // Close starting connection - p_db.close(); - - // Ensure replication happened in time - setTimeout(function() { - // Kill the primary - RS.killPrimary(function(node) { - - // debug("=========================================== shouldRetrieveCorrectCountAfterInsertionReconnect :: 0") - // Ensure valid connection - // Do inserts - // ensureConnection(test, retries, function(err, p_db) { - // // debug("=========================================== shouldRetrieveCorrectCountAfterInsertionReconnect :: 1") - // if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - // test.ok(err == null); - - p_db.collection('testsets', function(err, collection) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - collection.insert({a:30}, {safe:true}, function(err, r) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - collection.insert({a:40}, {safe:true}, function(err, r) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - // Execute count - collection.count(function(err, c) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - test.equal(3, c); - - p_db.close(); - test.done(); - }); - }); - }); - }); - // }); - }); - }, 2000); - }) - }) - }); - }); - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - - diff --git a/node_modules/mongodb/test/replicaset/insert_test.js b/node_modules/mongodb/test/replicaset/insert_test.js deleted file mode 100644 index 12bdb8b..0000000 --- a/node_modules/mongodb/test/replicaset/insert_test.js +++ /dev/null @@ -1,484 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // // Print any errors - // db.on("error", function(err) { - // console.log("============================= ensureConnection caught error") - // console.dir(err) - // if(err != null && err.stack != null) console.log(err.stack) - // db.close(); - // }) - - // Open the db - db.open(function(err, p_db) { - // Close connections - db.close(); - // Process result - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports.shouldCorrectlyWaitForReplicationToServersOnInserts = function(test) { - // debug("=========================================== shouldWorkCorrectlyWithInserts") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('shouldCorrectlyWaitForReplicationToServersOnInserts', function(err, r) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldCorrectlyWaitForReplicationToServersOnInserts', function(err, collection) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:2, wtimeout: 10000}}, function(err, r) { - test.equal(null, err); - test.done(); - p_db.close(); - }); - }); - }); - }); -} - -exports.shouldCorrectlyThrowTimeoutForReplicationToServersOnInserts = function(test) { - // debug("=========================================== shouldWorkCorrectlyWithInserts") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('shouldCorrectlyThrowTimeoutForReplicationToServersOnInserts', function(err, r) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldCorrectlyThrowTimeoutForReplicationToServersOnInserts', function(err, collection) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:7, wtimeout: 10000}}, function(err, r) { - test.equal('timeout', err.err); - test.equal(true, err.wtimeout); - test.done(); - p_db.close(); - }); - }); - }); - }); -} - -exports.shouldCorrectlyExecuteSafeFindAndModify = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('shouldCorrectlyExecuteSafeFindAndModify', function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldCorrectlyExecuteSafeFindAndModify', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:2, wtimeout: 10000}}, function(err, r) { - // Execute a safe insert with replication to two servers - collection.findAndModify({'a':20}, [['a', 1]], {'$set':{'b':3}}, {new:true, safe: {w:2, wtimeout: 10000}}, function(err, result) { - test.equal(20, result.a); - test.equal(3, result.b); - test.done(); - p_db.close(); - }) - }); - }); - }); - }); -} - -exports.shouldCorrectlyInsertAfterPrimaryComesBackUp = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - // {rs_name:RS.name, socketOptions:{timeout:30000}} - {rs_name:RS.name} - ); - - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - // Open db - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('shouldCorrectlyInsertAfterPrimaryComesBackUp', function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldCorrectlyInsertAfterPrimaryComesBackUp', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:'majority', wtimeout: 10000}}, function(err, r) { - // Kill the primary - RS.killPrimary(2, {killNodeWaitTime:0}, function(node) { - // Attempt insert (should fail) - collection.insert({a:30}, {safe: {w:2, wtimeout: 10000}}, function(err, r) { - test.ok(err != null) - - if(err != null) { - collection.insert({a:40}, {safe: {w:2, wtimeout: 10000}}, function(err, r) { - - // Peform a count - collection.count(function(err, count) { - - test.equal(2, count); - p_db.close(); - test.done(); - }); - }); - } else { - p_db.close(); - test.ok(false) - test.done(); - } - }); - }); - }); - }); - }); - }); -} - -exports.shouldCorrectlyQueryAfterPrimaryComesBackUp = function(test) { - // debug("=========================================== shouldWorkCorrectlyWithInserts") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - // Open db - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('shouldCorrectlyQueryAfterPrimaryComesBackUp', function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldCorrectlyQueryAfterPrimaryComesBackUp', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:'majority', wtimeout: 10000}}, function(err, r) { - // Kill the primary - RS.killPrimary(2, {killNodeWaitTime:0}, function(node) { - // Ok let's execute same query a couple of times - collection.find({}).toArray(function(err, items) { - // console.log("============================================ CALLED :: 0") - test.ok(err != null); - // console.dir(err) - - collection.find({}).toArray(function(err, items) { - // console.log("============================================ CALLED :: 1") - // console.dir(err) - // console.dir(items) - - test.ok(err == null); - test.equal(1, items.length); - - collection.find({}).toArray(function(err, items) { - test.ok(err == null); - test.equal(1, items.length); - p_db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports.shouldWorkCorrectlyWithInserts = function(test) { - // debug("=========================================== shouldWorkCorrectlyWithInserts") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - db.open(function(err, p_db) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Drop collection on replicaset - p_db.dropCollection('shouldWorkCorrectlyWithInserts', function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldWorkCorrectlyWithInserts', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Insert a dummy document - collection.insert({a:20}, {safe: {w:'majority', wtimeout: 10000}}, function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Execute a count - collection.count(function(err, c) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - test.equal(1, c); - - // Kill the primary - RS.killPrimary(function(node) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - test.ok(err == null); - - // p_db.collection('shouldWorkCorrectlyWithInserts', {safe:true}, function(err, collection) { - p_db.collection('shouldWorkCorrectlyWithInserts', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Execute a set of inserts - Step( - function inserts() { - var group = this.group(); - collection.save({a:30}, {safe:{w:2, wtimeout: 10000}}, group()); - collection.save({a:40}, {safe:{w:2, wtimeout: 10000}}, group()); - collection.save({a:50}, {safe:{w:2, wtimeout: 10000}}, group()); - collection.save({a:60}, {safe:{w:2, wtimeout: 10000}}, group()); - collection.save({a:70}, {safe:{w:2, wtimeout: 10000}}, group()); - }, - - function finishUp(err, values) { - if(err != null) console.log(err.stack) - // Restart the old master and wait for the sync to happen - RS.restartKilledNodes(function(err, result) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Contains the results - var results = []; - - // Just wait for the results - // setTimeout(function() { - // Ensure the connection - // ensureConnection(test, retries, function(err, p_db) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Get the collection - p_db.collection('shouldWorkCorrectlyWithInserts', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - collection.find().each(function(err, item) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - if(item == null) { - // Ensure we have the correct values - test.equal(6, results.length); - [20, 30, 40, 50, 60, 70].forEach(function(a) { - test.equal(1, results.filter(function(element) { - return element.a == a; - }).length); - }); - - // Run second check - collection.save({a:80}, {safe:true}, function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - collection.find().toArray(function(err, items) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Ensure we have the correct values - test.equal(7, items.length); - - // Sort items by a - items = items.sort(function(a,b) { return a.a > b.a}); - // Test all items - test.equal(20, items[0].a); - test.equal(30, items[1].a); - test.equal(40, items[2].a); - test.equal(50, items[3].a); - test.equal(60, items[4].a); - test.equal(70, items[5].a); - test.equal(80, items[6].a); - - p_db.close(); - test.done(); - }); - }); - } else { - results.push(item); - } - }); - }); - // }); - // }, 5000); - }) - } - ); - }); - }); - }) - }) - }); - }); - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - diff --git a/node_modules/mongodb/test/replicaset/map_reduce_test.js b/node_modules/mongodb/test/replicaset/map_reduce_test.js deleted file mode 100644 index 22bf66a..0000000 --- a/node_modules/mongodb/test/replicaset/map_reduce_test.js +++ /dev/null @@ -1,253 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Open the db - db.open(function(err, p_db) { - // Close connections - db.close(); - // Process result - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:0, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports['Should Correctly group using replicaset'] = function(test) { - var self = this; - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {slave_ok:true}); - db.open(function(err, p_db) { - if(err != null) debug("shouldGroup :: " + inspect(err)); - - p_db.createCollection("testgroup_replicaset", {safe:{w:2, wtimeout:10000}}, function(err, collection) { - if(err != null) debug("shoulGroup :: " + inspect(err)); - - collection.insert([{key:1,x:10}, {key:2,x:30}, {key:1,x:20}, {key:3,x:20}], {safe:{w:2, wtimeout:10000}}, function(err, result) { - // Ensure replication happened in time - setTimeout(function() { - // Kill the primary - RS.killPrimary(function(node) { - // Do a collection find - collection.group(['key'], {}, {sum:0}, function reduce(record, memo){ - memo.sum += record.x; - }, true, function(err, items){ - if(err != null) debug("shouldGroup :: " + inspect(err)); - test.equal(null, err); - test.equal(3, items.length); - - p_db.close(); - test.done(); - }) - }); - }, 2000); - }) - }); - }) -} - -exports.shouldPerformMapReduceFunctionInline = function(test) { - var self = this; - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Establish connection to db - var db = new Db('integration_test_', replSet, {slave_ok:true}); - db.open(function(err, db) { - - // Parse version of server if available - db.admin().serverInfo(function(err, result){ - - // Only run if the MongoDB version is higher than 1.7.6 - if(parseInt((result.version.replace(/\./g, ''))) >= 176) { - - // Create a test collection - db.createCollection('test_map_reduce_functions_inline_map_reduce', {safe:{w:2, wtimeout:10000}}, function(err, collection) { - // console.log("==================================================================================") - // console.dir(err) - - - // Insert some test documents - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - - // Map function - var map = function() { emit(this.user_id, 1); }; - // Reduce function - var reduce = function(k,vals) { return 1; }; - - // Execute map reduce and return results inline - collection.mapReduce(map, reduce, {out : {inline: 1}}, function(err, results) { - // console.log("=============================================================================") - // console.dir(err) - // console.dir(results) - - test.equal(2, results.length); - - db.close(); - test.done(); - }); - }); - }); - } else { - test.done(); - } - }); - }); -} - -exports.shouldFailToDoMapReduceToOutCollection = function(test) { - var self = this; - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Establish connection to db - var db = new Db('integration_test_', replSet, {slave_ok:true}); - db.open(function(err, db) { - - // Parse version of server if available - db.admin().serverInfo(function(err, result){ - - // Only run if the MongoDB version is higher than 1.7.6 - if(parseInt((result.version.replace(/\./g, ''))) >= 176) { - - // Create a test collection - db.createCollection('test_map_reduce_functions_notInline_map_reduce', {safe:{w:2, wtimeout:10000}}, function(err, collection) { - - // Insert some test documents - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - - // Map function - var map = function() { emit(this.user_id, 1); }; - // Reduce function - var reduce = function(k,vals) { return 1; }; - - // Execute map reduce and return results inline - collection.mapReduce(map, reduce, {out : {replace:'replacethiscollection'}}, function(err, results) { - test.ok(err != null); - - db.close(); - test.done(); - }); - }); - }); - } else { - test.done(); - } - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; diff --git a/node_modules/mongodb/test/replicaset/query_secondaries_test.js b/node_modules/mongodb/test/replicaset/query_secondaries_test.js deleted file mode 100644 index 31d2a88..0000000 --- a/node_modules/mongodb/test/replicaset/query_secondaries_test.js +++ /dev/null @@ -1,283 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports.shouldReadPrimary = function(test) { - // debug("=========================================== shouldReadPrimary") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - // Drop collection on replicaset - p_db.dropCollection('testsets', function(err, r) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - test.equal(false, p_db.serverConfig.isReadPrimary()); - test.equal(false, p_db.serverConfig.isPrimary()); - p_db.close(); - test.done(); - }); - }) -} - -exports.shouldCorrectlyTestConnection = function(test) { - // debug("=========================================== shouldCorrectlyTestConnection") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('testsets', function(err, r) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - - test.ok(p_db.serverConfig.primary != null); - test.ok(p_db.serverConfig.read != null); - test.ok(p_db.serverConfig.primary.port != p_db.serverConfig.read.port); - p_db.close(); - test.done(); - }); - }) -} - -exports.shouldCorrectlyQuerySecondaries = function(test) { - // debug("=========================================== shouldCorrectlyQuerySecondaries") - var self = this; - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - - p_db.createCollection("testsets", {safe:{w:2, wtimeout:10000}}, function(err, collection) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - - collection.insert([{a:20}, {a:30}, {a:40}], {safe:{w:2, wtimeout:10000}}, function(err, result) { - // Ensure replication happened in time - setTimeout(function() { - // Kill the primary - RS.killPrimary(function(node) { - // Do a collection find - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(3, items.length); - p_db.close(); - test.done(); - }); - }); - }, 2000); - }) - }); - }) -} - -exports.shouldCorrectlyQuerySecondaries = function(test) { - // debug("=========================================== shouldCorrectlyQuerySecondaries") - var self = this; - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:false} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - - // Ensure the checkoutReader gives us the actual writer object - var reader = replSet.checkoutReader(); - var writer = replSet.checkoutWriter(); - // Ensure the connections are the same - test.equal(reader.socketOptions.host, writer.socketOptions.host); - test.equal(reader.socketOptions.port, writer.socketOptions.port); - // Close connection to Spain - db.close(); - test.done(); - }); -} - -exports.shouldAllowToForceReadWithPrimary = function(test) { - // debug("=========================================== shouldAllowToForceReadWithPrimary") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - // Create a collection - p_db.createCollection('shouldAllowToForceReadWithPrimary', function(err, collection) { - test.equal(null, err); - // Insert a document - collection.insert({a:1}, {safe:{w:2, wtimeout:10000}}, function(err, result) { - test.equal(null, err); - - // Force read using primary - var cursor = collection.find({}, {read:'primary'}) - // Get documents - cursor.toArray(function(err, items) { - test.equal(1, items.length); - test.equal(1, items[0].a); - p_db.close(); - test.done(); - }) - }); - }) - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - - diff --git a/node_modules/mongodb/test/replicaset/read_preference_replicaset_test.js b/node_modules/mongodb/test/replicaset/read_preference_replicaset_test.js deleted file mode 100644 index 0c33e28..0000000 --- a/node_modules/mongodb/test/replicaset/read_preference_replicaset_test.js +++ /dev/null @@ -1,424 +0,0 @@ -// Read Preference behaviour based on Python driver by A. Jesse Jiryu Davis -// https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/__init__.py -// +----------------------+--------------------------------------------------+ -// | Connection type | Read Preference | -// +======================+================+================+================+ -// | |`PRIMARY` |`SECONDARY` |`SECONDARY_ONLY`| -// +----------------------+----------------+----------------+----------------+ -// |Connection to a single|Queries are |Queries are |Same as | -// |host. |allowed if the |allowed if the |`SECONDARY` | -// | |connection is to|connection is to| | -// | |the replica set |the replica set | | -// | |primary. |primary or a | | -// | | |secondary. | | -// +----------------------+----------------+----------------+----------------+ -// |Connection to a |Queries are sent|Queries are |Same as | -// |mongos. |to the primary |distributed |`SECONDARY` | -// | |of a shard. |among shard | | -// | | |secondaries. | | -// | | |Queries are sent| | -// | | |to the primary | | -// | | |if no | | -// | | |secondaries are | | -// | | |available. | | -// | | | | | -// +----------------------+----------------+----------------+----------------+ -// |ReplicaSetConnection |Queries are sent|Queries are |Queries are | -// | |to the primary |distributed |never sent to | -// | |of the replica |among replica |the replica set | -// | |set. |set secondaries.|primary. An | -// | | |Queries are sent|exception is | -// | | |to the primary |raised if no | -// | | |if no |secondary is | -// | | |secondaries are |available. | -// | | |available. | | -// | | | | | -// +----------------------+----------------+----------------+----------------+ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -var identifyServers = function(rs, dbname, callback) { - // Total number of servers to query - var numberOfServersToCheck = Object.keys(rs.mongods).length; - - // Arbiters - var arbiters = []; - var secondaries = []; - var primary = null; - - // Let's establish what all servers so we can pick targets for our queries - var keys = Object.keys(rs.mongods); - for(var i = 0; i < keys.length; i++) { - var host = rs.mongods[keys[i]].host; - var port = rs.mongods[keys[i]].port; - - // Connect to the db and query the state - var server = new Server(host, port,{auto_reconnect: true}); - // Create db instance - var db = new Db(dbname, server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, db) { - numberOfServersToCheck = numberOfServersToCheck - 1; - if(db.serverConfig.isMasterDoc.ismaster) { - primary = {host:db.serverConfig.host, port:db.serverConfig.port}; - } else if(db.serverConfig.isMasterDoc.secondary) { - secondaries.push({host:db.serverConfig.host, port:db.serverConfig.port}); - } else if(db.serverConfig.isMasterDoc.arbiterOnly) { - arbiters.push({host:db.serverConfig.host, port:db.serverConfig.port}); - } - - // Close the db - db.close(); - // If we are done perform the callback - if(numberOfServersToCheck <= 0) { - callback(null, {primary:primary, secondaries:secondaries, arbiters:arbiters}); - } - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -// +----------------------+--------------------------------------------------+ -// | Connection type | Read Preference | -// +======================+================+================+================+ -// | |`PRIMARY` |`SECONDARY` |`SECONDARY_ONLY`| -// +----------------------+----------------+----------------+----------------+ -// |ReplicaSetConnection |Queries are sent|Queries are |Queries are | -// | |to the primary |distributed |never sent to | -// | |of the replica |among replica |the replica set | -// | |set. |set secondaries.|primary. An | -// | | |Queries are sent|exception is | -// | | |to the primary |raised if no | -// | | |if no |secondary is | -// | | |secondaries are |available. | -// | | |available. | | -// | | | | | -// +----------------------+----------------+----------------+----------------+ -exports['Connection to replicaset with primary read preference'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, readPreference:Server.READ_PRIMARY} - ); - - // Execute flag - var executedCorrectly = false; - - // Create db instance - var db = new Db('integration_test_', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, p_db) { - // Let's get the primary server and wrap the checkout Method to ensure it's the one called for read - var checkoutWriterMethod = p_db.serverConfig._state.master.checkoutWriter; - // Set up checkoutWriter to catch correct write request - p_db.serverConfig._state.master.checkoutWriter = function() { - executedCorrectly = true; - return checkoutWriterMethod.apply(this); - } - - // Grab the collection - db.collection("read_preference_replicaset_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - // Does not get called or we don't care - test.ok(executedCorrectly); - p_db.close(); - test.done(); - }); - }); - }); -} - -exports['Connection to replicaset with secondary read preference with no secondaries should return primary'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, readPreference:Server.READ_SECONDARY} - ); - - // Create db instance - var db = new Db('integration_test_', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, p_db) { - // Rip out secondaries forcing an attempt to read from the primary - p_db.serverConfig._state.secondaries = {}; - - // Let's get the primary server and wrap the checkout Method to ensure it's the one called for read - var checkoutWriterMethod = p_db.serverConfig._state.master.checkoutWriter; - // Set up checkoutWriter to catch correct write request - p_db.serverConfig._state.master.checkoutWriter = function() { - var r = checkoutWriterMethod.apply(p_db.serverConfig._state.master); - test.equal(servers.primary.host, r.socketOptions.host); - test.equal(servers.primary.port, r.socketOptions.port); - return r; - } - - // Grab the collection - p_db.collection("read_preference_replicaset_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - // Does not get called or we don't care - p_db.close(); - test.done(); - }); - }); - }); - }); -} - -exports['Connection to replicaset with secondary only read preference no secondaries should not return a connection'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, readPreference:Server.READ_SECONDARY_ONLY} - ); - - // Create db instance - var db = new Db('integration_test_', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, p_db) { - // Rip out secondaries forcing an attempt to read from the primary - p_db.serverConfig._state.secondaries = {}; - - // Grab the collection - p_db.collection("read_preference_replicaset_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.ok(err != null); - test.equal("no open connections", err.message); - // Does not get called or we don't care - p_db.close(); - test.done(); - }); - }); - }); - }); -} - -exports['Connection to replicaset with secondary only read preference should return secondary server'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, readPreference:Server.READ_SECONDARY_ONLY} - ); - - // Execute flag - var executedCorrectly = false; - - // Create db instance - var db = new Db('integration_test_', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, p_db) { - // Let's set up all the secondaries - var keys = Object.keys(p_db.serverConfig._state.secondaries); - - // Set up checkoutReaders - for(var i = 0; i < keys.length; i++) { - var checkoutReader = p_db.serverConfig._state.secondaries[keys[i]].checkoutReader; - p_db.serverConfig._state.secondaries[keys[i]].checkoutReader = function() { - executedCorrectly = true; - } - } - - // Grab the collection - p_db.collection("read_preference_replicaset_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - // Does not get called or we don't care - test.ok(executedCorrectly); - p_db.close(); - test.done(); - }); - }); - }); - }); -} - -exports['Connection to replicaset with secondary read preference should return secondary server'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, readPreference:Server.READ_SECONDARY_ONLY} - ); - - // Execute flag - var executedCorrectly = false; - - // Create db instance - var db = new Db('integration_test_', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, p_db) { - // Let's set up all the secondaries - var keys = Object.keys(p_db.serverConfig._state.secondaries); - - // Set up checkoutReaders - for(var i = 0; i < keys.length; i++) { - var checkoutReader = p_db.serverConfig._state.secondaries[keys[i]].checkoutReader; - p_db.serverConfig._state.secondaries[keys[i]].checkoutReader = function() { - executedCorrectly = true; - return checkoutReader.apply(this); - } - } - - // Grab the collection - p_db.collection("read_preference_replicaset_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - // Does not get called or we don't care - test.ok(executedCorrectly); - p_db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - diff --git a/node_modules/mongodb/test/replicaset/read_preferences_single_test.js b/node_modules/mongodb/test/replicaset/read_preferences_single_test.js deleted file mode 100644 index bc6dd93..0000000 --- a/node_modules/mongodb/test/replicaset/read_preferences_single_test.js +++ /dev/null @@ -1,362 +0,0 @@ -// Read Preference behaviour based on Python driver by A. Jesse Jiryu Davis -// https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/__init__.py -// +----------------------+--------------------------------------------------+ -// | Connection type | Read Preference | -// +======================+================+================+================+ -// | |`PRIMARY` |`SECONDARY` |`SECONDARY_ONLY`| -// +----------------------+----------------+----------------+----------------+ -// |Connection to a single|Queries are |Queries are |Same as | -// |host. |allowed if the |allowed if the |`SECONDARY` | -// | |connection is to|connection is to| | -// | |the replica set |the replica set | | -// | |primary. |primary or a | | -// | | |secondary. | | -// +----------------------+----------------+----------------+----------------+ -// |Connection to a |Queries are sent|Queries are |Same as | -// |mongos. |to the primary |distributed |`SECONDARY` | -// | |of a shard. |among shard | | -// | | |secondaries. | | -// | | |Queries are sent| | -// | | |to the primary | | -// | | |if no | | -// | | |secondaries are | | -// | | |available. | | -// | | | | | -// +----------------------+----------------+----------------+----------------+ -// |ReplicaSetConnection |Queries are sent|Queries are |Queries are | -// | |to the primary |distributed |never sent to | -// | |of the replica |among replica |the replica set | -// | |set. |set secondaries.|primary. An | -// | | |Queries are sent|exception is | -// | | |to the primary |raised if no | -// | | |if no |secondary is | -// | | |secondaries are |available. | -// | | |available. | | -// | | | | | -// +----------------------+----------------+----------------+----------------+ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -var identifyServers = function(rs, dbname, callback) { - // Total number of servers to query - var numberOfServersToCheck = Object.keys(rs.mongods).length; - - // Arbiters - var arbiters = []; - var secondaries = []; - var primary = null; - - // Let's establish what all servers so we can pick targets for our queries - var keys = Object.keys(rs.mongods); - for(var i = 0; i < keys.length; i++) { - var host = rs.mongods[keys[i]].host; - var port = rs.mongods[keys[i]].port; - - // Connect to the db and query the state - var server = new Server(host, port,{auto_reconnect: true}); - // Create db instance - var db = new Db(dbname, server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, db) { - numberOfServersToCheck = numberOfServersToCheck - 1; - if(db.serverConfig.isMasterDoc.ismaster) { - primary = {host:db.serverConfig.host, port:db.serverConfig.port}; - } else if(db.serverConfig.isMasterDoc.secondary) { - secondaries.push({host:db.serverConfig.host, port:db.serverConfig.port}); - } else if(db.serverConfig.isMasterDoc.arbiterOnly) { - arbiters.push({host:db.serverConfig.host, port:db.serverConfig.port}); - } - - // Close the db - db.close(); - // If we are done perform the callback - if(numberOfServersToCheck <= 0) { - callback(null, {primary:primary, secondaries:secondaries, arbiters:arbiters}); - } - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -// +----------------------+--------------------------------------------------+ -// | Connection type | Read Preference | -// +======================+================+================+================+ -// | |`PRIMARY` |`SECONDARY` |`SECONDARY_ONLY`| -// +----------------------+----------------+----------------+----------------+ -// |Connection to a single|Queries are |Queries are |Same as | -// |host. |allowed if the |allowed if the |`SECONDARY` | -// | |connection is to|connection is to| | -// | |the replica set |the replica set | | -// | |primary. |primary or a | | -// | | |secondary. | | -// +----------------------+----------------+----------------+----------------+ -exports['Connection to a arbiter host with primary preference should give error'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Let's grab an arbiter, connect and attempt a query - var host = servers.arbiters[0].host; - var port = servers.arbiters[0].port; - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true}); - // Create db instance - var db = new Db('integration_test_', server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab a collection - p_db.createCollection('read_preference_single_test_0', function(err, collection) { - test.ok(err instanceof Error); - test.equal('Cannot write to an arbiter', err.message); - p_db.close(); - test.done(); - }); - }); - }); -} - -exports['Connection to a single primary host with different read preferences'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Select a secondary server, but specify read_primary (should fail) - // Let's grab a secondary server - var host = servers.primary.host; - var port = servers.primary.port; - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_PRIMARY}); - // Create db instance - var db = new Db('integration_test_', server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - p_db.collection("read_preference_single_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.equal(null, err); - p_db.close(); - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_SECONDARY}); - // Create db instance - var db = new Db('integration_test_', server, {slave_ok:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - db.collection("read_preference_single_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(0, items.length); - p_db.close(); - - // test.done(); - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_SECONDARY_ONLY}); - // Create db instance - var db = new Db('integration_test_', server, {slave_ok:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - db.collection("read_preference_single_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.ok(err instanceof Error); - test.equal("Cannot read from primary when secondary only specified", err.message); - - p_db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports['Connection to a single secondary host with different read preferences'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Select a secondary server, but specify read_primary (should fail) - // Let's grab a secondary server - var host = servers.secondaries[0].host; - var port = servers.secondaries[0].port; - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_PRIMARY}); - // Create db instance - var db = new Db('integration_test_', server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - p_db.collection("read_preference_single_test_1", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.ok(err instanceof Error); - test.equal("Read preference is primary and server is not master", err.message); - p_db.close(); - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_SECONDARY}); - // Create db instance - var db = new Db('integration_test_', server, {slave_ok:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - db.collection("read_preference_single_test_1", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(0, items.length); - p_db.close(); - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_SECONDARY_ONLY}); - // Create db instance - var db = new Db('integration_test_', server, {slave_ok:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - db.collection("read_preference_single_test_1", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(0, items.length); - - p_db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - - diff --git a/node_modules/mongodb/test/replicaset/tags_test.js b/node_modules/mongodb/test/replicaset/tags_test.js deleted file mode 100644 index c78e138..0000000 --- a/node_modules/mongodb/test/replicaset/tags_test.js +++ /dev/null @@ -1,382 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - PingStrategy = require('../../lib/mongodb/connection/strategies/ping_strategy').PingStrategy, - StatisticsStrategy = require('../../lib/mongodb/connection/strategies/statistics_strategy').StatisticsStrategy, - Server = require('../../lib/mongodb').Server; - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 3000); - } else { - return callback(null); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, passive_count:0, secondary_count:2, tags:[{"dc1":"ny"}, {"dc1":"ny"}, {"dc2":"sf"}]}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports['Should Correctly Connect With Default Replicaset And Insert Document For Tag Dc:NY'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Recreate collection on replicaset - p_db.createCollection('testsets', function(err, collection) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - - // Insert a dummy document - collection.insert({a:20}, {safe: {w:'majority'}}, function(err, r) { - // Should have no error - test.equal(null, err); - - // Do a read for the value - collection.findOne({a:20}, function(err, item) { - p_db.close(); - test.equal(20, item.a); - test.done(); - }) - }); - }); - }) -} - -exports['Should Honor setReadPreference primary'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference(Server.READ_PRIMARY); - // Open the database - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Checkout a reader and make sure it's the primary - var reader = replSet.checkoutReader(); - var readerAddress = reader.socketOptions['host'] + ":" + reader.socketOptions['port']; - // Locate server instance associated with this id - var serverInstance = replSet._state.addresses[readerAddress]; - // Check that it's the primary instance - test.equal(true, serverInstance.master); - // Check that it's in the list of primary servers - var primaryAddress = replSet._state.master.host + ":" + replSet._state.master.port; - test.equal(primaryAddress, readerAddress); - // End test and close db - p_db.close(); - test.done(); - }) -} - -exports['Should Honor setReadPreference secondary'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference(Server.READ_SECONDARY); - // Open the database - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Checkout a reader and make sure it's the primary - var reader = replSet.checkoutReader(); - var readerAddress = reader.socketOptions['host'] + ":" + reader.socketOptions['port']; - // Locate server instance associated with this id - var serverInstance = replSet._state.addresses[readerAddress]; - // Check that it's the primary instance - test.equal(false, serverInstance.master); - // Check that it's in the list of primary servers - test.ok(replSet._state.secondaries[readerAddress] != null); - // End test and close db - p_db.close(); - test.done(); - }) -} - -exports['Should correctly cleanup connection with tags'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference({'dc3':'pa', 'dc2':'sf', 'dc1':'ny'}); - // Open the database - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Checkout a reader and make sure it's the primary - var reader = replSet.checkoutWriter(); - var readerAddress = reader.socketOptions['host'] + ":" + reader.socketOptions['port']; - // Locate server instance associated with this id - var serverInstance = replSet._state.addresses[readerAddress]; - // Force cleanup of byTags - ReplSetServers._cleanupTags(serverInstance, replSet._state.byTags); - // Check cleanup successful - test.equal(1, replSet._state.byTags['dc1']['ny'].length); - test.equal(1, replSet._state.byTags['dc2']['sf'].length); - // End test and close db - p_db.close(); - test.done(); - }) -} - -exports['Should Honor setReadPreference tag'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference({'dc3':'pa', 'dc2':'sf', 'dc1':'ny'}); - // Open the database - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Checkout a reader and make sure it's the primary - var reader = replSet.checkoutReader(); - var readerAddress = reader.socketOptions['host'] + ":" + reader.socketOptions['port']; - // Locate server instance associated with this id - var serverInstance = replSet._state.addresses[readerAddress]; - test.deepEqual({ dc2: 'sf' }, serverInstance.tags) - p_db.close(); - test.done(); - }) -}, - -exports['Should Correctly Collect ping information from servers'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference({'dc3':'pa', 'dc2':'sf', 'dc1':'ny'}); - // Open the database - var db = new Db('integration_test_', replSet, {recordQueryStats:true}); - db.open(function(err, p_db) { - setTimeout(function() { - var keys = Object.keys(replSet._state.addresses); - for(var i = 0; i < keys.length; i++) { - var server = replSet._state.addresses[keys[i]]; - test.ok(server.queryStats.numDataValues >= 0); - test.ok(server.queryStats.mean >= 0); - test.ok(server.queryStats.variance >= 0); - test.ok(server.queryStats.standardDeviation >= 0); - } - - p_db.close(); - test.done(); - }, 5000) - }) -} - -exports['Should correctly pick a ping strategy for secondary'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference(Server.READ_SECONDARY); - // Open the database - var db = new Db('integration_test_', replSet, {recordQueryStats:true}); - db.open(function(err, p_db) { - p_db.createCollection('testsets3', function(err, collection) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - - // Insert a bunch of documents - collection.insert([{a:20}, {b:30}, {c:40}, {d:50}], {safe: {w:'majority'}}, function(err, r) { - - // Select all documents - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - p_db.close(); - test.done(); - }); - }); - }); - }) -} - -exports['Should correctly pick a statistics strategy for secondary'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {strategy:'statistical'} - ); - - // Ensure we have the right strategy - test.ok(replSet.strategyInstance instanceof StatisticsStrategy); - - // Set read preference - replSet.setReadPreference(Server.READ_SECONDARY); - // Open the database - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - p_db.createCollection('testsets2', function(err, collection) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - - // Insert a bunch of documents - collection.insert([{a:20}, {b:30}, {c:40}, {d:50}], {safe: {w:'majority'}}, function(err, r) { - - // Select all documents - collection.find().toArray(function(err, items) { - collection.find().toArray(function(err, items) { - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - - // Total number of entries done - var totalNumberOfStrategyEntries = 0; - - // Check that we have correct strategy objects - var keys = Object.keys(replSet._state.secondaries); - for(var i = 0; i < keys.length; i++) { - var server = replSet._state.secondaries[keys[i]]; - totalNumberOfStrategyEntries += server.queryStats.numDataValues; - } - - p_db.close(); - test.equal(4, totalNumberOfStrategyEntries); - test.done(); - }); - }); - }); - }); - }); - }) -}, - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; diff --git a/node_modules/mongodb/test/replicaset/two_server_tests.js b/node_modules/mongodb/test/replicaset/two_server_tests.js deleted file mode 100644 index 8be0031..0000000 --- a/node_modules/mongodb/test/replicaset/two_server_tests.js +++ /dev/null @@ -1,162 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - db.close(); - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, - arbiter_count:0, - secondary_count:1, - passive_count:0, - kill_node_wait_time:50000}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports.shouldCorrectlyExecuteSafeFindAndModify = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - // new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, read_secondary:false} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('testsets', function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('testsets', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:1, wtimeout: 10000}}, function(err, r) { - // Execute a findAndModify - collection.findAndModify({'a':20}, [['a', 1]], {'$set':{'b':3}}, {'new':true, safe: {w:7, wtimeout: 10000}}, function(err, updated_doc) { - test.equal('timeout', err.err) - test.equal(true, err.wtimeout) - p_db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - - diff --git a/node_modules/mongodb/test/streaming_test.js b/node_modules/mongodb/test/streaming_test.js deleted file mode 100644 index a769ce1..0000000 --- a/node_modules/mongodb/test/streaming_test.js +++ /dev/null @@ -1,143 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldStreamRecordsCallsDataTheRightNumberOfTimes = function(test) { - client.createCollection('test_stream_records', function(err, collection) { - test.ok(collection instanceof Collection); - collection.insert([{'a':1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}], {safe:true}, function(err, ids) { - var stream = collection.find({}, {'limit' : 3}).streamRecords(); - var callsToEnd = 0; - stream.on('end', function() { - test.done(); - }); - - var callsToData = 0; - stream.on('data',function(data){ - callsToData += 1; - test.ok(callsToData <= 3); - }); - }); - }); -} - -exports.shouldStreamRecordsCallsEndTheRightNumberOfTimes = function(test) { - client.createCollection('test_stream_records', function(err, collection) { - test.ok(collection instanceof Collection); - collection.insert([{'a':1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}], {safe:true}, function(err, ids) { - collection.find({}, {'limit' : 3}, function(err, cursor) { - var stream = cursor.streamRecords(function(er,item) {}); - var callsToEnd = 0; - stream.on('end', function() { - callsToEnd += 1; - test.equal(1, callsToEnd); - setTimeout(function() { - // Let's close the db - if (callsToEnd == 1) { - test.done(); - } - }.bind(this), 1000); - }); - - stream.on('data',function(data){ /* nothing here */ }); - }); - }); - }); -} - -exports.shouldStreamDocumentsWithLimitForFetching = function(test) { - var docs = [] - - for(var i = 0; i < 3000; i++) { - docs.push({'a':i}) - } - - client.createCollection('test_streaming_function_with_limit_for_fetching', function(err, collection) { - test.ok(collection instanceof Collection); - - collection.insert(docs, {safe:true}, function(err, ids) { - collection.find({}, function(err, cursor) { - // Execute find on all the documents - var stream = cursor.streamRecords({fetchSize:1000}); - var callsToEnd = 0; - stream.on('end', function() { - test.done(); - }); - - var callsToData = 0; - stream.on('data',function(data){ - callsToData += 1; - test.ok(callsToData <= 3000); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/mongodb/test/tools/keyfile.txt b/node_modules/mongodb/test/tools/keyfile.txt deleted file mode 100644 index f15d680..0000000 --- a/node_modules/mongodb/test/tools/keyfile.txt +++ /dev/null @@ -1 +0,0 @@ -THIS IS A SECRET KEYFILE FOR REPLICA SETS BWAHAHAHAH diff --git a/node_modules/mongodb/test/tools/replica_set_manager.js b/node_modules/mongodb/test/tools/replica_set_manager.js deleted file mode 100644 index 332c9f1..0000000 --- a/node_modules/mongodb/test/tools/replica_set_manager.js +++ /dev/null @@ -1,591 +0,0 @@ -var debug = require('util').debug, - inspect = require('util').inspect, - path = require('path'), - fs = require('fs'), - exec = require('child_process').exec, - spawn = require('child_process').spawn, - Connection = require('../../lib/mongodb').Connection, - Db = require('../../lib/mongodb').Db, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -var ReplicaSetManager = exports.ReplicaSetManager = function(options) { - options = options == null ? {} : options; - - this.startPort = options["start_port"] || 30000; - this.ports = []; - this.name = options["name"] != null ? options["name"] : "replica-set-foo"; - this.host = options["host"] != null ? options["host"] : "127.0.0.1"; - this.retries = options["retries"] != null ? options["retries"] : 60; - this.config = {"_id": this.name, "version": 1, "members": []}; - this.durable = options["durable"] != null ? options["durable"] : false; - this.auth = options['auth'] != null ? options['auth'] : false; - this.path = path.resolve("data"); - this.killNodeWaitTime = options['kill_node_wait_time'] != null ? options['kill_node_wait_time'] : 20000; - this.tags = options['tags'] != null ? options['tags'] : []; - this.ssl = options['ssl'] != null ? options['ssl'] : false; - - this.arbiterCount = options["arbiter_count"] != null ? options["arbiter_count"] : 2; - this.secondaryCount = options["secondary_count"] != null ? options["secondary_count"] : 1; - this.passiveCount = options["passive_count"] != null ? options["passive_count"] : 1; - this.primaryCount = options["primary_count"] != null ? options["primary_count"] : 1; - this.keyPath = [process.cwd(), "test", "tools", "keyfile.txt"].join("/"); - try { - fs.chmodSync(this.keyPath, 0600); - } catch(err) { - console.dir(err); - } - - this.count = this.primaryCount + this.passiveCount + this.arbiterCount + this.secondaryCount; - if(this.count > 7) { - throw new Error("Cannot create a replica set with #{node_count} nodes. 7 is the max."); - } - - // Keeps all the mongod instances - this.mongods = {}; -} - -ReplicaSetManager.prototype.secondaries = function(callback) { - return this.allHostPairsWithState(2, callback); -} - -ReplicaSetManager.prototype.arbiters = function(callback) { - return this.allHostPairsWithState(7, callback); -} - -ReplicaSetManager.prototype.primary = function(callback) { - return this.allHostPairsWithState(1, function(err, items) { - if(items.length == 0) { - return callback(null, null); - } else { - return callback(null, items[0]); - } - }); -} - -ReplicaSetManager.prototype.allHostPairsWithState = function(state, callback) { - this.ensureUp(function(err, status) { - if(err != null) return callback(err, null); - - var members = status["members"]; - - // Get the correct state memebers - var nodes = members.filter(function(value) { - return value["state"] == state; - }); - - // Filter out address of the server - var servers = nodes.map(function(item) { - return item["name"]; - }); - - // Map nodes - return callback(null, servers); - }) -} - -ReplicaSetManager.prototype.startSet = function(killall, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - killall = args.length ? args.shift() : true; - debug("** Starting a replica set with " + this.count + " nodes"); - - // Kill all existing mongod instances - exec(killall ? 'killall -9 mongod' : '', function(err, stdout, stderr) { - var n = 0; - var tagsIndex = 0; - - Step( - function startAllServers() { - var group = this.group(); - // Start primary instances - for(n = 0; n < (self.primaryCount + self.secondaryCount); n++) { - self.initNode(n, {tags:self.tags[tagsIndex] != null ? self.tags[tagsIndex++] : null}, group()); - } - - // Start passive instances - for(var i = 0; i < self.passiveCount; i++) { - self.initNode(n, {passive:true, priority:0, tags:self.tags[tagsIndex] != null ? self.tags[tagsIndex++] : null}, group()) - n = n + 1; - } - - // Start arbiter instances - for(var i = 0; i < self.arbiterCount; i++) { - self.initNode(n, {arbiterOnly:true, tags:self.tags[tagsIndex] != null ? self.tags[tagsIndex++] : null}, group()); - n = n + 1; - } - }, - - function finishUp(err, values) { - self.numberOfInitiateRetries = 0; - // Initiate - self.initiate(function(err, result) { - if(err != null) return callback(err, null); - self.ensureUpRetries = 0; - - // Ensure all the members are up - debug("** Ensuring members are up..."); - // Let's ensure everything is up - self.ensureUp(function(err, result) { - if(err != null) return callback(err, null); - // Return a correct result - callback(null, result); - }) - }); - } - ); - }) -} - -ReplicaSetManager.prototype.initiate = function(callback) { - var self = this; - var done = false; - // Get master connection - self.getConnection(function(err, connection) { - if(err != null) return callback(err, null); - // Set replica configuration - connection.admin().command({replSetInitiate:self.config}, function(err, result) { - // Close connection - connection.close(); - // If we have an error let's - if(err != null) { - // Retry a number of times - if(self.numberOfInitiateRetries < self.retries) { - setTimeout(function() { - self.numberOfInitiateRetries = self.numberOfInitiateRetries + 1; - self.initiate(callback); - }, 1000); - } - } else { - // Make sure we only do this once, even if some messages are late - if(!done) { - done = true; - self.numberOfInitiateRetries = 0; - callback(null, null); - } - } - }); - }); -} - -// Get absolute path -var getPath = function(self, name) { - return path.join(self.path, name); -} - -ReplicaSetManager.prototype.initNode = function(n, fields, callback) { - var self = this; - this.mongods[n] = this.mongods[n] == null ? {} : this.mongods[n]; - var port = this.startPort + n; - this.ports.push(port); - this.mongods[n]["ssl"] = this.ssl; - this.mongods[n]["host"] = this.host; - this.mongods[n]["port"] = port; - this.mongods[n]["db_path"] = getPath(this, "rs-" + port); - this.mongods[n]["log_path"] = getPath(this, "log-" + port); - this.up = false; - - // Set priority off server in config - var priority = typeof fields === 'object' ? fields.priority : null; - - // Add extra fields provided - for(var name in fields) { - this.mongods[n][name] = fields[name]; - } - - // Perform cleanup of directories - exec("rm -rf " + self.mongods[n]["db_path"], function(err, stdout, stderr) { - if(err != null) return callback(err, null); - - // Create directory - exec("mkdir -p " + self.mongods[n]["db_path"], function(err, stdout, stderr) { - if(err != null) return callback(err, null); - self.mongods[n]["start"] = self.startCmd(n); - - // console.log("----------------------------------------------------- node start command") - // console.log(self.mongods[n]["start"]) - - self.start(n, function() { - // Add instance to list of members - var member = {"_id": n, "host": self.host + ":" + self.mongods[n]["port"]}; - // Set it to arbiter if it's been passed - if(self.mongods[n]['arbiterOnly']) { - member['arbiterOnly'] = true; - } - // Set priority level if it's defined - if(priority != null) { - member['priority'] = priority; - } - - // Check if we have tags - if(self.mongods[n]['tags'] != null) { - member["tags"] = self.mongods[n]['tags']; - } - - // Push member to config - self.config["members"].push(member); - // Return - return callback(); - }); - }); - }); -} - -ReplicaSetManager.prototype.killAll = function(callback) { - exec('killall -9 mongod', function(err, stdout, stderr) { - return callback(); - }); -} - -ReplicaSetManager.prototype.kill = function(node, signal, options, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - signal = args.length ? args.shift() : 2; - options = args.length ? args.shift() : {}; - // kill node wait time - var killNodeWaitTime = options.killNodeWaitTime == null ? self.killNodeWaitTime : options.killNodeWaitTime; - - debug("** Killing node with pid " + this.mongods[node]["pid"] + " at port " + this.mongods[node]['port']); - var command = "kill -" + signal + " " + this.mongods[node]["pid"]; - // Kill process - exec(command, - function (error, stdout, stderr) { - debug('stdout: ' + stdout); - debug('stderr: ' + stderr); - if (error != null) { - debug('exec error: ' + error); - } - - self.mongods[node]["up"] = false; - // Wait for 5 seconds to give the server time to die a proper death - setTimeout(callback, killNodeWaitTime); - }); -} - -ReplicaSetManager.prototype.killPrimary = function(signal, options, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - signal = args.length ? args.shift() : 2; - options = args.length ? args.shift() : {}; - var done = false; - - this.getNodeWithState(1, function(err, node) { - if(!done) { - // Ensure no double callbacks due to later scheduled connections returning - done = true; - if(err != null) return callback(err, null); - - // Kill process and return node reference - self.kill(node, signal, options, function() { - // Wait for a while before passing back - callback(null, node); - }) - } - }); -} - -ReplicaSetManager.prototype.killSecondary = function(callback) { - var self = this; - var done = false; - - this.getNodeWithState(2, function(err, node) { - if(!done) { - // Ensure no double callbacks due to later scheduled connections returning - done = true; - if(err != null) return callback(err, null); - // Kill process and return node reference - self.kill(node, function() { - callback(null, node); - }) - } - }); -} - -ReplicaSetManager.prototype.stepDownPrimary = function(callback) { - var self = this; - // Get the primary node - this.getNodeWithState(1, function(err, primary) { - // Return error - if(err) return callback(err, null); - if(primary == null) return callback(new Error("No primary found"), null); - // Get the connection for the primary - self.getConnection(primary, function(err, connection) { - // Return any errors - if(err) return callback(err, null); - // Execute stepdown process - connection.admin().command({"replSetStepDown": 90}); - // Return the callback - return callback(null, connection); - }); - }); -} - -ReplicaSetManager.prototype.getNodeFromPort = function(port, callback) { - var self = this; - var nodes = Object.keys(this.mongods).filter(function(key, index, array) { - return self.mongods[key]["port"] == port; - }); - // Return first node - callback(null, nodes.length > 0 ? nodes.shift() : null); -} - -ReplicaSetManager.prototype.getNodeWithState = function(state, callback) { - var self = this; - self.ensureUpRetries = 0; - self.ensureUp(function(err, status) { - if(err != null) return callback(err, null); - - var node = status["members"].filter(function(element, index, array) { - return element["state"] == state; - }).shift(); - - if(node != null) { - var hostPort = node["name"].split(":"); - var port = hostPort[1] != null ? parseInt(hostPort[1]) : 27017; - var key = Object.keys(self.mongods).filter(function(element, index, array) { - return self.mongods[element]["port"] == port; - }).shift(); - return callback(null, key); - } else { - return callback(null, false); - } - }); -} - -ReplicaSetManager.prototype.ensureUp = function(callback) { - var self = this; - var numberOfInitiateRetries = this.retries; - var done = false; - - // Actual function doing testing - var ensureUpFunction = function() { - if(!done) { - if(!self.up) process.stdout.write("."); - // Attemp to retrieve a connection - self.getConnection(function(err, connection) { - // Adjust the number of retries - numberOfInitiateRetries = numberOfInitiateRetries - 1 - // If have no more retries stop - if(numberOfInitiateRetries == 0) { - // Set that we are done - done = true; - // perform callback - return callback(new Error("Servers did not come up again"), null); - } - - // We have a connection, execute command and update server object - if(err == null && connection != null) { - // Check repl set get status - connection.admin().command({"replSetGetStatus": 1}, function(err, object) { - // Close connection - if(connection != null) connection.close(); - // Get documents - var documents = object.documents; - // Get status object - var status = documents[0]; - - // If no members set - if(status["members"] == null || err != null) { - // if we have a connection force close it - if(connection != null) connection.close(); - // Ensure we perform enough retries - if(self.ensureUpRetries >= self.retries) { - // Set that we are done - done = true; - // Return error - return callback(new Error("Operation Failure"), null); - } else { - // Execute function again - setTimeout(ensureUpFunction, 1000); - } - } else { - // Establish all health member - var healthyMembers = status.members.filter(function(element) { - return element["health"] == 1 && [1, 2, 7].indexOf(element["state"]) != -1 - }); - - var stateCheck = status["members"].filter(function(element, indexOf, array) { - return element["state"] == 1; - }); - - if(healthyMembers.length == status.members.length && stateCheck.length > 0) { - // Set that we are done - done = true; - // if we have a connection force close it - if(connection != null) connection.close(); - // process.stdout.write("all members up! \n\n"); - if(!self.up) process.stdout.write("all members up!\n\n") - self.up = true; - return callback(null, status); - } else { - // if we have a connection force close it - if(connection != null) connection.close(); - // Ensure we perform enough retries - if(self.ensureUpRetries >= self.retries) { - // Set that we are done - done = true; - // Return error - return callback(new Error("Operation Failure"), null); - } else { - // Execute function again - setTimeout(ensureUpFunction, 1000); - } - } - } - }); - } else if(err != null && connection != null) { - if(connection != null) connection.close(); - } - }); - } - } - - // Execute the first function call - ensureUpFunction(); -} - -// Restart -ReplicaSetManager.prototype.restartKilledNodes = function(callback) { - var self = this; - - var nodes = Object.keys(self.mongods).filter(function(key) { - return self.mongods[key]["up"] == false; - }); - - var numberOfNodes = nodes.length; - if(numberOfNodes == 0) return self.ensureUp(callback); - - // Restart all the number of nodes - for(var i = 0; i < numberOfNodes; i++) { - // Start the process - self.start(nodes[i], function(err, result) { - // Adjust the number of nodes we are starting - numberOfNodes = numberOfNodes - 1; - - if(numberOfNodes === 0) { - self.ensureUp(callback); - } - }); - } -} - -ReplicaSetManager.prototype.getConnection = function(node, callback) { - var self = this; - // Function done - var done = false; - // Number of retries - var numberOfRetries = self.retries; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - node = args.length ? args.shift() : null; - - if(node == null) { - var keys = Object.keys(this.mongods); - for(var i = 0; i < keys.length; i++) { - var key = keys[i]; - // Locate first db that's runing and is not an arbiter - if(this.mongods[keys[i]]["arbiterOnly"] == null && this.mongods[key]["up"]) { - node = keys[i]; - break; - } - } - } - - // Get the node - if(self.mongods[node] != null) { - var intervalId = setInterval(function() { - var connection = new Db("replicaset_test", new Server(self.host, self.mongods[node]["port"], {ssl:self.ssl})); - connection.open(function(err, db) { - if(err == null && !done) { - // Set done - done = true; - // Clear interval - clearInterval(intervalId); - // Callback as done - return callback(null, connection); - } else { - // Close the connection - if(connection != null) connection.close(); - // Adjust the number of retries - numberOfRetries = numberOfRetries - 1; - // If we have no more retries fail - if(numberOfRetries == 0) { - // Set done - done = true; - // Clear interval - clearInterval(intervalId); - // Callback as done - return callback(new Error("Timed out connecting to primary"), null); - } - } - }); - }, 1000); - } else { - callback(new Error("no primary node found to do stepDownPrimary"), null); - } -} - -// Fire up the mongodb instance -var start = ReplicaSetManager.prototype.start = function(node, callback) { - var self = this; - - // Start up mongod process - var mongodb = exec(self.mongods[node]["start"], - function (error, stdout, stderr) { - debug('stdout: ' + stdout); - debug('stderr: ' + stderr); - if (error != null) { - debug('exec error: ' + error); - } - }); - - // Wait for a half a second then save the pids - setTimeout(function() { - // Mark server as running - self.mongods[node]["up"] = true; - self.mongods[node]["pid"]= fs.readFileSync(path.join(self.mongods[node]["db_path"], "mongod.lock"), 'ascii').trim(); - // Callback - callback(); - }, 5000); -} - -ReplicaSetManager.prototype.restart = start; - -ReplicaSetManager.prototype.startCmd = function(n) { - // Create boot command - this.mongods[n]["start"] = "mongod --rest --noprealloc --smallfiles --replSet " + this.name + " --logpath '" + this.mongods[n]['log_path'] + "' " + - " --dbpath " + this.mongods[n]['db_path'] + " --port " + this.mongods[n]['port'] + " --fork"; - this.mongods[n]["start"] = this.durable ? this.mongods[n]["start"] + " --dur" : this.mongods[n]["start"]; - - if(this.auth) { - this.mongods[n]["start"] = this.auth ? this.mongods[n]["start"] + " --keyFile " + this.keyPath : this.mongods[n]["start"]; - } - - // If we have ssl defined set up with test certificate - if(this.ssl) { - var path = getPath(this, '../test/certificates'); - this.mongods[n]["start"] = this.mongods[n]["start"] + " --sslOnNormalPorts --sslPEMKeyFile=" + path + "/mycert.pem --sslPEMKeyPassword=10gen"; - } - - return this.mongods[n]["start"]; -} - - - - - - - - - - - - - diff --git a/node_modules/mongodb/test/tools/server_manager.js b/node_modules/mongodb/test/tools/server_manager.js deleted file mode 100644 index 23c6a61..0000000 --- a/node_modules/mongodb/test/tools/server_manager.js +++ /dev/null @@ -1,142 +0,0 @@ -var debug = require('util').debug, - inspect = require('util').inspect, - path = require('path'), - fs = require('fs'), - exec = require('child_process').exec, - spawn = require('child_process').spawn, - Connection = require('../../lib/mongodb').Connection, - Db = require('../../lib/mongodb').Db, - Server = require('../../lib/mongodb').Server; - -var ServerManager = exports.ServerManager = function(options) { - options = options == null ? {} : options; - // Basic unpack values - this.path = path.resolve("data"); - this.port = options["start_port"] != null ? options["start_port"] : 27017; - this.db_path = getPath(this, "data-" + this.port); - this.log_path = getPath(this, "log-" + this.port); - this.journal = options["journal"] != null ? options["journal"] : false; - this.auth = options['auth'] != null ? options['auth'] : false; - this.ssl = options['ssl'] != null ? options['ssl'] : false; - this.purgedirectories = options['purgedirectories'] != null ? options['purgedirectories'] : true; - - // Server status values - this.up = false; - this.pid = null; -} - -// Start up the server instance -ServerManager.prototype.start = function(killall, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - killall = args.length ? args.shift() : true; - // Create start command - var startCmd = generateStartCmd(this, {log_path: self.log_path, - db_path: self.db_path, port: self.port, journal: self.journal, auth:self.auth, ssl:self.ssl}); - - // console.log("----------------------------------------------------------------------- start") - // console.log(startCmd) - - exec(killall ? 'killall mongod' : '', function(err, stdout, stderr) { - if(self.purgedirectories) { - // Remove directory - exec("rm -rf " + self.db_path, function(err, stdout, stderr) { - if(err != null) return callback(err, null); - // Create directory - exec("mkdir -p " + self.db_path, function(err, stdout, stderr) { - if(err != null) return callback(err, null); - // Start up mongod process - var mongodb = exec(startCmd, - function (error, stdout, stderr) { - // console.log('stdout: ' + stdout); - // console.log('stderr: ' + stderr); - if (error != null) { - console.log('exec error: ' + error); - } - }); - - // Wait for a half a second then save the pids - setTimeout(function() { - // Mark server as running - self.up = true; - self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); - // Callback - callback(); - }, 500); - }); - }); - } else { - // Ensure we remove the lock file as we are not purging the directory - fs.unlinkSync(path.join(self.db_path, "mongod.lock")); - - // Start up mongod process - var mongodb = exec(startCmd, - function (error, stdout, stderr) { - if (error != null) { - console.log('exec error: ' + error); - } - }); - - // Wait for a half a second then save the pids - setTimeout(function() { - // Mark server as running - self.up = true; - self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); - // Callback - callback(); - }, 5000); - } - }); -} - -ServerManager.prototype.stop = function(signal, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - signal = args.length ? args.shift() : 2; - // Stop the server - var command = "kill -" + signal + " " + self.pid; - // Kill process - exec(command, - function (error, stdout, stderr) { - // console.log('stdout: ' + stdout); - // console.log('stderr: ' + stderr); - if (error !== null) { - console.log('exec error: ' + error); - } - - self.up = false; - // Wait for a second - setTimeout(callback, 1000); - }); -} - -ServerManager.prototype.killAll = function(callback) { - exec('killall mongod', function(err, stdout, stderr) { - callback(null, null); - }); -} - -// Get absolute path -var getPath = function(self, name) { - return path.join(self.path, name); -} - -// Generate start command -var generateStartCmd = function(self, options) { - // Create boot command - var startCmd = "mongod --noprealloc --logpath '" + options['log_path'] + "' " + - " --dbpath " + options['db_path'] + " --port " + options['port'] + " --fork"; - startCmd = options['journal'] ? startCmd + " --journal" : startCmd; - startCmd = options['auth'] ? startCmd + " --auth" : startCmd; - // If we have ssl defined set up with test certificate - if(options['ssl']) { - var path = getPath(self, '../test/certificates'); - startCmd = startCmd + " --sslOnNormalPorts --sslPEMKeyFile=" + path + "/mycert.pem --sslPEMKeyPassword=10gen"; - } - // Return start command - return startCmd; -} diff --git a/node_modules/mongodb/test/tools/sharding_manager.js b/node_modules/mongodb/test/tools/sharding_manager.js deleted file mode 100644 index 9d58a7a..0000000 --- a/node_modules/mongodb/test/tools/sharding_manager.js +++ /dev/null @@ -1,155 +0,0 @@ -var debug = require('util').debug, - inspect = require('util').inspect, - path = require('path'), - fs = require('fs'), - exec = require('child_process').exec, - spawn = require('child_process').spawn, - Connection = require('../../lib/mongodb').Connection, - Db = require('../../lib/mongodb').Db, - Server = require('../../lib/mongodb').Server; - -var ShardingManager = exports.ShardingManager = function(options) { - options = options == null ? {} : options; - // Basic unpack values - this.path = path.resolve("data"); - this.port = options["start_port"] != null ? options["start_port"] : 27017; - this.number_of_sharding_servers = options["number_of_sharding_servers"] != null ? options["number_of_sharding_servers"] : 2; - this.number_of_config_servers = options["number_of_config_servers"] != null ? options["number_of_config_servers"] : 1; - this.db_path = getPath(this, "data-" + this.port); - this.log_path = getPath(this, "log-" + this.port); - this.journal = options["journal"] != null ? options["journal"] : false; - this.auth = options['auth'] != null ? options['auth'] : false; - this.ssl = options['ssl'] != null ? options['ssl'] : false; - this.purgedirectories = options['purgedirectories'] != null ? options['purgedirectories'] : true; - - // Server status values - this.up = false; - this.pid = null; -} - -// Start up the server instance -ShardingManager.prototype.start = function(killall, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - killall = args.length ? args.shift() : true; - // Create start command - var startCmd = generateStartCmd(this, {log_path: self.log_path, - db_path: self.db_path, port: self.port, journal: self.journal, auth:self.auth, ssl:self.ssl}); - - // Purge function for the data directory - var purgeFunction = function() { - if(self.purgedirectories) { - // Remove directory - exec("rm -rf " + self.db_path, function(err, stdout, stderr) { - if(err != null) return callback(err, null); - // Create directory - exec("mkdir -p " + self.db_path, function(err, stdout, stderr) { - if(err != null) return callback(err, null); - // Start up mongod process - var mongodb = exec(startCmd, - function (error, stdout, stderr) { - // console.log('stdout: ' + stdout); - // console.log('stderr: ' + stderr); - if (error != null) { - console.log('exec error: ' + error); - } - }); - - // Wait for a half a second then save the pids - setTimeout(function() { - // Mark server as running - self.up = true; - self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); - // Callback - callback(); - }, 500); - }); - }); - } else { - // Ensure we remove the lock file as we are not purging the directory - fs.unlinkSync(path.join(self.db_path, "mongod.lock")); - - // Start up mongod process - var mongodb = exec(startCmd, - function (error, stdout, stderr) { - if (error != null) { - console.log('exec error: ' + error); - } - }); - - // Wait for a half a second then save the pids - setTimeout(function() { - // Mark server as running - self.up = true; - self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); - // Callback - callback(); - }, 5000); - } - } - - // If we specified kill all the instances do that then purge the directories - if(killall) { - this.killAll(function() { - purgeFunction(); - }); - } else { - purgeFunction(); - } -} - -ShardingManager.prototype.stop = function(signal, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - signal = args.length ? args.shift() : 2; - // Stop the server - var command = "kill -" + signal + " " + self.pid; - // Kill process - exec(command, - function (error, stdout, stderr) { - // console.log('stdout: ' + stdout); - // console.log('stderr: ' + stderr); - if (error != null) { - console.log('exec error: ' + error); - } - - self.up = false; - // Wait for a second - setTimeout(callback, 1000); - }); -} - -ShardingManager.prototype.killAll = function(callback) { - // Kill all mongos instances - exec('killall mongos', function(err, stdout, stderr) { - // Kill all mongod instances - exec('killall mongod', function(err, stdout, stderr) { - callback(null, null); - }); - }); -} - -// Get absolute path -var getPath = function(self, name) { - return path.join(self.path, name); -} - -// Generate start command -var generateStartCmd = function(self, options) { - // Create boot command - var startCmd = "mongod --noprealloc --logpath '" + options['log_path'] + "' " + - " --dbpath " + options['db_path'] + " --port " + options['port'] + " --fork"; - startCmd = options['journal'] ? startCmd + " --journal" : startCmd; - startCmd = options['auth'] ? startCmd + " --auth" : startCmd; - // If we have ssl defined set up with test certificate - if(options['ssl']) { - var path = getPath(self, '../test/certificates'); - startCmd = startCmd + " --sslOnNormalPorts --sslPEMKeyFile=" + path + "/mycert.pem --sslPEMKeyPassword=10gen"; - } - // Return start command - return startCmd; -} diff --git a/node_modules/mongodb/test/unicode_test.js b/node_modules/mongodb/test/unicode_test.js deleted file mode 100644 index e253421..0000000 --- a/node_modules/mongodb/test/unicode_test.js +++ /dev/null @@ -1,185 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlySaveUnicodeContainingDocument = function(test) { - var doc = {statuses_count: 1687 - , created_at: 'Mon Oct 22 14:55:08 +0000 2007' - , description: 'NodeJS hacker, Cofounder of Debuggable, CakePHP core alumnus' - , favourites_count: 6 - , profile_sidebar_fill_color: 'EADEAA' - , screen_name: 'felixge' - , status: - { created_at: 'Fri Mar 12 08:59:44 +0000 2010' - , in_reply_to_screen_name: null - , truncated: false - , in_reply_to_user_id: null - , source: '
Tweetie' - , favorited: false - , in_reply_to_status_id: null - , id: 10364119169 - , text: '#berlin #snow = #fail : (' - } - , contributors_enabled: false - , following: null - , geo_enabled: false - , time_zone: 'Eastern Time (US & Canada)' - , profile_sidebar_border_color: 'D9B17E' - , url: 'http://debuggable.com' - , verified: false - , location: 'Berlin' - , profile_text_color: '333333' - , notifications: null - , profile_background_image_url: 'http://s.twimg.com/a/1268354287/images/themes/theme8/bg.gif' - , protected: false - , profile_link_color: '9D582E' - , followers_count: 840 - , name: 'Felix Geisend\u00f6rfer' - , profile_background_tile: false - , id: 9599342 - , lang: 'en' - , utc_offset: -18000 - , friends_count: 450 - , profile_background_color: '8B542B' - , profile_image_url: 'http://a3.twimg.com/profile_images/107142257/passbild-square_normal.jpg' - }; - - client.createCollection('test_should_correctly_save_unicode_containing_document', function(err, collection) { - doc['_id'] = 'felixge'; - - collection.save(doc, {safe:true}, function(err, doc) { - collection.findOne(function(err, doc) { - test.equal('felixge', doc._id); - test.done(); - }); - }); - }); -} - -// Test unicode characters -exports.shouldCorrectlyInsertUnicodeCharacters = function(test) { - client.createCollection('unicode_test_collection', function(err, collection) { - var test_strings = ["ouooueauiOUOOUEAUI", "öüóőúéáűíÖÜÓŐÚÉÁŰÍ", "本荘由利地域に洪水警報"]; - collection.insert({id: 0, text: test_strings[0]}, {safe:true}, function(err, ids) { - collection.insert({id: 1, text: test_strings[1]}, {safe:true}, function(err, ids) { - collection.insert({id: 2, text: test_strings[2]}, {safe:true}, function(err, ids) { - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - test.equal(test_strings[item.id], item.text); - } else { - test.done(); - } - }); - }); - }); - }); - }); - }); -} - -exports.shouldCreateObjectWithChineseObjectName = function(test) { - var object = {'客家话' : 'Hello'}; - - client.createCollection('create_object_with_chinese_object_name', function(err, r) { - client.collection('create_object_with_chinese_object_name', function(err, collection) { - - collection.insert(object, {safe:true}, function(err, result) { - collection.findOne(function(err, item) { - test.equal(object['客家话'], item['客家话']) - - collection.find().toArray(function(err, items) { - test.equal(object['客家话'], items[0]['客家话']) - test.done(); - }) - }) - }); - }) - }) -} - -exports.shouldCorrectlyHandleUT8KeyNames = function(test) { - client.createCollection('test_utf8_key_name', function(err, collection) { - collection.insert({'šđžčćŠĐŽČĆ':1}, {safe:true}, function(err, ids) { - // finished_test({test_utf8_key_name:'ok'}); - collection.find({}, {'fields': ['šđžčćŠĐŽČĆ']}, function(err, cursor) { - cursor.toArray(function(err, items) { - // console.log("---------------------------------------------------------------") - // console.dir(err) - // console.dir(items) - // - test.equal(1, items[0]['šđžčćŠĐŽČĆ']); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/.npmignore b/node_modules/reg/node_modules/mongodb/.npmignore index 42ccab3..ed901d9 100644 --- a/node_modules/reg/node_modules/mongodb/.npmignore +++ b/node_modules/reg/node_modules/mongodb/.npmignore @@ -1,3 +1,12 @@ .git* +.buildinfo +.mongodb docs/ +docs/sphinx-docs data/ +dev/ +examples/ +test/ +.DS_Store + + diff --git a/node_modules/reg/node_modules/mongodb/HISTORY b/node_modules/reg/node_modules/mongodb/HISTORY index da42c33..adfb2fc 100644 --- a/node_modules/reg/node_modules/mongodb/HISTORY +++ b/node_modules/reg/node_modules/mongodb/HISTORY @@ -1,3 +1,8 @@ +0.9.9.1 2012-02-15 +------------------ +* Better handling of safe when using some commands such as createIndex, ensureIndex, addUser, removeUser, createCollection. +* Mapreduce now throws error if out parameter is not specified. + 0.9.9 2012-02-13 ---------------- * Added createFromTime method on ObjectID to allow for queries against _id more easily using the timestamp. diff --git a/node_modules/reg/node_modules/mongodb/deps/gleak/.npmignore b/node_modules/reg/node_modules/mongodb/deps/gleak/.npmignore deleted file mode 100644 index f6ff43a..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/gleak/.npmignore +++ /dev/null @@ -1,4 +0,0 @@ -*.swp -*.swo -*.swu -node_modules/ diff --git a/node_modules/reg/node_modules/mongodb/deps/gleak/History.md b/node_modules/reg/node_modules/mongodb/deps/gleak/History.md deleted file mode 100644 index d4f9d05..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/gleak/History.md +++ /dev/null @@ -1,42 +0,0 @@ - -0.2.1 / 10-18-2011 -================== - - * fixed; package.json dependency versioning - -0.2.0 / 10-11-2011 -================== - - * added; node v0.5 / v0.6 support - -0.1.3 / 09-22-2011 -================== - - * use old school node engine format in package.json - -0.1.2 / 09-08-2011 -================== - - * changed; utilize detectNew in middleware - * updated; docs - -0.1.1 / 09-07-2011 -================== - - * added; #detectNew method - -0.1.0 / 09-06-2011 -================== - - * added; #ignore method - * added; multiple instance support - -0.0.2 / 09-06-2011 -================== - - * added; allow whitelisting by variable name - -0.0.1 / 09-03-2011 -================== - - * initial release diff --git a/node_modules/reg/node_modules/mongodb/deps/gleak/Makefile b/node_modules/reg/node_modules/mongodb/deps/gleak/Makefile deleted file mode 100644 index 532107e..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/gleak/Makefile +++ /dev/null @@ -1,6 +0,0 @@ - -test: - @NODE_ENV=test ./node_modules/expresso/bin/expresso \ - test/index.js - -.PHONY: test diff --git a/node_modules/reg/node_modules/mongodb/deps/gleak/README.md b/node_modules/reg/node_modules/mongodb/deps/gleak/README.md deleted file mode 100644 index 901f22a..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/gleak/README.md +++ /dev/null @@ -1,118 +0,0 @@ -# Gleak -Global variable leak detection for Node.js - - var detector = require('gleak')(); - - detector.detect().forEach(function (name) { - console.warn('found global leak: %s', name); - }); - -Global variable leaks in javascript can bite you when you least -expect it. Do something about it now and run this module after -your tests, after HTTP requests, and after you brush your teeth. - -## Detectable - -As demonstrated, gleak comes with the `detect` method which returns -an array of all found variable leaks. - -Often times we want to run the detector many times, progressively -checking for any new leaks that occurred since we last checked. In -this scenario we can utilize the `detectNew` method. - - var detector = require('gleak')(); - - x = 1; - detector.detectNew(); // ['x'] - detector.detectNew(); // [] - y = 3; - detector.detectNew(); // ['y'] - -## Configurable: - -Gleak comes configured for Node.js and will ignore built-ins by default -but you can configure it however your like: - - var gleak = require('gleak')(); - gleak.ignore(app, db); - -The `gleak.ignore` method allows us to add globals we want to ignore -while safely ignoring duplicates. - -`gleak.whitelist` is an array that holds all globals we are ignoring. -You can push to it or blow it away completely with your own list too. - - var gleak = require('gleak')(); - gleak.whitelist = [dnode, cluster]; - -Changes to your whitelists do not impact any global settings. For example: - - var gleak = require('gleak'); - var g1 = gleak(); - var g2 = gleak(); - - g1.ignore(myglobal); - g2.whitelist.indexOf(myglobal) === -1; - -`g2` does not inherit changes to `g1`s whitelist. - -## Printable - -If you don't want anything fancy and want to quickly dump all -global leaks to your console, just call `print()`. - - var gleak = require('gleak')(); - gleak.print(); // prints "Gleak!: leakedVarName" - -## Expressable - -We might want to print leaked variables to our console after each -HTTP request. This is especially helpful during development. -To accomplish this we can utilize the bundled [express](http://expressjs.com) middleware: - - var app = express.createServer(); - app.use(gleak.middleware()); - -What if we want to output to a different stream than stderr? - - app.use(gleak.middleware(stream)); - -How about customized logging formats? - - app.use(gleak.middleware('\x1b[31mLeak!\x1b[0m %s')); - -Combining formats and streams? - - app.use(gleak.middleware(stream, '\x1b[31mLeak!\x1b[0m %s')); - -## Installable - - npm install gleak - -### Node version -Compatible with Node >=v0.4 <0.5.0 - -## License - -(The MIT License) - -Copyright (c) 2011 [Aaron Heckmann](aaron.heckmann+github@gmail.com) - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/reg/node_modules/mongodb/deps/gleak/index.js b/node_modules/reg/node_modules/mongodb/deps/gleak/index.js deleted file mode 100644 index 6597707..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/gleak/index.js +++ /dev/null @@ -1,190 +0,0 @@ - -/** - * Gleak - detect global var leaks. - * @api public - */ - -module.exports = exports = function gleak () { - return new Gleak; -} - -/** - * Version. - * @api public - */ - -exports.version = '0.2.1'; - -/** - * Express middleware. - * @api public - */ - -exports.middleware = function gleakMiddleware (stream, format) { - var g = new Gleak; - - if (!format) { - switch (typeof stream) { - case 'string': - format = stream; - stream = process.stderr; - break; - case 'undefined': - format = g.format; - stream = process.stderr; - break; - default: - format = g.format; - } - } - - setTimeout(print, 1000); - - function print () { - g.detectNew().forEach(function (leak) { - stream.write(format.replace(/%s/, leak) + '\n'); - }); - } - - return function gleakMiddleware (req, res, next) { - if (res._gleak) return next(); - res._gleak = true; - - var send = res.send; - - res.send = function () { - res.send = send; - res.send.apply(res, arguments); - print(); - } - - next(); - } -} - -/** - * Gleak constructor - * @api private - */ - -function Gleak () { - this.whitelist = this.whitelist.slice(); -} - -/** - * Whitelisted globals. - * @api public - */ - -// v0.4.x -Gleak.prototype.whitelist = [ - setTimeout - , setInterval - , clearTimeout - , clearInterval - , console - , Buffer - , process - , global - , GLOBAL - , root -]; - -// check for new globals in >= v0.5x -var version = process.version.replace(/^v/, '').split('.'); -if ('0' === version[0] && version[1] > 4) { - Gleak.prototype.whitelist.push( - ArrayBuffer - , Int8Array - , Uint8Array - , Int16Array - , Uint16Array - , Int32Array - , Uint32Array - , Float32Array - , Float64Array - , DataView - , 'errno' // node >= v0.5.x hack - ) -} - -/** - * Default format. - * @api public - */ - -Gleak.prototype.format = '\x1b[31mGleak!:\x1b[0m %s'; - -/** - * Detects global variable leaks. - * @api public - */ - -Gleak.prototype.detect = function detect () { - var whitelist = this.whitelist - , ret = [] - - Object.keys(global).forEach(function (key) { - var w = whitelist.length - , bad = true - , white - - while (w--) { - white = whitelist[w]; - if (global[key] === white || 'string' === typeof white && key === white) { - bad = false; - break; - } - } - - if (bad) ret.push(key); - }); - - return ret; -}; - -/** - * Return only new leaks since the last time `detectNew` - * was run. - * @api public - */ - -Gleak.prototype.detectNew = function detectNew () { - var found = this.found || (this.found = []); - var ret = []; - - this.detect().forEach(function (leak) { - if (~found.indexOf(leak)) return; - found.push(leak); - ret.push(leak); - }); - - return ret; -} - -/** - * Prints all gleaks to stderr. - * @api public - */ - -Gleak.prototype.print = function print () { - var format = this.format; - this.detect().forEach(function (leak) { - console.error(format, leak); - }); -} - -/** - * Add items to the whitelist disallowing duplicates. - * @api public - */ - -Gleak.prototype.ignore = function ignore () { - var i = arguments.length; - while (i--) { - if (~this.whitelist.indexOf(arguments[i])) continue; - this.whitelist.push(arguments[i]); - } - return this; -} - diff --git a/node_modules/reg/node_modules/mongodb/deps/gleak/package.json b/node_modules/reg/node_modules/mongodb/deps/gleak/package.json deleted file mode 100644 index 374de40..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/gleak/package.json +++ /dev/null @@ -1,22 +0,0 @@ -{ - "author": "Aaron Heckmann ", - "name": "gleak", - "description": "Node global variable leak detector", - "version": "0.2.1", - "repository": { - "type": "git" - , "url": "git://github.com/aheckmann/gleak.git" - }, - "main": "./index.js", - "scripts": { - "test": "make test" - }, - "engines": { - "node": ">=0.4.0" - }, - "dependencies": {}, - "devDependencies": { - "express": ">=2.0.0" - , "expresso": "0.7.5" - } -} diff --git a/node_modules/reg/node_modules/mongodb/deps/gleak/test/index.js b/node_modules/reg/node_modules/mongodb/deps/gleak/test/index.js deleted file mode 100644 index 9e0bdee..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/gleak/test/index.js +++ /dev/null @@ -1,215 +0,0 @@ - -var assert = require('assert') -var express = require('express') -var gleak = require('../index') - -exports['version exists'] = function () { - assert.equal('string', typeof gleak.version); -} - -exports['middleware exists'] = function () { - assert.equal('function', typeof gleak.middleware); -} - -exports['gleak is a function'] = function () { - assert.equal('function', typeof gleak); -} - -exports['default format is correct'] = function () { - var g = gleak(); - assert.equal('\x1b[31mGleak!:\x1b[0m %s', g.format); -} - -exports['whitelist is an array'] = function () { - var g = gleak(); - assert.ok(Array.isArray(g.whitelist)); -} - -exports['setTimeout is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(setTimeout)); -}; - -exports['setInterval is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(setInterval)); -}; -exports['clearTimeout is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(clearTimeout)); -}; -exports['clearInterval is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(clearInterval)); -}; -exports['console is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(console)); -}; -exports['Buffer is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(Buffer)); -}; -exports['process is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(process)); -}; -exports['global is a default'] = function () { - var g = gleak(); - assert.ok(~g.whitelist.indexOf(global)); -}; - -exports['whitelist is mutable'] = function () { - var g = gleak(); - var i = g.whitelist.push(assert); - assert.ok(~g.whitelist.indexOf(assert)); - g.whitelist.splice(i-1, 1); - assert.ok(!~g.whitelist.indexOf(assert)); -} - -exports['#detect is a function'] = function () { - var g = gleak(); - assert.ok('function' === typeof g.detect); -} - -exports['detect()'] = function () { - var g = gleak(); - var found = g.detect(); - assert.ok(Array.isArray(found)); - assert.ok(0 === found.length); - haha = "lol" - assert.ok(1 === g.detect().length); - assert.equal("haha", g.detect()[0]); -} - -exports['unknown values can be whitelisted by passing strings'] = function () { - var g = gleak(); - ignoreme = 1; - assert.ok(~g.detect().indexOf('ignoreme')); - g.whitelist.push('ignoreme'); - assert.ok(!~g.detect().indexOf('ignoreme')); - delete global.ignoreme; -} - -exports['#ignore'] = function () { - var g = gleak(); - assert.equal('function', typeof g.ignore); -} - -exports['ignore identical whitelisted values'] = function () { - var g = gleak(); - var len = g.whitelist.length; - var an = 'another'; - g.ignore('another', 'another', 'another', an); - assert.equal(len + 1, g.whitelist.length); -} - -exports['#print'] = function () { - var g = gleak(); - var write = console.error; - var times = 0; - haha = "heh"; - console.error = function (format, item) { - assert.equal(g.format, format); - assert.equal("haha", item); - ++times; - } - g.print(); - console.error = write; - assert.equal(1, times); -} - -exports['whitelists are seperate from other instances'] = function () { - var g1 = gleak() - , g2 = gleak(); - - g1.ignore('the', 'bad'); - assert.ok(~g1.whitelist.indexOf('the')); - assert.ok(!~g2.whitelist.indexOf('the')); -} - -exports['formats are seperate from other instances'] = function () { - var g1 = gleak() - , g2 = gleak(); - - g1.format = "different %s"; - assert.ok(~g1.format !== g1.format); -} - -exports['#detectNew'] = function () { - var g = gleak(); - assert.equal('function', typeof g.detectNew); - var found = g.detectNew(); - assert.equal(true, Array.isArray(found)); - assert.equal(found.length, 1); - assert.equal(g.detectNew().length, 0); - zombocom = 'welcome'; - found = g.detectNew(); - assert.equal(found.length, 1); - assert.equal(found[0], 'zombocom'); - assert.equal(g.detectNew().length, 0); - delete global.zombocom; -} - -exports['test middleware'] = function (beforeExit) { - var called = false; - var req = {}; - var res = { send: function (x) { assert.equal(x, 'yes'); called = true; }}; - var m = gleak.middleware(); - m(req, res, function(){}); - assert.equal(res._gleak, true); - res.send('yes'); - assert.equal(true, called); - - // another leak - meToo = 47; - - // mock stream - function makeStream (tests) { - return { - i: 0 - , write: function (data) { - assert.equal(tests[this.i], data); - ++this.i; - } - } - } - - var app = express.createServer(); - - var sout = [ - '\x1b[31mGleak!:\x1b[0m haha\n' - , '\x1b[31mGleak!:\x1b[0m meToo\n' - ]; - var stream1 = makeStream(sout); - - app.get('/stream', gleak.middleware(stream1), function (req, res, next) { - res.send('passed a stream'); - }); - - var both = [ - 'yes : haha\n' - , 'yes : meToo\n' - ]; - var stream2 = makeStream(both); - - app.get('/formatstream', gleak.middleware(stream2, 'yes : %s'), function (req, res, next) { - res.send('passed format and stream'); - }); - - assert.response(app, - { url: '/stream' } - , { status: 200 - , body: 'passed a stream' }) - - assert.response(app, - { url: '/formatstream' } - , { status: 200 - , body: 'passed format and stream' }) - - beforeExit(function () { - assert.equal(stream1.i, 2); - assert.equal(stream2.i, 2); - }); -} - diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/.npmignore b/node_modules/reg/node_modules/mongodb/deps/nodeunit/.npmignore deleted file mode 100644 index 1a82501..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/.npmignore +++ /dev/null @@ -1,3 +0,0 @@ -dist -stamp-build -test/fixtures/dir2 diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/CONTRIBUTORS.md b/node_modules/reg/node_modules/mongodb/deps/nodeunit/CONTRIBUTORS.md deleted file mode 100644 index fba3609..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/CONTRIBUTORS.md +++ /dev/null @@ -1,68 +0,0 @@ -Nodeunit contributors (sorted alphabeticaly) -============================================ - -* **[Alex Gorbatchev](https://github.com/alexgorbatchev)** - - * Deeper default object inspection - * Timeout to ensure flushing of console output (default reporter) - -* **[Alex Wolfe](https://github.com/alexkwolfe)** - - * HTML test reporter - -* **[Caolan McMahon](https://github.com/caolan)** - - * Author and maintainer - * Most features develpopment - -* **[Carl Fürstenberg](https://github.com/azatoth)** - - * Debian-friendly Makefile, supports both 'node' and 'nodejs' executables - * Sandbox utility - * Minimal test reporter - -* **[Gerad Suyderhoud](https://github.com/gerad)** - - * First comand-line tool - -* **[Kadir Pekel](https://github.com/kadirpekel)** - - * Improvements to default test reporter - * HTTP test utility - -* **[Λlisue](https://github.com/lambdalisue)** - - * Add machineout reporter - -* **[Matthias Lübken](https://github.com/luebken)** - - * Utility functions for tracking incomplete tests on exit - -* **[Oleg Efimov](https://github.com/Sannis)** - - * Adding 'make lint' and fixing nodelint errors - * Option parsing, --help text and config file support - * Reporters option for command-line tool - -* **[Orlando Vazquez](https://github.com/orlandov)** - - * Added jUnit XML reporter - -* **[Ryan Dahl](https://github.com/ry)** - - * Add package.json - -* **[Sam Stephenson](https://github.com/sstephenson)** - - * Coffee-script support - -* **[Thomas Mayfield](https://github.com/thegreatape)** - - * Async setUp and tearDown support for testCase - -* **[Maciej Małecki](https://github.com/mmalecki)** - - * Removal of `testCase` - -**[Full contributors list](https://github.com/caolan/nodeunit/contributors).** - diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/LICENSE b/node_modules/reg/node_modules/mongodb/deps/nodeunit/LICENSE deleted file mode 100644 index b7f9d50..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2010 Caolan McMahon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/Makefile b/node_modules/reg/node_modules/mongodb/deps/nodeunit/Makefile deleted file mode 100644 index 31fdb0e..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/Makefile +++ /dev/null @@ -1,176 +0,0 @@ -PACKAGE = nodeunit -NODEJS = $(if $(shell test -f /usr/bin/nodejs && echo "true"),nodejs,node) - -PREFIX ?= /usr/local -BINDIR ?= $(PREFIX)/bin -DATADIR ?= $(PREFIX)/share -MANDIR ?= $(PREFIX)/share/man -LIBDIR ?= $(PREFIX)/lib -NODEJSLIBDIR ?= $(LIBDIR)/$(NODEJS) - -BUILDDIR = dist - -DOCS = $(shell find doc -name '*.md' \ - |sed 's|.md|.1|g' \ - |sed 's|doc/|man1/|g' \ - ) - - -$(shell if [ ! -d $(BUILDDIR) ]; then mkdir $(BUILDDIR); fi) - -all: build doc - -browser: - # super hacky build script for browser version! - mkdir -p $(BUILDDIR)/browser - rm -rf $(BUILDDIR)/browser/* - # build browser version of nodeunit.js - cat share/license.js >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit = (function(){" >> $(BUILDDIR)/browser/nodeunit.js - cat deps/json2.js >> $(BUILDDIR)/browser/nodeunit.js - # make assert global - echo "var assert = this.assert = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var types = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var core = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var nodeunit = {};" >> $(BUILDDIR)/browser/nodeunit.js - echo "var reporter = {};" >> $(BUILDDIR)/browser/nodeunit.js - cat deps/async.js >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/assert.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(assert);" >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/types.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(types);" >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/core.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(core);" >> $(BUILDDIR)/browser/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/browser/nodeunit.js - cat lib/reporters/browser.js >> $(BUILDDIR)/browser/nodeunit.js - echo "})(reporter);" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit = core;" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit.assert = assert;" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit.reporter = reporter;" >> $(BUILDDIR)/browser/nodeunit.js - echo "nodeunit.run = reporter.run;" >> $(BUILDDIR)/browser/nodeunit.js - echo "return nodeunit; })();" >> $(BUILDDIR)/browser/nodeunit.js - cp $(BUILDDIR)/browser/nodeunit.js $(BUILDDIR)/browser/.nodeunit.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.nodeunit.js > $(BUILDDIR)/browser/nodeunit.js - rm $(BUILDDIR)/browser/.nodeunit.js - # copy nodeunit.css - cp share/nodeunit.css $(BUILDDIR)/browser/nodeunit.css - # create nodeunit.min.js - node_modules/uglify-js/bin/uglifyjs $(BUILDDIR)/browser/nodeunit.js > $(BUILDDIR)/browser/nodeunit.min.js - # create test scripts - mkdir -p $(BUILDDIR)/browser/test - cp test/test.html $(BUILDDIR)/browser/test/test.html - # test-base.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-base.js - cat test/test-base.js >> $(BUILDDIR)/browser/test/test-base.js - echo "})(this.test_base = {});" >> $(BUILDDIR)/browser/test/test-base.js - cp $(BUILDDIR)/browser/test/test-base.js $(BUILDDIR)/browser/.test-base.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-base.js > $(BUILDDIR)/browser/test/test-base.js - rm $(BUILDDIR)/browser/.test-base.js - # test-runmodule.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-runmodule.js - cat test/test-runmodule.js >> $(BUILDDIR)/browser/test/test-runmodule.js - echo "})(this.test_runmodule = {});" >> $(BUILDDIR)/browser/test/test-runmodule.js - cp $(BUILDDIR)/browser/test/test-runmodule.js $(BUILDDIR)/browser/.test-runmodule.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-runmodule.js > $(BUILDDIR)/browser/test/test-runmodule.js - rm $(BUILDDIR)/browser/.test-runmodule.js - # test-runtest.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-runtest.js - cat test/test-runtest.js >> $(BUILDDIR)/browser/test/test-runtest.js - echo "})(this.test_runtest = {});" >> $(BUILDDIR)/browser/test/test-runtest.js - cp $(BUILDDIR)/browser/test/test-runtest.js $(BUILDDIR)/browser/.test-runtest.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-runtest.js > $(BUILDDIR)/browser/test/test-runtest.js - rm $(BUILDDIR)/browser/.test-runtest.js - # test-testcase.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-testcase.js - cat test/test-testcase.js >> $(BUILDDIR)/browser/test/test-testcase.js - echo "})(this.test_testcase = {});" >> $(BUILDDIR)/browser/test/test-testcase.js - cp $(BUILDDIR)/browser/test/test-testcase.js $(BUILDDIR)/browser/.test-testcase.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-testcase.js > $(BUILDDIR)/browser/test/test-testcase.js - rm $(BUILDDIR)/browser/.test-testcase.js - # test-testcase-legacy.js - echo "(function (exports) {" > $(BUILDDIR)/browser/test/test-testcase-legacy.js - cat test/test-testcase-legacy.js >> $(BUILDDIR)/browser/test/test-testcase-legacy.js - echo "})(this.test_testcase_legacy = {});" >> $(BUILDDIR)/browser/test/test-testcase-legacy.js - cp $(BUILDDIR)/browser/test/test-testcase-legacy.js $(BUILDDIR)/browser/.test-testcase-legacy.js - sed "/\@REMOVE_LINE_FOR_BROWSER/d" <$(BUILDDIR)/browser/.test-testcase-legacy.js > $(BUILDDIR)/browser/test/test-testcase-legacy.js - rm $(BUILDDIR)/browser/.test-testcase-legacy.js - # copy nodeunit.js to dist/browser/test to make it easier for me to host and - # run on windows VMs with IE - cp $(BUILDDIR)/browser/nodeunit.js $(BUILDDIR)/browser/test/nodeunit.js - cp $(BUILDDIR)/browser/nodeunit.css $(BUILDDIR)/browser/test/nodeunit.css - -commonjs: - # super hacky build script for browser commonjs version! - ##### make commonjs browser module ###### - mkdir -p $(BUILDDIR)/commonjs - mkdir -p $(BUILDDIR)/commonjs/deps - cp deps/json2.js $(BUILDDIR)/commonjs/deps - cp deps/async.js $(BUILDDIR)/commonjs/deps - echo "var async = require('async');" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var assert = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var types = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var core = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var nodeunit = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "var reporter = {};" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/assert.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(assert);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/types.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(types);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/core.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(core);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports = core;" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "(function(exports, nodeunit){" >> $(BUILDDIR)/commonjs/nodeunit.js - cat lib/reporters/browser.js >> $(BUILDDIR)/commonjs/nodeunit.js - echo "})(reporter, module.exports);" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports.assert = assert;" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports.reporter = reporter;" >> $(BUILDDIR)/commonjs/nodeunit.js - echo "module.exports.run = reporter.run;" >> $(BUILDDIR)/commonjs/nodeunit.js - sed -i "/\@REMOVE_LINE_FOR_BROWSER/d" $(BUILDDIR)/commonjs/nodeunit.js - sed -i "/\@REMOVE_LINE_FOR_COMMONJS/d" $(BUILDDIR)/commonjs/nodeunit.js - ##### end of commonjs browser module ##### - -build: stamp-build - -stamp-build: $(wildcard deps/* lib/*.js) - touch $@; - mkdir -p $(BUILDDIR)/nodeunit - cp -R bin node_modules deps index.js lib package.json share $(BUILDDIR)/nodeunit - printf '#!/bin/sh\n$(NODEJS) $(NODEJSLIBDIR)/$(PACKAGE)/bin/nodeunit $$@' > $(BUILDDIR)/nodeunit.sh - -test: - $(NODEJS) ./bin/nodeunit test - -install: build - install -d $(NODEJSLIBDIR) - cp -a $(BUILDDIR)/nodeunit $(NODEJSLIBDIR) - install -m 0755 $(BUILDDIR)/nodeunit.sh $(BINDIR)/nodeunit - install -d $(MANDIR)/man1/ - cp -a man1/nodeunit.1 $(MANDIR)/man1/ - -uninstall: - rm -rf $(NODEJSLIBDIR)/nodeunit $(NODEJSLIBDIR)/nodeunit.js $(BINDIR)/nodeunit - rm -rf $(MANDIR)/man1/nodeunit.1 - -clean: - rm -rf $(BUILDDIR) stamp-build - -lint: - nodelint --config nodelint.cfg ./index.js ./bin/nodeunit ./bin/nodeunit.json ./lib/*.js ./lib/reporters/*.js ./test/*.js - -doc: man1 $(DOCS) - @true - -man1: - @if ! test -d man1 ; then mkdir -p man1 ; fi - -# use `npm install ronn` for this to work. -man1/%.1: doc/%.md - ronn --roff $< > $@ - -.PHONY: browser test install uninstall build all diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/README.md b/node_modules/reg/node_modules/mongodb/deps/nodeunit/README.md deleted file mode 100644 index 359a9c7..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/README.md +++ /dev/null @@ -1,443 +0,0 @@ -Nodeunit -======== - -Simple syntax, powerful tools. Nodeunit provides easy async unit testing for -node.js and the browser. - -* Simple to use -* Just export the tests from a module -* Works with node.js and in the browser. -* Helps you avoid common pitfalls when testing asynchronous code -* Easy to add test cases with setUp and tearDown functions if you wish -* Flexible reporters for custom output, built-in support for HTML and jUnit XML -* Allows the use of mocks and stubs - -__Contributors__ - -* [alexgorbatchev](https://github.com/alexgorbatchev) -* [alexkwolfe](https://github.com/alexkwolfe) -* [azatoth](https://github.com/azatoth) -* [kadirpekel](https://github.com/kadirpekel) -* [lambdalisue](https://github.com/lambdalisue) -* [luebken](https://github.com/luebken) -* [orlandov](https://github.com/orlandov) -* [Sannis](https://github.com/Sannis) -* [sstephenson](https://github.com/sstephenson) -* [thegreatape](https://github.com/thegreatape) -* [mmalecki](https://github.com/mmalecki) -* and thanks to [cjohansen](https://github.com/cjohansen) for input and advice - on implementing setUp and tearDown functions. See - [cjohansen's fork](https://github.com/cjohansen/nodeunit). - -Also, check out gerad's [nodeunit-dsl](https://github.com/gerad/nodeunit-dsl) -project, which implements a 'pretty dsl on top of nodeunit'. - -More contributor information can be found in the -[CONTRIBUTORS.md](https://github.com/caolan/nodeunit/blob/master/CONTRIBUTORS.md) -file. - -Usage ------ - -Here is an example unit test module: - - exports.testSomething = function(test){ - test.expect(1); - test.ok(true, "this assertion should pass"); - test.done(); - }; - - exports.testSomethingElse = function(test){ - test.ok(false, "this assertion should fail"); - test.done(); - }; - -When run using the included test runner, this will output the following: - - - -Installation ------------- - -There are two options for installing nodeunit: - -1. Clone / download nodeunit from [github](https://github.com/caolan/nodeunit), - then: - - make && sudo make install - -2. Install via npm: - - npm install nodeunit - -API Documentation ------------------ - -Nodeunit uses the functions available in the node.js -[assert module](http://nodejs.org/docs/v0.4.2/api/assert.html): - -* __ok(value, [message])__ - Tests if value is a true value. -* __equal(actual, expected, [message])__ - Tests shallow, coercive equality - with the equal comparison operator ( == ). -* __notEqual(actual, expected, [message])__ - Tests shallow, coercive - non-equality with the not equal comparison operator ( != ). -* __deepEqual(actual, expected, [message])__ - Tests for deep equality. -* __notDeepEqual(actual, expected, [message])__ - Tests for any deep - inequality. -* __strictEqual(actual, expected, [message])__ - Tests strict equality, as - determined by the strict equality operator ( === ) -* __notStrictEqual(actual, expected, [message])__ - Tests strict non-equality, - as determined by the strict not equal operator ( !== ) -* __throws(block, [error], [message])__ - Expects block to throw an error. -* __doesNotThrow(block, [error], [message])__ - Expects block not to throw an - error. -* __ifError(value)__ - Tests if value is not a false value, throws if it is a - true value. Useful when testing the first argument, error in callbacks. - -Nodeunit also provides the following functions within tests: - -* __expect(amount)__ - Specify how many assertions are expected to run within a - test. Very useful for ensuring that all your callbacks and assertions are - run. -* __done()__ - Finish the current test function, and move on to the next. ALL - tests should call this! - -Nodeunit aims to be simple and easy to learn. This is achieved through using -existing structures (such as node.js modules) to maximum effect, and reducing -the API where possible, to make it easier to digest. - -Tests are simply exported from a module, but they are still run in the order -they are defined. - -__Note:__ Users of old nodeunit versions may remember using ok, equals and same -in the style of qunit, instead of the assert functions above. These functions -still exist for backwards compatibility, and are simply aliases to their assert -module counterparts. - - -Asynchronous Testing --------------------- - -When testing asynchronous code, there are a number of sharp edges to watch out -for. Thankfully, nodeunit is designed to help you avoid as many of these -pitfalls as possible. For the most part, testing asynchronous code in nodeunit -_just works_. - - -### Tests run in series - -While running tests in parallel seems like a good idea for speeding up your -test suite, in practice I've found it means writing much more complicated -tests. Because of node's module cache, running tests in parallel means mocking -and stubbing is pretty much impossible. One of the nicest things about testing -in javascript is the ease of doing stubs: - - var _readFile = fs.readFile; - fs.readFile = function(path, callback){ - // its a stub! - }; - // test function that uses fs.readFile - - // we're done - fs.readFile = _readFile; - -You cannot do this when running tests in parallel. In order to keep testing as -simple as possible, nodeunit avoids it. Thankfully, most unit-test suites run -fast anyway. - - -### Explicit ending of tests - -When testing async code its important that tests end at the correct point, not -just after a given number of assertions. Otherwise your tests can run short, -ending before all assertions have completed. Its important to detect too -many assertions as well as too few. Combining explicit ending of tests with -an expected number of assertions helps to avoid false test passes, so be sure -to use the test.expect() method at the start of your test functions, and -test.done() when finished. - - -Groups, setUp and tearDown --------------------------- - -Nodeunit allows the nesting of test functions: - - exports.test1 = function (test) { - ... - } - - exports.group = { - test2: function (test) { - ... - }, - test3: function (test) { - ... - } - } - -This would be run as: - - test1 - group - test2 - group - test3 - -Using these groups, Nodeunit allows you to define a `setUp` function, which is -run before each test, and a `tearDown` function, which is run after each test -calls `test.done()`: - - module.exports = { - setUp: function (callback) { - this.foo = 'bar'; - callback(); - }, - tearDown: function (callback) { - // clean up - callback(); - }, - test1: function (test) { - test.equals(this.foo, 'bar'); - test.done(); - } - }; - -In this way, its possible to have multiple groups of tests in a module, each -group with its own setUp and tearDown functions. - - -Running Tests -------------- - -Nodeunit comes with a basic command-line test runner, which can be installed -using 'sudo make install'. Example usage: - - nodeunit testmodule1.js testfolder [...] - -The default test reporter uses color output, because I think that's more fun :) I -intend to add a no-color option in future. To give you a feeling of the fun you'll -be having writing tests, lets fix the example at the start of the README: - - - -Ahhh, Doesn't that feel better? - -When using the included test runner, it will exit using the failed number of -assertions as the exit code. Exiting with 0 when all tests pass. - - -### Command-line Options - -* __--reporter FILE__ - you can set the test reporter to a custom module or -on of the modules in nodeunit/lib/reporters, when omitted, the default test runner -is used. -* __--list-reporters__ - list available build-in reporters. -* __--config FILE__ - load config options from a JSON file, allows -the customisation of color schemes for the default test reporter etc. See -bin/nodeunit.json for current available options. -* __--version__ or __-v__ - report nodeunit version -* __--help__ - show nodeunit help - - -Running tests in the browser ----------------------------- - -Nodeunit tests can also be run inside the browser. For example usage, see -the examples/browser folder. The basic syntax is as follows: - -__test.html__ - - - - Example Test Suite - - - - - - -

- - -nodeunit with vim -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -There is [nodeunit.vim](https://github.com/lambdalisue/nodeunit.vim) so you can use nodeunit with VIM. -That compiler use __machineout__ reporter and it is useful to use with [vim-makegreen](https://github.com/reinh/vim-makegreen) - - - -Contributing ------------- - -Contributions to the project are most welcome, so feel free to fork and improve. -When submitting a pull request, please run 'make lint' first to ensure -we're following a consistent coding style. diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/bin/nodeunit b/node_modules/reg/node_modules/mongodb/deps/nodeunit/bin/nodeunit deleted file mode 100644 index b11cfb1..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/bin/nodeunit +++ /dev/null @@ -1,125 +0,0 @@ -#!/usr/bin/env node - -var - fs = require('fs'), - path = require('path'); - -// TODO: remove this when https://github.com/joyent/node/pull/1312 -// lands in core. -// -// Until then, use console.log from npm (https://gist.github.com/1077544) -require('../deps/console.log'); - -//require.paths.push(process.cwd()); -var args = (process.ARGV || process.argv).slice(2); - -var files = []; - -var testrunner, - config_file, - config_param_found = false, - output_param_found = false, - reporter_file = 'default', - reporter_param_found = false, - testspec_param_found = false; - -var usage = "Usage: nodeunit [options] testmodule1.js testfolder [...] \n" + - "Options:\n\n" + - " --config FILE the path to a JSON file with options\n" + - " --reporter FILE optional path to a reporter file to customize the output\n" + - " --list-reporters list available build-in reporters\n" + - " -t name, specify a test to run\n" + - " -h, --help display this help and exit\n" + - " -v, --version output version information and exit"; - - -// load default options -var content = fs.readFileSync(__dirname + '/nodeunit.json', 'utf8'); -var options = JSON.parse(content); - -// a very basic pseudo --options parser -args.forEach(function (arg) { - if (arg.slice(0, 9) === "--config=") { - config_file = arg.slice(9); - } else if (arg === '--config') { - config_param_found = true; - } else if (config_param_found) { - config_file = arg; - config_param_found = false; - } else if (arg.slice(0, 9) === "--output=") { - options.output = arg.slice(9); - } else if (arg === '--output') { - output_param_found = true; - } else if (output_param_found) { - options.output = arg; - output_param_found = false; - } else if (arg.slice(0, 11) === "--reporter=") { - reporter_file = arg.slice(11); - } else if (arg === '--reporter') { - reporter_param_found = true; - } else if (reporter_param_found) { - reporter_file = arg; - reporter_param_found = false; - } else if (arg === '-t') { - testspec_param_found = true; - } else if (testspec_param_found) { - options.testspec = arg; - testspec_param_found = false; - } else if (arg === '--list-reporters') { - var reporters = fs.readdirSync(__dirname + '/../lib/reporters'); - reporters = reporters.filter(function (reporter_file) { - return (/\.js$/).test(reporter_file); - }).map(function (reporter_file) { - return reporter_file.replace(/\.js$/, ''); - }).filter(function (reporter_file) { - return reporter_file !== 'index'; - }); - console.log('Build-in reporters: '); - reporters.forEach(function (reporter_file) { - var reporter = require('../lib/reporters/' + reporter_file); - console.log(' * ' + reporter_file + (reporter.info ? ': ' + reporter.info : '')); - }); - process.exit(0); - } else if ((arg === '-v') || (arg === '--version')) { - var content = fs.readFileSync(__dirname + '/../package.json', 'utf8'); - var pkg = JSON.parse(content); - console.log(pkg.version); - process.exit(0); - } else if ((arg === '-h') || (arg === '--help')) { - console.log(usage); - process.exit(0); - } else { - files.push(arg); - } -}); - -if (files.length === 0) { - console.log('Files required.'); - console.log(usage); - process.exit(1); -} - -if (config_file) { - content = fs.readFileSync(config_file, 'utf8'); - var custom_options = JSON.parse(content); - - for (var option in custom_options) { - if (typeof option === 'string') { - options[option] = custom_options[option]; - } - } -} - -var builtin_reporters = require(__dirname + '/../lib/reporters'); -if (reporter_file in builtin_reporters) { - testrunner = builtin_reporters[reporter_file]; -} -else { - testrunner = require(reporter_file); -} - -testrunner.run(files, options, function(err) { - if (err) { - process.exit(1); - } -}); diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/bin/nodeunit.json b/node_modules/reg/node_modules/mongodb/deps/nodeunit/bin/nodeunit.json deleted file mode 100644 index 5c7778f..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/bin/nodeunit.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "error_prefix": "\u001B[31m", - "error_suffix": "\u001B[39m", - "ok_prefix": "\u001B[32m", - "ok_suffix": "\u001B[39m", - "bold_prefix": "\u001B[1m", - "bold_suffix": "\u001B[22m", - "assertion_prefix": "\u001B[35m", - "assertion_suffix": "\u001B[39m" -} diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/async.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/async.js deleted file mode 100644 index d81255f..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/async.js +++ /dev/null @@ -1,623 +0,0 @@ -/*global setTimeout: false, console: false */ -(function () { - - var async = {}; - - // global on the server, window in the browser - var root = this, - previous_async = root.async; - - if (typeof module !== 'undefined' && module.exports) { - module.exports = async; - } - else { - root.async = async; - } - - async.noConflict = function () { - root.async = previous_async; - return async; - }; - - //// cross-browser compatiblity functions //// - - var _forEach = function (arr, iterator) { - if (arr.forEach) { - return arr.forEach(iterator); - } - for (var i = 0; i < arr.length; i += 1) { - iterator(arr[i], i, arr); - } - }; - - var _map = function (arr, iterator) { - if (arr.map) { - return arr.map(iterator); - } - var results = []; - _forEach(arr, function (x, i, a) { - results.push(iterator(x, i, a)); - }); - return results; - }; - - var _reduce = function (arr, iterator, memo) { - if (arr.reduce) { - return arr.reduce(iterator, memo); - } - _forEach(arr, function (x, i, a) { - memo = iterator(memo, x, i, a); - }); - return memo; - }; - - var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; - }; - - var _indexOf = function (arr, item) { - if (arr.indexOf) { - return arr.indexOf(item); - } - for (var i = 0; i < arr.length; i += 1) { - if (arr[i] === item) { - return i; - } - } - return -1; - }; - - //// exported async module functions //// - - //// nextTick implementation with browser-compatible fallback //// - if (typeof process === 'undefined' || !(process.nextTick)) { - async.nextTick = function (fn) { - setTimeout(fn, 0); - }; - } - else { - async.nextTick = process.nextTick; - } - - async.forEach = function (arr, iterator, callback) { - if (!arr.length) { - return callback(); - } - var completed = 0; - _forEach(arr, function (x) { - iterator(x, function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed === arr.length) { - callback(); - } - } - }); - }); - }; - - async.forEachSeries = function (arr, iterator, callback) { - if (!arr.length) { - return callback(); - } - var completed = 0; - var iterate = function () { - iterator(arr[completed], function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - completed += 1; - if (completed === arr.length) { - callback(); - } - else { - iterate(); - } - } - }); - }; - iterate(); - }; - - - var doParallel = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.forEach].concat(args)); - }; - }; - var doSeries = function (fn) { - return function () { - var args = Array.prototype.slice.call(arguments); - return fn.apply(null, [async.forEachSeries].concat(args)); - }; - }; - - - var _asyncMap = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (err, v) { - results[x.index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - }; - async.map = doParallel(_asyncMap); - async.mapSeries = doSeries(_asyncMap); - - - // reduce only has a series version, as doing reduce in parallel won't - // work in many situations. - async.reduce = function (arr, memo, iterator, callback) { - async.forEachSeries(arr, function (x, callback) { - iterator(memo, x, function (err, v) { - memo = v; - callback(err); - }); - }, function (err) { - callback(err, memo); - }); - }; - // inject alias - async.inject = async.reduce; - // foldl alias - async.foldl = async.reduce; - - async.reduceRight = function (arr, memo, iterator, callback) { - var reversed = _map(arr, function (x) { - return x; - }).reverse(); - async.reduce(reversed, memo, iterator, callback); - }; - // foldr alias - async.foldr = async.reduceRight; - - var _filter = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.filter = doParallel(_filter); - async.filterSeries = doSeries(_filter); - // select alias - async.select = async.filter; - async.selectSeries = async.filterSeries; - - var _reject = function (eachfn, arr, iterator, callback) { - var results = []; - arr = _map(arr, function (x, i) { - return {index: i, value: x}; - }); - eachfn(arr, function (x, callback) { - iterator(x.value, function (v) { - if (!v) { - results.push(x); - } - callback(); - }); - }, function (err) { - callback(_map(results.sort(function (a, b) { - return a.index - b.index; - }), function (x) { - return x.value; - })); - }); - }; - async.reject = doParallel(_reject); - async.rejectSeries = doSeries(_reject); - - var _detect = function (eachfn, arr, iterator, main_callback) { - eachfn(arr, function (x, callback) { - iterator(x, function (result) { - if (result) { - main_callback(x); - } - else { - callback(); - } - }); - }, function (err) { - main_callback(); - }); - }; - async.detect = doParallel(_detect); - async.detectSeries = doSeries(_detect); - - async.some = function (arr, iterator, main_callback) { - async.forEach(arr, function (x, callback) { - iterator(x, function (v) { - if (v) { - main_callback(true); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(false); - }); - }; - // any alias - async.any = async.some; - - async.every = function (arr, iterator, main_callback) { - async.forEach(arr, function (x, callback) { - iterator(x, function (v) { - if (!v) { - main_callback(false); - main_callback = function () {}; - } - callback(); - }); - }, function (err) { - main_callback(true); - }); - }; - // all alias - async.all = async.every; - - async.sortBy = function (arr, iterator, callback) { - async.map(arr, function (x, callback) { - iterator(x, function (err, criteria) { - if (err) { - callback(err); - } - else { - callback(null, {value: x, criteria: criteria}); - } - }); - }, function (err, results) { - if (err) { - return callback(err); - } - else { - var fn = function (left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - }; - callback(null, _map(results.sort(fn), function (x) { - return x.value; - })); - } - }); - }; - - async.auto = function (tasks, callback) { - callback = callback || function () {}; - var keys = _keys(tasks); - if (!keys.length) { - return callback(null); - } - - var completed = []; - - var listeners = []; - var addListener = function (fn) { - listeners.unshift(fn); - }; - var removeListener = function (fn) { - for (var i = 0; i < listeners.length; i += 1) { - if (listeners[i] === fn) { - listeners.splice(i, 1); - return; - } - } - }; - var taskComplete = function () { - _forEach(listeners, function (fn) { - fn(); - }); - }; - - addListener(function () { - if (completed.length === keys.length) { - callback(null); - } - }); - - _forEach(keys, function (k) { - var task = (tasks[k] instanceof Function) ? [tasks[k]]: tasks[k]; - var taskCallback = function (err) { - if (err) { - callback(err); - // stop subsequent errors hitting callback multiple times - callback = function () {}; - } - else { - completed.push(k); - taskComplete(); - } - }; - var requires = task.slice(0, Math.abs(task.length - 1)) || []; - var ready = function () { - return _reduce(requires, function (a, x) { - return (a && _indexOf(completed, x) !== -1); - }, true); - }; - if (ready()) { - task[task.length - 1](taskCallback); - } - else { - var listener = function () { - if (ready()) { - removeListener(listener); - task[task.length - 1](taskCallback); - } - }; - addListener(listener); - } - }); - }; - - async.waterfall = function (tasks, callback) { - if (!tasks.length) { - return callback(); - } - callback = callback || function () {}; - var wrapIterator = function (iterator) { - return function (err) { - if (err) { - callback(err); - callback = function () {}; - } - else { - var args = Array.prototype.slice.call(arguments, 1); - var next = iterator.next(); - if (next) { - args.push(wrapIterator(next)); - } - else { - args.push(callback); - } - async.nextTick(function () { - iterator.apply(null, args); - }); - } - }; - }; - wrapIterator(async.iterator(tasks))(); - }; - - async.parallel = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.map(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args || null); - }); - } - }, callback); - } - else { - var results = {}; - async.forEach(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.series = function (tasks, callback) { - callback = callback || function () {}; - if (tasks.constructor === Array) { - async.mapSeries(tasks, function (fn, callback) { - if (fn) { - fn(function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - callback.call(null, err, args || null); - }); - } - }, callback); - } - else { - var results = {}; - async.forEachSeries(_keys(tasks), function (k, callback) { - tasks[k](function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (args.length <= 1) { - args = args[0]; - } - results[k] = args; - callback(err); - }); - }, function (err) { - callback(err, results); - }); - } - }; - - async.iterator = function (tasks) { - var makeCallback = function (index) { - var fn = function () { - if (tasks.length) { - tasks[index].apply(null, arguments); - } - return fn.next(); - }; - fn.next = function () { - return (index < tasks.length - 1) ? makeCallback(index + 1): null; - }; - return fn; - }; - return makeCallback(0); - }; - - async.apply = function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - return function () { - return fn.apply( - null, args.concat(Array.prototype.slice.call(arguments)) - ); - }; - }; - - var _concat = function (eachfn, arr, fn, callback) { - var r = []; - eachfn(arr, function (x, cb) { - fn(x, function (err, y) { - r = r.concat(y || []); - cb(err); - }); - }, function (err) { - callback(err, r); - }); - }; - async.concat = doParallel(_concat); - async.concatSeries = doSeries(_concat); - - async.whilst = function (test, iterator, callback) { - if (test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.whilst(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.until = function (test, iterator, callback) { - if (!test()) { - iterator(function (err) { - if (err) { - return callback(err); - } - async.until(test, iterator, callback); - }); - } - else { - callback(); - } - }; - - async.queue = function (worker, concurrency) { - var workers = 0; - var tasks = []; - var q = { - concurrency: concurrency, - push: function (data, callback) { - tasks.push({data: data, callback: callback}); - async.nextTick(q.process); - }, - process: function () { - if (workers < q.concurrency && tasks.length) { - var task = tasks.splice(0, 1)[0]; - workers += 1; - worker(task.data, function () { - workers -= 1; - if (task.callback) { - task.callback.apply(task, arguments); - } - q.process(); - }); - } - }, - length: function () { - return tasks.length; - } - }; - return q; - }; - - var _console_fn = function (name) { - return function (fn) { - var args = Array.prototype.slice.call(arguments, 1); - fn.apply(null, args.concat([function (err) { - var args = Array.prototype.slice.call(arguments, 1); - if (typeof console !== 'undefined') { - if (err) { - if (console.error) { - console.error(err); - } - } - else if (console[name]) { - _forEach(args, function (x) { - console[name](x); - }); - } - } - }])); - }; - }; - async.log = _console_fn('log'); - async.dir = _console_fn('dir'); - /*async.info = _console_fn('info'); - async.warn = _console_fn('warn'); - async.error = _console_fn('error');*/ - - async.memoize = function (fn, hasher) { - var memo = {}; - hasher = hasher || function (x) { - return x; - }; - return function () { - var args = Array.prototype.slice.call(arguments); - var callback = args.pop(); - var key = hasher.apply(null, args); - if (key in memo) { - callback.apply(null, memo[key]); - } - else { - fn.apply(null, args.concat([function () { - memo[key] = arguments; - callback.apply(null, arguments); - }])); - } - }; - }; - -}()); diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/console.log.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/console.log.js deleted file mode 100644 index fe146c1..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/console.log.js +++ /dev/null @@ -1,55 +0,0 @@ -/* - A console.log that won't leave you hanging when node exits - 90% of this file was ripped from node.js - - License: see: https://github.com/joyent/node/blob/master/lib/console.js - */ - - // console object -var formatRegExp = /%[sdj]/g; -function format(f) { - var util = require('util'); - - if (typeof f !== 'string') { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(util.inspect(arguments[i])); - } - return objects.join(' '); - } - - - var i = 1; - var args = arguments; - var str = String(f).replace(formatRegExp, function(x) { - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': return JSON.stringify(args[i++]); - default: - return x; - } - }); - for (var len = args.length, x = args[i]; i < len; x = args[++i]) { - if (x === null || typeof x !== 'object') { - str += ' ' + x; - } else { - str += ' ' + util.inspect(x); - } - } - return str; -} - -console.log = function() { - var res = process.stdout.write(format.apply(this, arguments) + '\n'); - - // this is the first time stdout got backed up - if (!res && !process.stdout.pendingWrite) { - process.stdout.pendingWrite = true; - - // magic sauce: keep node alive until stdout has flushed - process.stdout.once('drain', function () { - process.stdout.draining = false; - }); - } -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/History.md b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/History.md deleted file mode 100644 index 00d2b5b..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/History.md +++ /dev/null @@ -1,70 +0,0 @@ - -0.4.3 / 2011-06-20 -================== - - * Fixed stacktraces line number when used multiline js expressions [Octave] - -0.4.2 / 2011-05-11 -================== - - * Added client side support - -0.4.1 / 2011-04-21 -================== - - * Fixed error context - -0.4.0 / 2011-04-21 -================== - - * Added; ported jade's error reporting to ejs. [slaskis] - -0.3.1 / 2011-02-23 -================== - - * Fixed optional `compile()` options - -0.3.0 / 2011-02-14 -================== - - * Added 'json' filter [Yuriy Bogdanov] - * Use exported version of parse function to allow monkey-patching [Anatoliy Chakkaev] - -0.2.1 / 2010-10-07 -================== - - * Added filter support - * Fixed _cache_ option. ~4x performance increase - -0.2.0 / 2010-08-05 -================== - - * Added support for global tag config - * Added custom tag support. Closes #5 - * Fixed whitespace bug. Closes #4 - -0.1.0 / 2010-08-04 -================== - - * Faster implementation [ashleydev] - -0.0.4 / 2010-08-02 -================== - - * Fixed single quotes for content outside of template tags. [aniero] - * Changed; `exports.compile()` now expects only "locals" - -0.0.3 / 2010-07-15 -================== - - * Fixed single quotes - -0.0.2 / 2010-07-09 -================== - - * Fixed newline preservation - -0.0.1 / 2010-07-09 -================== - - * Initial release diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/Makefile b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/Makefile deleted file mode 100644 index a8b00d9..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/Makefile +++ /dev/null @@ -1,20 +0,0 @@ - -SRC = $(shell find lib -name "*.js" -type f) -UGLIFY_FLAGS = --no-mangle - -test: - @./node_modules/.bin/expresso test/*.test.js - -ejs.js: $(SRC) - @node support/compile.js $^ - -ejs.min.js: ejs.js - @uglifyjs $(UGLIFY_FLAGS) $< > $@ \ - && du ejs.min.js \ - && du ejs.js - -clean: - rm -f ejs.js - rm -f ejs.min.js - -.PHONY: test \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/Readme.md b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/Readme.md deleted file mode 100644 index 58cb10a..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/Readme.md +++ /dev/null @@ -1,152 +0,0 @@ - -# EJS - -Embedded JavaScript templates. - -## Installation - - $ npm install ejs - -## Features - - * Complies with the [Express](http://expressjs.com) view system - * Static caching of intermediate JavaScript - * Unbuffered code for conditionals etc `<% code %>` - * Escapes html by default with `<%= code %>` - * Unescaped buffering with `<%- code %>` - * Supports tag customization - * Filter support for designer-friendly templates - * Client-side support - -## Example - - <% if (user) { %> -

<%= user.name %>

- <% } %> - -## Usage - - ejs.compile(str, options); - // => Function - - ejs.render(str, options); - // => str - -## Options - - - `locals` Local variables object - - `cache` Compiled functions are cached, requires `filename` - - `filename` Used by `cache` to key caches - - `scope` Function execution context - - `debug` Output generated function body - - `open` Open tag, defaulting to "<%" - - `close` Closing tag, defaulting to "%>" - -## Custom tags - -Custom tags can also be applied globally: - - var ejs = require('ejs'); - ejs.open = '{{'; - ejs.close = '}}'; - -Which would make the following a valid template: - -

{{= title }}

- -## Filters - -EJS conditionally supports the concept of "filters". A "filter chain" -is a designer friendly api for manipulating data, without writing JavaScript. - -Filters can be applied by supplying the _:_ modifier, so for example if we wish to take the array `[{ name: 'tj' }, { name: 'mape' }, { name: 'guillermo' }]` and output a list of names we can do this simply with filters: - -Template: - -

<%=: users | map:'name' | join %>

- -Output: - -

Tj, Mape, Guillermo

- -Render call: - - ejs.render(str, { - locals: { - users: [ - { name: 'tj' }, - { name: 'mape' }, - { name: 'guillermo' } - ] - } - }); - -Or perhaps capitalize the first user's name for display: - -

<%=: users | first | capitalize %>

- -## Filter list - -Currently these filters are available: - - - first - - last - - capitalize - - downcase - - upcase - - sort - - sort_by:'prop' - - size - - length - - plus:n - - minus:n - - times:n - - divided_by:n - - join:'val' - - truncate:n - - truncate_words:n - - replace:pattern,substitution - - prepend:val - - append:val - - map:'prop' - - reverse - - get:'prop' - -## Adding filters - - To add a filter simply add a method to the `.filters` object: - -```js -ejs.filters.last = function(obj) { - return obj[obj.length - 1]; -}; -``` - -## client-side support - - include `./ejs.js` or `./ejs.min.js` and `require("ejs").compile(str)`. - -## License - -(The MIT License) - -Copyright (c) 2009-2010 TJ Holowaychuk <tj@vision-media.ca> - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -'Software'), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/benchmark.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/benchmark.js deleted file mode 100644 index 7b267e1..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/benchmark.js +++ /dev/null @@ -1,14 +0,0 @@ - - -var ejs = require('./lib/ejs'), - str = '<% if (foo) { %>

<%= foo %>

<% } %>', - times = 50000; - -console.log('rendering ' + times + ' times'); - -var start = new Date; -while (times--) { - ejs.render(str, { cache: true, filename: 'test', locals: { foo: 'bar' }}); -} - -console.log('took ' + (new Date - start) + 'ms'); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.js deleted file mode 100644 index b8c6aa1..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.js +++ /dev/null @@ -1,531 +0,0 @@ - -// CommonJS require() - -function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - } - -require.modules = {}; - -require.resolve = function (path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }; - -require.register = function (path, fn){ - require.modules[path] = fn; - }; - -require.relative = function (parent) { - return function(p){ - if ('.' != p[0]) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }; - - -require.register("ejs.js", function(module, exports, require){ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./utils'); - -/** - * Library version. - */ - -exports.version = '0.4.2'; - -/** - * Filters. - * - * @type Object - */ - -var filters = exports.filters = require('./filters'); - -/** - * Intermediate js cache. - * - * @type Object - */ - -var cache = {}; - -/** - * Clear intermediate js cache. - * - * @api public - */ - -exports.clearCache = function(){ - cache = {}; -}; - -/** - * Translate filtered code into function calls. - * - * @param {String} js - * @return {String} - * @api private - */ - -function filtered(js) { - return js.substr(1).split('|').reduce(function(js, filter){ - var parts = filter.split(':') - , name = parts.shift() - , args = parts.shift() || ''; - if (args) args = ', ' + args; - return 'filters.' + name + '(' + js + args + ')'; - }); -}; - -/** - * Re-throw the given `err` in context to the - * `str` of ejs, `filename`, and `lineno`. - * - * @param {Error} err - * @param {String} str - * @param {String} filename - * @param {String} lineno - * @api private - */ - -function rethrow(err, str, filename, lineno){ - var lines = str.split('\n') - , start = Math.max(lineno - 3, 0) - , end = Math.min(lines.length, lineno + 3); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' >> ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'ejs') + ':' - + lineno + '\n' - + context + '\n\n' - + err.message; - - throw err; -} - -/** - * Parse the given `str` of ejs, returning the function body. - * - * @param {String} str - * @return {String} - * @api public - */ - -var parse = exports.parse = function(str, options){ - var options = options || {} - , open = options.open || exports.open || '<%' - , close = options.close || exports.close || '%>'; - - var buf = [ - "var buf = [];" - , "\nwith (locals) {" - , "\n buf.push('" - ]; - - var lineno = 1; - - for (var i = 0, len = str.length; i < len; ++i) { - if (str.slice(i, open.length + i) == open) { - i += open.length - - var prefix, postfix, line = '__stack.lineno=' + lineno; - switch (str[i]) { - case '=': - prefix = "', escape((" + line + ', '; - postfix = ")), '"; - ++i; - break; - case '-': - prefix = "', (" + line + ', '; - postfix = "), '"; - ++i; - break; - default: - prefix = "');" + line + ';'; - postfix = "; buf.push('"; - } - - var start = i; - var end = str.indexOf(close, i); - var js = str.substring(i, end); - var n = 0; - while ((n = js.indexOf("\n", n)) > -1) { - n++; - lineno++; - } - if (js[0] == ':') js = filtered(js); - buf.push(prefix, js, postfix); - i += end - start + close.length - 1; - - } else if (str[i] == "\\") { - buf.push("\\\\"); - } else if (str[i] == "'") { - buf.push("\\'"); - } else if (str[i] == "\r") { - buf.push(" "); - } else if (str[i] == "\n") { - buf.push("\\n"); - lineno++; - } else { - buf.push(str[i]); - } - } - - buf.push("');\n}\nreturn buf.join('');"); - return buf.join(''); -}; - -/** - * Compile the given `str` of ejs into a `Function`. - * - * @param {String} str - * @param {Object} options - * @return {Function} - * @api public - */ - -var compile = exports.compile = function(str, options){ - options = options || {}; - - var input = JSON.stringify(str) - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined'; - - // Adds the fancy stack trace meta info - str = [ - 'var __stack = { lineno: 1, input: ' + input + ', filename: ' + filename + ' };', - rethrow.toString(), - 'try {', - exports.parse(str, options), - '} catch (err) {', - ' rethrow(err, __stack.input, __stack.filename, __stack.lineno);', - '}' - ].join("\n"); - - if (options.debug) console.log(str); - var fn = new Function('locals, filters, escape', str); - return function(locals){ - return fn.call(this, locals, filters, utils.escape); - } -}; - -/** - * Render the given `str` of ejs. - * - * Options: - * - * - `locals` Local variables object - * - `cache` Compiled functions are cached, requires `filename` - * - `filename` Used by `cache` to key caches - * - `scope` Function execution context - * - `debug` Output generated function body - * - `open` Open tag, defaulting to "<%" - * - `close` Closing tag, defaulting to "%>" - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api public - */ - -exports.render = function(str, options){ - var fn - , options = options || {}; - if (options.cache) { - if (options.filename) { - fn = cache[options.filename] || (cache[options.filename] = compile(str, options)); - } else { - throw new Error('"cache" option requires "filename".'); - } - } else { - fn = compile(str, options); - } - return fn.call(options.scope, options.locals || {}); -}; - -/** - * Expose to require(). - */ - -if (require.extensions) { - require.extensions['.ejs'] = function(module, filename) { - source = require('fs').readFileSync(filename, 'utf-8'); - module._compile(compile(source, {}), filename); - }; -} else if (require.registerExtension) { - require.registerExtension('.ejs', function(src) { - return compile(src, {}); - }); -} - -}); // module: ejs.js - -require.register("filters.js", function(module, exports, require){ - -/*! - * EJS - Filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * First element of the target `obj`. - */ - -exports.first = function(obj) { - return obj[0]; -}; - -/** - * Last element of the target `obj`. - */ - -exports.last = function(obj) { - return obj[obj.length - 1]; -}; - -/** - * Capitalize the first letter of the target `str`. - */ - -exports.capitalize = function(str){ - str = String(str); - return str[0].toUpperCase() + str.substr(1, str.length); -}; - -/** - * Downcase the target `str`. - */ - -exports.downcase = function(str){ - return String(str).toLowerCase(); -}; - -/** - * Uppercase the target `str`. - */ - -exports.upcase = function(str){ - return String(str).toUpperCase(); -}; - -/** - * Sort the target `obj`. - */ - -exports.sort = function(obj){ - return Object.create(obj).sort(); -}; - -/** - * Sort the target `obj` by the given `prop` ascending. - */ - -exports.sort_by = function(obj, prop){ - return Object.create(obj).sort(function(a, b){ - a = a[prop], b = b[prop]; - if (a > b) return 1; - if (a < b) return -1; - return 0; - }); -}; - -/** - * Size or length of the target `obj`. - */ - -exports.size = exports.length = function(obj) { - return obj.length; -}; - -/** - * Add `a` and `b`. - */ - -exports.plus = function(a, b){ - return Number(a) + Number(b); -}; - -/** - * Subtract `b` from `a`. - */ - -exports.minus = function(a, b){ - return Number(a) - Number(b); -}; - -/** - * Multiply `a` by `b`. - */ - -exports.times = function(a, b){ - return Number(a) * Number(b); -}; - -/** - * Divide `a` by `b`. - */ - -exports.divided_by = function(a, b){ - return Number(a) / Number(b); -}; - -/** - * Join `obj` with the given `str`. - */ - -exports.join = function(obj, str){ - return obj.join(str || ', '); -}; - -/** - * Truncate `str` to `len`. - */ - -exports.truncate = function(str, len){ - str = String(str); - return str.substr(0, len); -}; - -/** - * Truncate `str` to `n` words. - */ - -exports.truncate_words = function(str, n){ - var str = String(str) - , words = str.split(/ +/); - return words.slice(0, n).join(' '); -}; - -/** - * Replace `pattern` with `substitution` in `str`. - */ - -exports.replace = function(str, pattern, substitution){ - return String(str).replace(pattern, substitution || ''); -}; - -/** - * Prepend `val` to `obj`. - */ - -exports.prepend = function(obj, val){ - return Array.isArray(obj) - ? [val].concat(obj) - : val + obj; -}; - -/** - * Append `val` to `obj`. - */ - -exports.append = function(obj, val){ - return Array.isArray(obj) - ? obj.concat(val) - : obj + val; -}; - -/** - * Map the given `prop`. - */ - -exports.map = function(arr, prop){ - return arr.map(function(obj){ - return obj[prop]; - }); -}; - -/** - * Reverse the given `obj`. - */ - -exports.reverse = function(obj){ - return Array.isArray(obj) - ? obj.reverse() - : String(obj).split('').reverse().join(''); -}; - -/** - * Get `prop` of the given `obj`. - */ - -exports.get = function(obj, prop){ - return obj[prop]; -}; - -/** - * Packs the given `obj` into json string - */ -exports.json = function(obj){ - return JSON.stringify(obj); -}; -}); // module: filters.js - -require.register("utils.js", function(module, exports, require){ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - -}); // module: utils.js diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.min.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.min.js deleted file mode 100644 index 6b72d94..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/ejs.min.js +++ /dev/null @@ -1,2 +0,0 @@ -// CommonJS require() -function require(p){var path=require.resolve(p),mod=require.modules[path];if(!mod)throw new Error('failed to require "'+p+'"');mod.exports||(mod.exports={},mod.call(mod.exports,mod,mod.exports,require.relative(path)));return mod.exports}require.modules={},require.resolve=function(path){var orig=path,reg=path+".js",index=path+"/index.js";return require.modules[reg]&®||require.modules[index]&&index||orig},require.register=function(path,fn){require.modules[path]=fn},require.relative=function(parent){return function(p){if("."!=p[0])return require(p);var path=parent.split("/"),segs=p.split("/");path.pop();for(var i=0;i> ":" ")+curr+"| "+line}).join("\n");err.path=filename,err.message=(filename||"ejs")+":"+lineno+"\n"+context+"\n\n"+err.message;throw err}var parse=exports.parse=function(str,options){var options=options||{},open=options.open||exports.open||"<%",close=options.close||exports.close||"%>",buf=["var buf = [];","\nwith (locals) {","\n buf.push('"],lineno=1;for(var i=0,len=str.length;ib)return 1;if(a/g,">").replace(/"/g,""")}}) \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/client.html b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/client.html deleted file mode 100644 index 7081a04..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/client.html +++ /dev/null @@ -1,5 +0,0 @@ - - - - - \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.ejs b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.ejs deleted file mode 100644 index d571330..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.ejs +++ /dev/null @@ -1,7 +0,0 @@ -<% if (names.length) { %> -
    - <% names.forEach(function(name){ %> -
  • <%= name %>
  • - <% }) %> -
-<% } %> \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.js deleted file mode 100644 index 9cd7168..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/examples/list.js +++ /dev/null @@ -1,16 +0,0 @@ - -/** - * Module dependencies. - */ - -var ejs = require('../') - , fs = require('fs') - , str = fs.readFileSync(__dirname + '/list.ejs', 'utf8'); - -var ret = ejs.render(str, { - locals: { - names: ['foo', 'bar', 'baz'] - } -}); - -console.log(ret); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/index.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/index.js deleted file mode 100644 index 20bf71a..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/index.js +++ /dev/null @@ -1,2 +0,0 @@ - -module.exports = require('./lib/ejs'); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/ejs.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/ejs.js deleted file mode 100644 index 46afa74..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/ejs.js +++ /dev/null @@ -1,251 +0,0 @@ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Module dependencies. - */ - -var utils = require('./utils'); - -/** - * Library version. - */ - -exports.version = '0.4.3'; - -/** - * Filters. - * - * @type Object - */ - -var filters = exports.filters = require('./filters'); - -/** - * Intermediate js cache. - * - * @type Object - */ - -var cache = {}; - -/** - * Clear intermediate js cache. - * - * @api public - */ - -exports.clearCache = function(){ - cache = {}; -}; - -/** - * Translate filtered code into function calls. - * - * @param {String} js - * @return {String} - * @api private - */ - -function filtered(js) { - return js.substr(1).split('|').reduce(function(js, filter){ - var parts = filter.split(':') - , name = parts.shift() - , args = parts.shift() || ''; - if (args) args = ', ' + args; - return 'filters.' + name + '(' + js + args + ')'; - }); -}; - -/** - * Re-throw the given `err` in context to the - * `str` of ejs, `filename`, and `lineno`. - * - * @param {Error} err - * @param {String} str - * @param {String} filename - * @param {String} lineno - * @api private - */ - -function rethrow(err, str, filename, lineno){ - var lines = str.split('\n') - , start = Math.max(lineno - 3, 0) - , end = Math.min(lines.length, lineno + 3); - - // Error context - var context = lines.slice(start, end).map(function(line, i){ - var curr = i + start + 1; - return (curr == lineno ? ' >> ' : ' ') - + curr - + '| ' - + line; - }).join('\n'); - - // Alter exception message - err.path = filename; - err.message = (filename || 'ejs') + ':' - + lineno + '\n' - + context + '\n\n' - + err.message; - - throw err; -} - -/** - * Parse the given `str` of ejs, returning the function body. - * - * @param {String} str - * @return {String} - * @api public - */ - -var parse = exports.parse = function(str, options){ - var options = options || {} - , open = options.open || exports.open || '<%' - , close = options.close || exports.close || '%>'; - - var buf = [ - "var buf = [];" - , "\nwith (locals) {" - , "\n buf.push('" - ]; - - var lineno = 1; - - for (var i = 0, len = str.length; i < len; ++i) { - if (str.slice(i, open.length + i) == open) { - i += open.length - - var prefix, postfix, line = '__stack.lineno=' + lineno; - switch (str.substr(i, 1)) { - case '=': - prefix = "', escape((" + line + ', '; - postfix = ")), '"; - ++i; - break; - case '-': - prefix = "', (" + line + ', '; - postfix = "), '"; - ++i; - break; - default: - prefix = "');" + line + ';'; - postfix = "; buf.push('"; - } - - var end = str.indexOf(close, i) - , js = str.substring(i, end) - , start = i - , n = 0; - - while (~(n = js.indexOf("\n", n))) n++, lineno++; - if (js.substr(0, 1) == ':') js = filtered(js); - buf.push(prefix, js, postfix); - i += end - start + close.length - 1; - - } else if (str.substr(i, 1) == "\\") { - buf.push("\\\\"); - } else if (str.substr(i, 1) == "'") { - buf.push("\\'"); - } else if (str.substr(i, 1) == "\r") { - buf.push(" "); - } else if (str.substr(i, 1) == "\n") { - buf.push("\\n"); - lineno++; - } else { - buf.push(str.substr(i, 1)); - } - } - - buf.push("');\n}\nreturn buf.join('');"); - return buf.join(''); -}; - -/** - * Compile the given `str` of ejs into a `Function`. - * - * @param {String} str - * @param {Object} options - * @return {Function} - * @api public - */ - -var compile = exports.compile = function(str, options){ - options = options || {}; - - var input = JSON.stringify(str) - , filename = options.filename - ? JSON.stringify(options.filename) - : 'undefined'; - - // Adds the fancy stack trace meta info - str = [ - 'var __stack = { lineno: 1, input: ' + input + ', filename: ' + filename + ' };', - rethrow.toString(), - 'try {', - exports.parse(str, options), - '} catch (err) {', - ' rethrow(err, __stack.input, __stack.filename, __stack.lineno);', - '}' - ].join("\n"); - - if (options.debug) console.log(str); - var fn = new Function('locals, filters, escape', str); - return function(locals){ - return fn.call(this, locals, filters, utils.escape); - } -}; - -/** - * Render the given `str` of ejs. - * - * Options: - * - * - `locals` Local variables object - * - `cache` Compiled functions are cached, requires `filename` - * - `filename` Used by `cache` to key caches - * - `scope` Function execution context - * - `debug` Output generated function body - * - `open` Open tag, defaulting to "<%" - * - `close` Closing tag, defaulting to "%>" - * - * @param {String} str - * @param {Object} options - * @return {String} - * @api public - */ - -exports.render = function(str, options){ - var fn - , options = options || {}; - if (options.cache) { - if (options.filename) { - fn = cache[options.filename] || (cache[options.filename] = compile(str, options)); - } else { - throw new Error('"cache" option requires "filename".'); - } - } else { - fn = compile(str, options); - } - return fn.call(options.scope, options.locals || {}); -}; - -/** - * Expose to require(). - */ - -if (require.extensions) { - require.extensions['.ejs'] = function(module, filename) { - source = require('fs').readFileSync(filename, 'utf-8'); - module._compile(compile(source, {}), filename); - }; -} else if (require.registerExtension) { - require.registerExtension('.ejs', function(src) { - return compile(src, {}); - }); -} diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/filters.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/filters.js deleted file mode 100644 index d425c8d..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/filters.js +++ /dev/null @@ -1,198 +0,0 @@ - -/*! - * EJS - Filters - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * First element of the target `obj`. - */ - -exports.first = function(obj) { - return obj[0]; -}; - -/** - * Last element of the target `obj`. - */ - -exports.last = function(obj) { - return obj[obj.length - 1]; -}; - -/** - * Capitalize the first letter of the target `str`. - */ - -exports.capitalize = function(str){ - str = String(str); - return str[0].toUpperCase() + str.substr(1, str.length); -}; - -/** - * Downcase the target `str`. - */ - -exports.downcase = function(str){ - return String(str).toLowerCase(); -}; - -/** - * Uppercase the target `str`. - */ - -exports.upcase = function(str){ - return String(str).toUpperCase(); -}; - -/** - * Sort the target `obj`. - */ - -exports.sort = function(obj){ - return Object.create(obj).sort(); -}; - -/** - * Sort the target `obj` by the given `prop` ascending. - */ - -exports.sort_by = function(obj, prop){ - return Object.create(obj).sort(function(a, b){ - a = a[prop], b = b[prop]; - if (a > b) return 1; - if (a < b) return -1; - return 0; - }); -}; - -/** - * Size or length of the target `obj`. - */ - -exports.size = exports.length = function(obj) { - return obj.length; -}; - -/** - * Add `a` and `b`. - */ - -exports.plus = function(a, b){ - return Number(a) + Number(b); -}; - -/** - * Subtract `b` from `a`. - */ - -exports.minus = function(a, b){ - return Number(a) - Number(b); -}; - -/** - * Multiply `a` by `b`. - */ - -exports.times = function(a, b){ - return Number(a) * Number(b); -}; - -/** - * Divide `a` by `b`. - */ - -exports.divided_by = function(a, b){ - return Number(a) / Number(b); -}; - -/** - * Join `obj` with the given `str`. - */ - -exports.join = function(obj, str){ - return obj.join(str || ', '); -}; - -/** - * Truncate `str` to `len`. - */ - -exports.truncate = function(str, len){ - str = String(str); - return str.substr(0, len); -}; - -/** - * Truncate `str` to `n` words. - */ - -exports.truncate_words = function(str, n){ - var str = String(str) - , words = str.split(/ +/); - return words.slice(0, n).join(' '); -}; - -/** - * Replace `pattern` with `substitution` in `str`. - */ - -exports.replace = function(str, pattern, substitution){ - return String(str).replace(pattern, substitution || ''); -}; - -/** - * Prepend `val` to `obj`. - */ - -exports.prepend = function(obj, val){ - return Array.isArray(obj) - ? [val].concat(obj) - : val + obj; -}; - -/** - * Append `val` to `obj`. - */ - -exports.append = function(obj, val){ - return Array.isArray(obj) - ? obj.concat(val) - : obj + val; -}; - -/** - * Map the given `prop`. - */ - -exports.map = function(arr, prop){ - return arr.map(function(obj){ - return obj[prop]; - }); -}; - -/** - * Reverse the given `obj`. - */ - -exports.reverse = function(obj){ - return Array.isArray(obj) - ? obj.reverse() - : String(obj).split('').reverse().join(''); -}; - -/** - * Get `prop` of the given `obj`. - */ - -exports.get = function(obj, prop){ - return obj[prop]; -}; - -/** - * Packs the given `obj` into json string - */ -exports.json = function(obj){ - return JSON.stringify(obj); -}; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/utils.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/utils.js deleted file mode 100644 index 8d569d6..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/lib/utils.js +++ /dev/null @@ -1,23 +0,0 @@ - -/*! - * EJS - * Copyright(c) 2010 TJ Holowaychuk - * MIT Licensed - */ - -/** - * Escape the given string of `html`. - * - * @param {String} html - * @return {String} - * @api private - */ - -exports.escape = function(html){ - return String(html) - .replace(/&(?!\w+;)/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); -}; - \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/package.json b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/package.json deleted file mode 100644 index 224b4ff..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "name": "ejs", - "description": "Embedded JavaScript templates", - "version": "0.4.3", - "author": "TJ Holowaychuk ", - "keywords": ["template", "engine", "ejs"], - "devDependencies": { - "expresso": "0.9.2" - }, - "main": "./lib/ejs.js" -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/support/compile.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/support/compile.js deleted file mode 100644 index edd3815..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/support/compile.js +++ /dev/null @@ -1,173 +0,0 @@ - -/** - * Module dependencies. - */ - -var fs = require('fs'); - -/** - * Arguments. - */ - -var args = process.argv.slice(2) - , pending = args.length - , files = {}; - -console.log(''); - -// parse arguments - -args.forEach(function(file){ - var mod = file.replace('lib/', ''); - fs.readFile(file, 'utf8', function(err, js){ - if (err) throw err; - console.log(' \033[90mcompile : \033[0m\033[36m%s\033[0m', file); - files[file] = parse(js); - --pending || compile(); - }); -}); - -/** - * Parse the given `js`. - */ - -function parse(js) { - return parseInheritance(parseConditionals(js)); -} - -/** - * Parse __proto__. - */ - -function parseInheritance(js) { - return js - .replace(/^ *(\w+)\.prototype\.__proto__ * = *(\w+)\.prototype *;?/gm, function(_, child, parent){ - return child + '.prototype = new ' + parent + ';\n' - + child + '.prototype.constructor = '+ child + ';\n'; - }); -} - -/** - * Parse the given `js`, currently supporting: - * - * 'if' ['node' | 'browser'] - * 'end' - * - */ - -function parseConditionals(js) { - var lines = js.split('\n') - , len = lines.length - , buffer = true - , browser = false - , buf = [] - , line - , cond; - - for (var i = 0; i < len; ++i) { - line = lines[i]; - if (/^ *\/\/ *if *(node|browser)/gm.exec(line)) { - cond = RegExp.$1; - buffer = browser = 'browser' == cond; - } else if (/^ *\/\/ *end/.test(line)) { - buffer = true; - browser = false; - } else if (browser) { - buf.push(line.replace(/^( *)\/\//, '$1')); - } else if (buffer) { - buf.push(line); - } - } - - return buf.join('\n'); -} - -/** - * Compile the files. - */ - -function compile() { - var buf = ''; - buf += '\n// CommonJS require()\n\n'; - buf += browser.require + '\n\n'; - buf += 'require.modules = {};\n\n'; - buf += 'require.resolve = ' + browser.resolve + ';\n\n'; - buf += 'require.register = ' + browser.register + ';\n\n'; - buf += 'require.relative = ' + browser.relative + ';\n\n'; - args.forEach(function(file){ - var js = files[file]; - file = file.replace('lib/', ''); - buf += '\nrequire.register("' + file + '", function(module, exports, require){\n'; - buf += js; - buf += '\n}); // module: ' + file + '\n'; - }); - fs.writeFile('ejs.js', buf, function(err){ - if (err) throw err; - console.log(' \033[90m create : \033[0m\033[36m%s\033[0m', 'ejs.js'); - console.log(); - }); -} - -// refactored version of weepy's -// https://github.com/weepy/brequire/blob/master/browser/brequire.js - -var browser = { - - /** - * Require a module. - */ - - require: function require(p){ - var path = require.resolve(p) - , mod = require.modules[path]; - if (!mod) throw new Error('failed to require "' + p + '"'); - if (!mod.exports) { - mod.exports = {}; - mod.call(mod.exports, mod, mod.exports, require.relative(path)); - } - return mod.exports; - }, - - /** - * Resolve module path. - */ - - resolve: function(path){ - var orig = path - , reg = path + '.js' - , index = path + '/index.js'; - return require.modules[reg] && reg - || require.modules[index] && index - || orig; - }, - - /** - * Return relative require(). - */ - - relative: function(parent) { - return function(p){ - if ('.' != p.substr(0, 1)) return require(p); - - var path = parent.split('/') - , segs = p.split('/'); - path.pop(); - - for (var i = 0; i < segs.length; i++) { - var seg = segs[i]; - if ('..' == seg) path.pop(); - else if ('.' != seg) path.push(seg); - } - - return require(path.join('/')); - }; - }, - - /** - * Register a module. - */ - - register: function(path, fn){ - require.modules[path] = fn; - } -}; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/test/ejs.test.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/test/ejs.test.js deleted file mode 100644 index 624157d..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/deps/ejs/test/ejs.test.js +++ /dev/null @@ -1,269 +0,0 @@ - -/** - * Module dependencies. - */ - -var ejs = require('../') - , assert = require('assert'); - -module.exports = { - 'test .version': function(){ - assert.ok(/^\d+\.\d+\.\d+$/.test(ejs.version), 'Test .version format'); - }, - - 'test html': function(){ - assert.equal('

yay

', ejs.render('

yay

')); - }, - - 'test buffered code': function(){ - var html = '

tj

', - str = '

<%= name %>

', - locals = { name: 'tj' }; - assert.equal(html, ejs.render(str, { locals: locals })); - }, - - 'test unbuffered code': function(){ - var html = '

tj

', - str = '<% if (name) { %>

<%= name %>

<% } %>', - locals = { name: 'tj' }; - assert.equal(html, ejs.render(str, { locals: locals })); - }, - - 'test `scope` option': function(){ - var html = '

tj

', - str = '

<%= this %>

'; - assert.equal(html, ejs.render(str, { scope: 'tj' })); - }, - - 'test escaping': function(){ - assert.equal('<script>', ejs.render('<%= " - - - - - - - - diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/examples/nested/nested_reporter_test.unit.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/examples/nested/nested_reporter_test.unit.js deleted file mode 100644 index 612adcd..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/examples/nested/nested_reporter_test.unit.js +++ /dev/null @@ -1,94 +0,0 @@ -var testCase = require('nodeunit').testCase; -/* - This is an example test suite to demonstrate the nested test reporter. - Run with --reporter nested, e.g., - nodeunit --reporter nested nested_reporter_test.unit.js - - The test output should be something like: - - nested_reporter_test.unit.js - Test 0.1 (pass) - TC 1 - TC 1.1 - Test 1.1.1 (pass) - TC 2 - TC 2.1 - TC 2.1.1 - Test 2.1.1.1 (pass) - Test 2.1.1.2 (pass) - TC 2.2.1 - Test 2.2.1.1 (pass) - TC 2.2.1.1 - Test 2.2.1.1.1 (pass) - Test 2.2.1.2 (pass) - TC 3 - TC 3.1 - TC 3.1.1 - Test 3.1.1.1 (should fail) (fail) ✖ - AssertionError: false == true - // stack trace here. - - FAILURES: 1/8 assertions failed (6ms) -*/ - -module.exports = testCase({ - "Test 0.1": function(test) { - test.ok(true); - test.done(); - }, - - "TC 1": testCase({ - "TC 1.1": testCase({ - "Test 1.1.1": function(test) { - test.ok(true); - test.done(); - } - }) - }), - - "TC 2": testCase({ - "TC 2.1": testCase({ - "TC 2.1.1": testCase({ - "Test 2.1.1.1": function(test) { - test.ok(true); - test.done(); - }, - - "Test 2.1.1.2": function(test) { - test.ok(true); - test.done(); - } - }), - - "TC 2.2.1": testCase({ - "Test 2.2.1.1": function(test) { - test.ok(true); - test.done(); - }, - - "TC 2.2.1.1": testCase({ - "Test 2.2.1.1.1": function(test) { - test.ok(true); - test.done(); - }, - }), - - "Test 2.2.1.2": function(test) { - test.ok(true); - test.done(); - } - }) - }) - }), - - "TC 3": testCase({ - "TC 3.1": testCase({ - "TC 3.1.1": testCase({ - "Test 3.1.1.1 (should fail)": function(test) { - test.ok(false); - test.done(); - } - }) - }) - }) -}); diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/img/example_fail.png b/node_modules/reg/node_modules/mongodb/deps/nodeunit/img/example_fail.png deleted file mode 100644 index 78ff425..0000000 Binary files a/node_modules/reg/node_modules/mongodb/deps/nodeunit/img/example_fail.png and /dev/null differ diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/img/example_machineout.png b/node_modules/reg/node_modules/mongodb/deps/nodeunit/img/example_machineout.png deleted file mode 100644 index c6bfa27..0000000 Binary files a/node_modules/reg/node_modules/mongodb/deps/nodeunit/img/example_machineout.png and /dev/null differ diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/img/example_pass.png b/node_modules/reg/node_modules/mongodb/deps/nodeunit/img/example_pass.png deleted file mode 100644 index 069d716..0000000 Binary files a/node_modules/reg/node_modules/mongodb/deps/nodeunit/img/example_pass.png and /dev/null differ diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/index.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/index.js deleted file mode 100644 index 07867d0..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/index.js +++ /dev/null @@ -1,3 +0,0 @@ -// This file is just added for convenience so this repository can be -// directly checked out into a project's deps folder -module.exports = require('./lib/nodeunit'); diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/assert.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/assert.js deleted file mode 100644 index 6f5f07e..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/assert.js +++ /dev/null @@ -1,327 +0,0 @@ -/** - * This file is based on the node.js assert module, but with some small - * changes for browser-compatibility - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - */ - - -/** - * Added for browser compatibility - */ - -var _keys = function(obj){ - if(Object.keys) return Object.keys(obj); - if (typeof obj != 'object' && typeof obj != 'function') { - throw new TypeError('-'); - } - var keys = []; - for(var k in obj){ - if(obj.hasOwnProperty(k)) keys.push(k); - } - return keys; -}; - - - -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// Permission is hereby granted, free of charge, to any person obtaining a copy -// of this software and associated documentation files (the 'Software'), to -// deal in the Software without restriction, including without limitation the -// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -// sell copies of the Software, and to permit persons to whom the Software is -// furnished to do so, subject to the following conditions: -// -// The above copyright notice and this permission notice shall be included in -// all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN -// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - -var pSlice = Array.prototype.slice; - -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = exports; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({message: message, actual: actual, expected: expected}) - -assert.AssertionError = function AssertionError (options) { - this.name = "AssertionError"; - this.message = options.message; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - var stackStartFunction = options.stackStartFunction || fail; - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } -}; -// code from util.inherits in node -assert.AssertionError.super_ = Error; - - -// EDITED FOR BROWSER COMPATIBILITY: replaced Object.create call -// TODO: test what effect this may have -var ctor = function () { this.constructor = assert.AssertionError; }; -ctor.prototype = Error.prototype; -assert.AssertionError.prototype = new ctor(); - - -assert.AssertionError.prototype.toString = function() { - if (this.message) { - return [this.name+":", this.message].join(' '); - } else { - return [ this.name+":" - , JSON.stringify(this.expected ) - , this.operator - , JSON.stringify(this.actual) - ].join(" "); - } -}; - -// assert.AssertionError instanceof Error - -assert.AssertionError.__proto__ = Error.prototype; - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -assert.ok = function ok(value, message) { - if (!!!value) fail(value, true, message, "==", assert.ok); -}; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, "==", assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, "!=", assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected)) { - fail(actual, expected, message, "deepEqual", assert.deepEqual); - } -}; - -function _deepEqual(actual, expected) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (actual instanceof Date && expected instanceof Date) { - return actual.getTime() === expected.getTime(); - - // 7.2.1 If the expcted value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object that refers to the same source and options - } else if (actual instanceof RegExp && expected instanceof RegExp) { - return actual.source === expected.source && - actual.global === expected.global && - actual.ignoreCase === expected.ignoreCase && - actual.multiline === expected.multiline; - - // 7.3. Other pairs that do not both pass typeof value == "object", - // equivalence is determined by ==. - } else if (typeof actual != 'object' && typeof expected != 'object') { - return actual == expected; - - // 7.4. For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical "prototype" property. Note: this - // accounts for both named and indexed properties on Arrays. - } else { - return objEquiv(actual, expected); - } -} - -function isUndefinedOrNull (value) { - return value === null || value === undefined; -} - -function isArguments (object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv (a, b) { - if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) - return false; - // an identical "prototype" property. - if (a.prototype !== b.prototype) return false; - //~~~I've managed to break Object.keys through screwy arguments passing. - // Converting to array solves the problem. - if (isArguments(a)) { - if (!isArguments(b)) { - return false; - } - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b); - } - try{ - var ka = _keys(a), - kb = _keys(b), - key, i; - } catch (e) {//happens when one is a string literal and the other isn't - return false; - } - // having the same number of owned properties (keys incorporates hasOwnProperty) - if (ka.length != kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] != kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key] )) - return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected)) { - fail(actual, expected, message, "notDeepEqual", assert.notDeepEqual); - } -}; - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, "===", assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as determined by !==. -// assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, "!==", assert.notStrictEqual); - } -}; - -function _throws (shouldThrow, block, err, message) { - var exception = null, - threw = false, - typematters = true; - - message = message || ""; - - //handle optional arguments - if (arguments.length == 3) { - if (typeof(err) == "string") { - message = err; - typematters = false; - } - } else if (arguments.length == 2) { - typematters = false; - } - - try { - block(); - } catch (e) { - threw = true; - exception = e; - } - - if (shouldThrow && !threw) { - fail( "Missing expected exception" - + (err && err.name ? " ("+err.name+")." : '.') - + (message ? " " + message : "") - ); - } - if (!shouldThrow && threw && typematters && exception instanceof err) { - fail( "Got unwanted exception" - + (err && err.name ? " ("+err.name+")." : '.') - + (message ? " " + message : "") - ); - } - if ((shouldThrow && threw && typematters && !(exception instanceof err)) || - (!shouldThrow && threw)) { - throw exception; - } -}; - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [true].concat(pSlice.call(arguments))); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws.apply(this, [false].concat(pSlice.call(arguments))); -}; - -assert.ifError = function (err) { if (err) {throw err;}}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/core.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/core.js deleted file mode 100644 index 028745e..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/core.js +++ /dev/null @@ -1,316 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, it's mostly to avoid requiring code - * that is node specific - */ - -/** - * Module dependencies - */ - -var async = require('../deps/async'), //@REMOVE_LINE_FOR_BROWSER - nodeunit = require('./nodeunit'), //@REMOVE_LINE_FOR_BROWSER - types = require('./types'); //@REMOVE_LINE_FOR_BROWSER - - -/** - * Added for browser compatibility - */ - -var _keys = function (obj) { - if (Object.keys) { - return Object.keys(obj); - } - var keys = []; - for (var k in obj) { - if (obj.hasOwnProperty(k)) { - keys.push(k); - } - } - return keys; -}; - - -var _copy = function (obj) { - var nobj = {}; - var keys = _keys(obj); - for (var i = 0; i < keys.length; i += 1) { - nobj[keys[i]] = obj[keys[i]]; - } - return nobj; -}; - - -/** - * Runs a test function (fn) from a loaded module. After the test function - * calls test.done(), the callback is executed with an assertionList as its - * second argument. - * - * @param {String} name - * @param {Function} fn - * @param {Object} opt - * @param {Function} callback - * @api public - */ - -exports.runTest = function (name, fn, opt, callback) { - var options = types.options(opt); - - options.testStart(name); - var start = new Date().getTime(); - var test = types.test(name, start, options, callback); - - try { - fn(test); - } - catch (e) { - test.done(e); - } -}; - -/** - * Takes an object containing test functions or other test suites as properties - * and runs each in series. After all tests have completed, the callback is - * called with a list of all assertions as the second argument. - * - * If a name is passed to this function it is prepended to all test and suite - * names that run within it. - * - * @param {String} name - * @param {Object} suite - * @param {Object} opt - * @param {Function} callback - * @api public - */ - -exports.runSuite = function (name, suite, opt, callback) { - suite = wrapGroup(suite); - var keys = _keys(suite); - - async.concatSeries(keys, function (k, cb) { - var prop = suite[k], _name; - - _name = name ? [].concat(name, k) : [k]; - _name.toString = function () { - // fallback for old one - return this.join(' - '); - }; - - if (typeof prop === 'function') { - var in_name = false; - for (var i = 0; i < _name.length; i += 1) { - if (_name[i] === opt.testspec) { - in_name = true; - } - } - if (!opt.testspec || in_name) { - if (opt.moduleStart) { - opt.moduleStart(); - } - exports.runTest(_name, suite[k], opt, cb); - } - else { - return cb(); - } - } - else { - exports.runSuite(_name, suite[k], opt, cb); - } - }, callback); -}; - -/** - * Run each exported test function or test suite from a loaded module. - * - * @param {String} name - * @param {Object} mod - * @param {Object} opt - * @param {Function} callback - * @api public - */ - -exports.runModule = function (name, mod, opt, callback) { - var options = _copy(types.options(opt)); - - var _run = false; - var _moduleStart = options.moduleStart; - - mod = wrapGroup(mod); - - function run_once() { - if (!_run) { - _run = true; - _moduleStart(name); - } - } - options.moduleStart = run_once; - - var start = new Date().getTime(); - - exports.runSuite(null, mod, options, function (err, a_list) { - var end = new Date().getTime(); - var assertion_list = types.assertionList(a_list, end - start); - options.moduleDone(name, assertion_list); - if (nodeunit.complete) { - nodeunit.complete(name, assertion_list); - } - callback(null, a_list); - }); -}; - -/** - * Treats an object literal as a list of modules keyed by name. Runs each - * module and finished with calling 'done'. You can think of this as a browser - * safe alternative to runFiles in the nodeunit module. - * - * @param {Object} modules - * @param {Object} opt - * @api public - */ - -// TODO: add proper unit tests for this function -exports.runModules = function (modules, opt) { - var all_assertions = []; - var options = types.options(opt); - var start = new Date().getTime(); - - async.concatSeries(_keys(modules), function (k, cb) { - exports.runModule(k, modules[k], options, cb); - }, - function (err, all_assertions) { - var end = new Date().getTime(); - options.done(types.assertionList(all_assertions, end - start)); - }); -}; - - -/** - * Wraps a test function with setUp and tearDown functions. - * Used by testCase. - * - * @param {Function} setUp - * @param {Function} tearDown - * @param {Function} fn - * @api private - */ - -var wrapTest = function (setUp, tearDown, fn) { - return function (test) { - var context = {}; - if (tearDown) { - var done = test.done; - test.done = function (err) { - try { - tearDown.call(context, function (err2) { - if (err && err2) { - test._assertion_list.push( - types.assertion({error: err}) - ); - return done(err2); - } - done(err || err2); - }); - } - catch (e) { - done(e); - } - }; - } - if (setUp) { - setUp.call(context, function (err) { - if (err) { - return test.done(err); - } - fn.call(context, test); - }); - } - else { - fn.call(context, test); - } - }; -}; - - -/** - * Returns a serial callback from two functions. - * - * @param {Function} funcFirst - * @param {Function} funcSecond - * @api private - */ - -var getSerialCallback = function (fns) { - if (!fns.length) { - return null; - } - return function (callback) { - var that = this; - var bound_fns = []; - for (var i = 0, len = fns.length; i < len; i++) { - (function (j) { - bound_fns.push(function () { - return fns[j].apply(that, arguments); - }); - })(i); - } - return async.series(bound_fns, callback); - }; -}; - - -/** - * Wraps a group of tests with setUp and tearDown functions. - * Used by testCase. - * - * @param {Object} group - * @param {Array} setUps - parent setUp functions - * @param {Array} tearDowns - parent tearDown functions - * @api private - */ - -var wrapGroup = function (group, setUps, tearDowns) { - var tests = {}; - - var setUps = setUps ? setUps.slice(): []; - var tearDowns = tearDowns ? tearDowns.slice(): []; - - if (group.setUp) { - setUps.push(group.setUp); - delete group.setUp; - } - if (group.tearDown) { - tearDowns.unshift(group.tearDown); - delete group.tearDown; - } - - var keys = _keys(group); - - for (var i = 0; i < keys.length; i += 1) { - var k = keys[i]; - if (typeof group[k] === 'function') { - tests[k] = wrapTest( - getSerialCallback(setUps), - getSerialCallback(tearDowns), - group[k] - ); - } - else if (typeof group[k] === 'object') { - tests[k] = wrapGroup(group[k], setUps, tearDowns); - } - } - return tests; -}; - - -/** - * Backwards compatibility for test suites using old testCase API - */ - -exports.testCase = function (suite) { - return suite; -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/nodeunit.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/nodeunit.js deleted file mode 100644 index c7164ca..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/nodeunit.js +++ /dev/null @@ -1,103 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var async = require('../deps/async'), - types = require('./types'), - utils = require('./utils'), - core = require('./core'), - reporters = require('./reporters'), - assert = require('./assert'), - path = require('path'), - events = require('events'); - -/** - * Export sub-modules. - */ - -exports.types = types; -exports.utils = utils; -exports.reporters = reporters; -exports.assert = assert; - -// backwards compatibility -exports.testrunner = { - run: function () { - console.log( - 'WARNING: nodeunit.testrunner is going to be deprecated, please ' + - 'use nodeunit.reporters.default instead!' - ); - return reporters['default'].run.apply(this, arguments); - } -}; - - -/** - * Export all core functions - */ - -for (var k in core) { - exports[k] = core[k]; -}; - - -/** - * Load modules from paths array and run all exported tests in series. If a path - * is a directory, load all supported file types inside it as modules. This only - * reads 1 level deep in the directory and does not recurse through - * sub-directories. - * - * @param {Array} paths - * @param {Object} opt - * @api public - */ - -exports.runFiles = function (paths, opt) { - var all_assertions = []; - var options = types.options(opt); - var start = new Date().getTime(); - - if (!paths.length) { - return options.done(types.assertionList(all_assertions)); - } - - utils.modulePaths(paths, function (err, files) { - if (err) throw err; - async.concatSeries(files, function (file, cb) { - var name = path.basename(file); - exports.runModule(name, require(file), options, cb); - }, - function (err, all_assertions) { - var end = new Date().getTime(); - exports.done() - options.done(types.assertionList(all_assertions, end - start)); - }); - }); - -}; - -/* Export all prototypes from events.EventEmitter */ -var label; -for (label in events.EventEmitter.prototype) { - exports[label] = events.EventEmitter.prototype[label]; -} - -/* Emit event 'complete' on completion of a test suite. */ -exports.complete = function(name, assertions) -{ - exports.emit('complete', name, assertions); -}; - -/* Emit event 'complete' on completion of all tests. */ -exports.done = function() -{ - exports.emit('done'); -}; - -module.exports = exports; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/browser.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/browser.js deleted file mode 100644 index 9836c90..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/browser.js +++ /dev/null @@ -1,121 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - - -/** - * NOTE: this test runner is not listed in index.js because it cannot be - * used with the command-line tool, only inside the browser. - */ - - -/** - * Reporter info string - */ - -exports.info = "Browser-based test reporter"; - - -/** - * Run all tests within each module, reporting the results - * - * @param {Array} files - * @api public - */ - -exports.run = function (modules, options) { - var start = new Date().getTime(), div; - options = options || {}; - div = options.div || document.body; - - function setText(el, txt) { - if ('innerText' in el) { - el.innerText = txt; - } - else if ('textContent' in el){ - el.textContent = txt; - } - } - - function getOrCreate(tag, id) { - var el = document.getElementById(id); - if (!el) { - el = document.createElement(tag); - el.id = id; - div.appendChild(el); - } - return el; - }; - - var header = getOrCreate('h1', 'nodeunit-header'); - var banner = getOrCreate('h2', 'nodeunit-banner'); - var userAgent = getOrCreate('h2', 'nodeunit-userAgent'); - var tests = getOrCreate('ol', 'nodeunit-tests'); - var result = getOrCreate('p', 'nodeunit-testresult'); - - setText(userAgent, navigator.userAgent); - - nodeunit.runModules(modules, { - moduleStart: function (name) { - /*var mheading = document.createElement('h2'); - mheading.innerText = name; - results.appendChild(mheading); - module = document.createElement('ol'); - results.appendChild(module);*/ - }, - testDone: function (name, assertions) { - var test = document.createElement('li'); - var strong = document.createElement('strong'); - strong.innerHTML = name + ' (' + - '' + assertions.failures() + ', ' + - '' + assertions.passes() + ', ' + - assertions.length + - ')'; - test.className = assertions.failures() ? 'fail': 'pass'; - test.appendChild(strong); - - var aList = document.createElement('ol'); - aList.style.display = 'none'; - test.onclick = function () { - var d = aList.style.display; - aList.style.display = (d == 'none') ? 'block': 'none'; - }; - for (var i=0; i' + (a.error.stack || a.error) + ''; - li.className = 'fail'; - } - else { - li.innerHTML = a.message || a.method || 'no message'; - li.className = 'pass'; - } - aList.appendChild(li); - } - test.appendChild(aList); - tests.appendChild(test); - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - - var failures = assertions.failures(); - banner.className = failures ? 'fail': 'pass'; - - result.innerHTML = 'Tests completed in ' + duration + - ' milliseconds.
' + - assertions.passes() + ' assertions of ' + - '' + assertions.length + ' passed, ' + - assertions.failures() + ' failed.'; - } - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/default.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/default.js deleted file mode 100644 index a72a42e..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/default.js +++ /dev/null @@ -1,130 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - track = require('../track'), - path = require('path'), - AssertionError = require('../assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Default tests reporter"; - - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var error = function (str) { - return options.error_prefix + str + options.error_suffix; - }; - var ok = function (str) { - return options.ok_prefix + str + options.ok_suffix; - }; - var bold = function (str) { - return options.bold_prefix + str + options.bold_suffix; - }; - var assertion_message = function (str) { - return options.assertion_prefix + str + options.assertion_suffix; - }; - - var start = new Date().getTime(); - var tracker = track.createTracker(function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log(error(bold( - 'FAILURES: Undone tests (or their setups/teardowns): ' - ))); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log('- ' + names[i]); - } - console.log(''); - console.log('To fix this, make sure all tests call test.done()'); - process.reallyExit(tracker.unfinished()); - } - }); - - var opts = { - testspec: options.testspec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - console.log('✔ ' + name); - } - else { - console.log(error('✖ ' + name) + '\n'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + - assertion_message(a.message) - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - done: function (assertions, end) { - var end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - }, - testStart: function(name) { - tracker.put(name); - } - }; - if (files && files.length) { - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - nodeunit.runFiles(paths, opts); - } else { - nodeunit.runModules(files,opts); - } -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/eclipse.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/eclipse.js deleted file mode 100644 index 6775ff1..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/eclipse.js +++ /dev/null @@ -1,104 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - track = require('../track'), - path = require('path'), - AssertionError = require('../assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Reporter for eclipse plugin"; - - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - var start = new Date().getTime(); - var paths = files.map(function (p) { - if (p.indexOf('/') === 0) { - return p; - } - return path.join(process.cwd(), p); - }); - var tracker = track.createTracker(function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log('FAILURES: Undone tests (or their setups/teardowns): '); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log('- ' + names[i]); - } - console.log(''); - console.log('To fix this, make sure all tests call test.done()'); - process.reallyExit(tracker.unfinished()); - } - }); - - nodeunit.runFiles(paths, { - testspec: undefined, - moduleStart: function (name) { - console.log('\n' + name); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - console.log('✔ ' + name); - } - else { - console.log('✖ ' + name + '\n'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + a.message - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - done: function (assertions, end) { - var end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + 'FAILURES: ' + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + 'OK: ' + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - }, - testStart: function (name) { - tracker.put(name); - } - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/html.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/html.js deleted file mode 100644 index 2790b58..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/html.js +++ /dev/null @@ -1,109 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - path = require('path'), - AssertionError = require('assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Report tests result as HTML"; - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - - console.log(''); - console.log(''); - console.log(''); - console.log(''); - console.log(''); - console.log(''); - nodeunit.runFiles(paths, { - testspec: options.testspec, - moduleStart: function (name) { - console.log('

' + name + '

'); - console.log('
    '); - }, - testDone: function (name, assertions) { - if (!assertions.failures()) { - console.log('
  1. ' + name + '
  2. '); - } - else { - console.log('
  3. ' + name); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log('
    ' + - 'Assertion Message: ' + a.message + - '
    '); - } - console.log('
    ');
    -                        console.log(a.error.stack);
    -                        console.log('
    '); - } - }); - console.log('
  4. '); - } - }, - moduleDone: function () { - console.log('
'); - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '

FAILURES: ' + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)

' - ); - } - else { - console.log( - '

OK: ' + assertions.length + - ' assertions (' + assertions.duration + 'ms)

' - ); - } - console.log(''); - console.log(''); - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - } - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/index.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/index.js deleted file mode 100644 index b3989c0..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/index.js +++ /dev/null @@ -1,14 +0,0 @@ -module.exports = { - 'junit': require('./junit'), - 'default': require('./default'), - 'skip_passed': require('./skip_passed'), - 'minimal': require('./minimal'), - 'html': require('./html'), - 'eclipse': require('./eclipse'), - 'machineout': require('./machineout'), - 'tap': require('./tap'), - 'nested': require('./nested'), - 'verbose' : require('./verbose') - // browser test reporter is not listed because it cannot be used - // with the command line tool, only inside a browser. -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/junit.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/junit.js deleted file mode 100644 index ea12280..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/junit.js +++ /dev/null @@ -1,179 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - path = require('path'), - async = require('../../deps/async'), - AssertionError = require('assert').AssertionError, - child_process = require('child_process'), - ejs = require('../../deps/ejs'); - - -/** - * Reporter info string - */ - -exports.info = "jUnit XML test reports"; - - -/** - * Ensures a directory exists using mkdir -p. - * - * @param {String} path - * @param {Function} callback - * @api private - */ - -var ensureDir = function (path, callback) { - var mkdir = child_process.spawn('mkdir', ['-p', path]); - mkdir.on('error', function (err) { - callback(err); - callback = function(){}; - }); - mkdir.on('exit', function (code) { - if (code === 0) callback(); - else callback(new Error('mkdir exited with code: ' + code)); - }); -}; - - -/** - * Returns absolute version of a path. Relative paths are interpreted - * relative to process.cwd() or the cwd parameter. Paths that are already - * absolute are returned unaltered. - * - * @param {String} p - * @param {String} cwd - * @return {String} - * @api public - */ - -var abspath = function (p, /*optional*/cwd) { - if (p[0] === '/') return p; - cwd = cwd || process.cwd(); - return path.normalize(path.join(cwd, p)); -}; - - -/** - * Run all tests within each module, reporting the results to the command-line, - * then writes out junit-compatible xml documents. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, opts, callback) { - if (!opts.output) { - console.error( - 'Error: No output directory defined.\n' + - '\tEither add an "output" property to your nodeunit.json config ' + - 'file, or\n\tuse the --output command line option.' - ); - return; - } - opts.output = abspath(opts.output); - var error = function (str) { - return opts.error_prefix + str + opts.error_suffix; - }; - var ok = function (str) { - return opts.ok_prefix + str + opts.ok_suffix; - }; - var bold = function (str) { - return opts.bold_prefix + str + opts.bold_suffix; - }; - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - - var modules = {} - var curModule; - - nodeunit.runFiles(paths, { - testspec: opts.testspec, - moduleStart: function (name) { - curModule = { - errorCount: 0, - failureCount: 0, - tests: 0, - testcases: [], - name: name - }; - modules[name] = curModule; - }, - testDone: function (name, assertions) { - var testcase = {name: name}; - for (var i=0; i name_slice(['TC1', 'TC1.1', 'mytest'], 1); - * "TC1,TC1.1" - */ - var name_slice = function (name_arr, end_index) { - return name_arr.slice(0, end_index + 1).join(","); - }; - - var indent = (function () { - var txt = ''; - var i; - for (i = 0; i < spaces_per_indent; i++) { - txt += ' '; - } - return txt; - }()); - - // Indent once for each indent_level - var add_indent = function (txt, indent_level) { - var k; - for (k = 0; k < indent_level; k++) { - txt += indent; - } - return txt; - }; - - // If it's not the last element of the name_arr, it's a testCase. - var is_testCase = function (name_arr, index) { - return index === name_arr.length - 1 ? false : true; - }; - - var testCase_line = function (txt) { - return txt + "\n"; - }; - - /** - * Prints (console.log) the nested test status line(s). - * - * @param {Array} name_arr - Array of name elements. - * @param {String} status - either 'pass' or 'fail'. - * @example - * > print_status(['TC1', 'TC1.1', 'mytest'], 'pass'); - * TC1 - * TC1.1 - * mytest (pass) - */ - var print_status = function (name_arr, status) { - var txt = ''; - var _name_slice, part, i; - for (i = 0; i < name_arr.length; i++) { - _name_slice = name_slice(name_arr, i); - part = name_arr[i]; - if (!tracker.already_printed[_name_slice]) { - txt = add_indent(txt, i); - if (is_testCase(name_arr, i)) { - txt += testCase_line(part); - } else { - txt += status_text(part, status); - } - tracker.already_printed[_name_slice] = true; - } - } - console.log(txt); - }; - - nodeunit.runFiles(paths, { - testspec: options.testspec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - print_status(name, 'pass'); - } else { - print_status(name, 'fail'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + - assertion_message(a.message) - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - done: function (assertions, end) { - end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - }, - testStart: function (name) { - tracker.put(name); - } - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/skip_passed.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/skip_passed.js deleted file mode 100644 index b39de41..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/skip_passed.js +++ /dev/null @@ -1,107 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - path = require('path'), - AssertionError = require('assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Skip passed tests output"; - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options, callback) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var error = function (str) { - return options.error_prefix + str + options.error_suffix; - }; - var ok = function (str) { - return options.ok_prefix + str + options.ok_suffix; - }; - var bold = function (str) { - return options.bold_prefix + str + options.bold_suffix; - }; - var assertion_message = function (str) { - return options.assertion_prefix + str + options.assertion_suffix; - }; - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - - nodeunit.runFiles(paths, { - testspec: options.testspec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - if (assertions.failures()) { - console.log(error('✖ ' + name) + '\n'); - assertions.forEach(function (a) { - if (a.failed()) { - a = utils.betterErrors(a); - if (a.error instanceof AssertionError && a.message) { - console.log( - 'Assertion Message: ' + assertion_message(a.message) - ); - } - console.log(a.error.stack + '\n'); - } - }); - } - }, - moduleDone: function (name, assertions) { - if (!assertions.failures()) { - console.log('✔ all tests passed'); - } - else { - console.log(error('✖ some tests failed')); - } - }, - done: function (assertions) { - var end = new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - - if (callback) callback(assertions.failures() ? new Error('We have got test failures.') : undefined); - } - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/tap.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/tap.js deleted file mode 100644 index b057460..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/tap.js +++ /dev/null @@ -1,65 +0,0 @@ -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - path = require('path'), - assert = require('tap-assert'), - TapProducer = require('tap-producer'); - -/** - * Reporter info string - */ - -exports.info = "TAP output"; - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - var output = new TapProducer(); - output.pipe(process.stdout); - - nodeunit.runFiles(paths, { - testStart: function (name) { - output.write(name.toString()); - }, - testDone: function (name, assertions) { - assertions.forEach(function (e) { - var extra = {}; - if (e.error) { - extra.error = { - name: e.error.name, - message: e.error.message, - stack: e.error.stack.split(/\n/).filter(function (line) { - // exclude line of "types.js" - return ! RegExp(/types.js:83:39/).test(line); - }).join('\n') - }; - extra.wanted = e.error.expected; - extra.found = e.error.actual; - } - output.write(assert(e.passed(), e.message, extra)); - }); - }, - done: function (assertions) { - output.end(); - } - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/verbose.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/verbose.js deleted file mode 100644 index 6ccb617..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/reporters/verbose.js +++ /dev/null @@ -1,122 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var nodeunit = require('../nodeunit'), - utils = require('../utils'), - fs = require('fs'), - track = require('../track'), - path = require('path'); - AssertionError = require('../assert').AssertionError; - -/** - * Reporter info string - */ - -exports.info = "Verbose tests reporter" - - -/** - * Run all tests within each module, reporting the results to the command-line. - * - * @param {Array} files - * @api public - */ - -exports.run = function (files, options) { - - if (!options) { - // load default options - var content = fs.readFileSync( - __dirname + '/../../bin/nodeunit.json', 'utf8' - ); - options = JSON.parse(content); - } - - var error = function (str) { - return options.error_prefix + str + options.error_suffix; - }; - var ok = function (str) { - return options.ok_prefix + str + options.ok_suffix; - }; - var bold = function (str) { - return options.bold_prefix + str + options.bold_suffix; - }; - var assertion_message = function (str) { - return options.assertion_prefix + str + options.assertion_suffix; - }; - - var start = new Date().getTime(); - var paths = files.map(function (p) { - return path.join(process.cwd(), p); - }); - var tracker = track.createTracker(function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log(error(bold( - 'FAILURES: Undone tests (or their setups/teardowns): ' - ))); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log('- ' + names[i]); - } - console.log(''); - console.log('To fix this, make sure all tests call test.done()'); - process.reallyExit(tracker.unfinished()); - } - }); - - nodeunit.runFiles(paths, { - testspec: options.testspec, - moduleStart: function (name) { - console.log('\n' + bold(name)); - }, - testDone: function (name, assertions) { - tracker.remove(name); - - if (!assertions.failures()) { - console.log('✔ ' + name); - } - else { - console.log(error('✖ ' + name)); - } - // verbose so print everything - assertions.forEach(function (a) { - if (a.failed()) { - console.log(error(' ✖ ' + a.message)); - a = utils.betterErrors(a); - console.log(' ' + a.error.stack); - } - else { - console.log(' ✔ ' + a.message); - } - }); - }, - done: function (assertions, end) { - var end = end || new Date().getTime(); - var duration = end - start; - if (assertions.failures()) { - console.log( - '\n' + bold(error('FAILURES: ')) + assertions.failures() + - '/' + assertions.length + ' assertions failed (' + - assertions.duration + 'ms)' - ); - } - else { - console.log( - '\n' + bold(ok('OK: ')) + assertions.length + - ' assertions (' + assertions.duration + 'ms)' - ); - } - }, - testStart: function(name) { - tracker.put(name); - } - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/track.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/track.js deleted file mode 100644 index 5af98ad..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/track.js +++ /dev/null @@ -1,48 +0,0 @@ -/*! - * Simple util module to track tests. Adds a process.exit hook to print - * the undone tests. - */ - - -exports.createTracker = function (on_exit) { - var names = {}; - var tracker = { - names: function () { - var arr = []; - for (var k in names) { - if (names.hasOwnProperty(k)) { - arr.push(k); - } - } - return arr; - }, - unfinished: function () { - return tracker.names().length; - }, - put: function (testname) { - names[testname] = testname; - }, - remove: function (testname) { - delete names[testname]; - } - }; - - process.on('exit', function() { - on_exit = on_exit || exports.default_on_exit; - on_exit(tracker); - }); - - return tracker; -}; - -exports.default_on_exit = function (tracker) { - if (tracker.unfinished()) { - console.log(''); - console.log('Undone tests (or their setups/teardowns): '); - var names = tracker.names(); - for (var i = 0; i < names.length; i += 1) { - console.log(names[i]); - } - process.reallyExit(tracker.unfinished()); - } -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/types.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/types.js deleted file mode 100644 index 2cdd1ef..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/types.js +++ /dev/null @@ -1,189 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, it's mostly to avoid requiring code - * that is node specific - */ - -/** - * Module dependencies - */ - -var assert = require('./assert'), //@REMOVE_LINE_FOR_BROWSER - async = require('../deps/async'); //@REMOVE_LINE_FOR_BROWSER - - -/** - * Creates assertion objects representing the result of an assert call. - * Accepts an object or AssertionError as its argument. - * - * @param {object} obj - * @api public - */ - -exports.assertion = function (obj) { - return { - method: obj.method || '', - message: obj.message || (obj.error && obj.error.message) || '', - error: obj.error, - passed: function () { - return !this.error; - }, - failed: function () { - return Boolean(this.error); - } - }; -}; - -/** - * Creates an assertion list object representing a group of assertions. - * Accepts an array of assertion objects. - * - * @param {Array} arr - * @param {Number} duration - * @api public - */ - -exports.assertionList = function (arr, duration) { - var that = arr || []; - that.failures = function () { - var failures = 0; - for (var i = 0; i < this.length; i += 1) { - if (this[i].failed()) { - failures += 1; - } - } - return failures; - }; - that.passes = function () { - return that.length - that.failures(); - }; - that.duration = duration || 0; - return that; -}; - -/** - * Create a wrapper function for assert module methods. Executes a callback - * after it's complete with an assertion object representing the result. - * - * @param {Function} callback - * @api private - */ - -var assertWrapper = function (callback) { - return function (new_method, assert_method, arity) { - return function () { - var message = arguments[arity - 1]; - var a = exports.assertion({method: new_method, message: message}); - try { - assert[assert_method].apply(null, arguments); - } - catch (e) { - a.error = e; - } - callback(a); - }; - }; -}; - -/** - * Creates the 'test' object that gets passed to every test function. - * Accepts the name of the test function as its first argument, followed by - * the start time in ms, the options object and a callback function. - * - * @param {String} name - * @param {Number} start - * @param {Object} options - * @param {Function} callback - * @api public - */ - -exports.test = function (name, start, options, callback) { - var expecting; - var a_list = []; - - var wrapAssert = assertWrapper(function (a) { - a_list.push(a); - if (options.log) { - async.nextTick(function () { - options.log(a); - }); - } - }); - - var test = { - done: function (err) { - if (expecting !== undefined && expecting !== a_list.length) { - var e = new Error( - 'Expected ' + expecting + ' assertions, ' + - a_list.length + ' ran' - ); - var a1 = exports.assertion({method: 'expect', error: e}); - a_list.push(a1); - if (options.log) { - async.nextTick(function () { - options.log(a1); - }); - } - } - if (err) { - var a2 = exports.assertion({error: err}); - a_list.push(a2); - if (options.log) { - async.nextTick(function () { - options.log(a2); - }); - } - } - var end = new Date().getTime(); - async.nextTick(function () { - var assertion_list = exports.assertionList(a_list, end - start); - options.testDone(name, assertion_list); - callback(null, a_list); - }); - }, - ok: wrapAssert('ok', 'ok', 2), - same: wrapAssert('same', 'deepEqual', 3), - equals: wrapAssert('equals', 'equal', 3), - expect: function (num) { - expecting = num; - }, - _assertion_list: a_list - }; - // add all functions from the assert module - for (var k in assert) { - if (assert.hasOwnProperty(k)) { - test[k] = wrapAssert(k, k, assert[k].length); - } - } - return test; -}; - -/** - * Ensures an options object has all callbacks, adding empty callback functions - * if any are missing. - * - * @param {Object} opt - * @return {Object} - * @api public - */ - -exports.options = function (opt) { - var optionalCallback = function (name) { - opt[name] = opt[name] || function () {}; - }; - - optionalCallback('moduleStart'); - optionalCallback('moduleDone'); - optionalCallback('testStart'); - optionalCallback('testDone'); - //optionalCallback('log'); - - // 'done' callback is not optional. - - return opt; -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/utils.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/utils.js deleted file mode 100644 index 8f49e46..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/lib/utils.js +++ /dev/null @@ -1,209 +0,0 @@ -/*! - * Nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - */ - -/** - * Module dependencies - */ - -var async = require('../deps/async'), - fs = require('fs'), - util = require('util'), - Script = process.binding('evals').Script || process.binding('evals').NodeScript, - http = require('http'); - - -/** - * Detect if coffee-script is available and search for .coffee as an - * extension in modulePaths if it is. - */ - -var extensionPattern; -try { - require('coffee-script'); - extensionPattern = /\.(?:js|coffee)$/; -} -catch (e) { - extensionPattern = /\.js$/; -} - - -/** - * Finds all modules at each path in an array, If a path is a directory, it - * returns all supported file types inside it. This only reads 1 level deep in - * the directory and does not recurse through sub-directories. - * - * The extension (.js, .coffee etc) is stripped from the filenames so they can - * simply be require()'ed. - * - * @param {Array} paths - * @param {Function} callback - * @api public - */ - -exports.modulePaths = function (paths, callback) { - async.concat(paths, function (p, cb) { - fs.stat(p, function (err, stats) { - if (err) { - return cb(err); - } - if (stats.isFile()) { - return cb(null, [p]); - } - if (stats.isDirectory()) { - fs.readdir(p, function (err, files) { - if (err) { - return cb(err); - } - - // filter out any filenames with unsupported extensions - var modules = files.filter(function (filename) { - return extensionPattern.exec(filename); - }); - - // remove extension from module name and prepend the - // directory path - var fullpaths = modules.map(function (filename) { - var mod_name = filename.replace(extensionPattern, ''); - return [p, mod_name].join('/'); - }); - - // sort filenames here, because Array.map changes order - fullpaths.sort(); - - cb(null, fullpaths); - }); - } - }); - }, callback); -}; - -/** - * Evaluates JavaScript files in a sandbox, returning the context. The first - * argument can either be a single filename or an array of filenames. If - * multiple filenames are given their contents are concatenated before - * evalution. The second argument is an optional context to use for the sandbox. - * - * @param files - * @param {Object} sandbox - * @return {Object} - * @api public - */ - -exports.sandbox = function (files, /*optional*/sandbox) { - var source, script, result; - if (!(files instanceof Array)) { - files = [files]; - } - source = files.map(function (file) { - return fs.readFileSync(file, 'utf8'); - }).join(''); - - if (!sandbox) { - sandbox = {}; - } - script = new Script(source); - result = script.runInNewContext(sandbox); - return sandbox; -}; - -/** - * Provides a http request, response testing environment. - * - * Example: - * - * var httputil = require('nodeunit').utils.httputil - * exports.testSomething = function(test) { - * httputil(function (req, resp) { - * resp.writeHead(200, {}); - * resp.end('test data'); - * }, - * function(server, client) { - * client.fetch('GET', '/', {}, function(resp) { - * test.equal('test data', resp.body); - * server.close(); - * test.done(); - * }) - * }); - * }; - * - * @param {Function} cgi - * @param {Function} envReady - * @api public - */ -exports.httputil = function (cgi, envReady) { - var hostname = process.env.HOSTNAME || 'localhost'; - var port = process.env.PORT || 3000; - - var server = http.createServer(cgi); - server.listen(port, hostname); - - var client = http.createClient(port, hostname); - client.fetch = function (method, path, headers, respReady) { - var request = this.request(method, path, headers); - request.end(); - request.on('response', function (response) { - response.setEncoding('utf8'); - response.on('data', function (chunk) { - if (response.body) { - response.body += chunk; - } else { - response.body = chunk; - } - }); - response.on('end', function () { - if (response.headers['content-type'] === 'application/json') { - response.bodyAsObject = JSON.parse(response.body); - } - respReady(response); - }); - }); - }; - - process.nextTick(function () { - if (envReady && typeof envReady === 'function') { - envReady(server, client); - } - }); -}; - - -/** - * Improves formatting of AssertionError messages to make deepEqual etc more - * readable. - * - * @param {Object} assertion - * @return {Object} - * @api public - */ - -exports.betterErrors = function (assertion) { - if (!assertion.error) return; - - var e = assertion.error; - // deepEqual error message is a bit sucky, lets improve it! - // e.actual and e.expected could be null or undefined, so - // using getOwnPropertyDescriptor to see if they exist: - if (Object.getOwnPropertyDescriptor(e, 'actual') && - Object.getOwnPropertyDescriptor(e, 'expected')) { - - // alexgorbatchev 2010-10-22 :: Added a bit of depth to inspection - var actual = util.inspect(e.actual, false, 10).replace(/\n$/, ''); - var expected = util.inspect(e.expected, false, 10).replace(/\n$/, ''); - var multiline = ( - actual.indexOf('\n') !== -1 || - expected.indexOf('\n') !== -1 - ); - var spacing = (multiline ? '\n' : ' '); - e._message = e.message; - e.stack = ( - e.name + ':' + spacing + - actual + spacing + e.operator + spacing + - expected + '\n' + - e.stack.split('\n').slice(1).join('\n') - ); - } - return assertion; -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/man1/nodeunit.1 b/node_modules/reg/node_modules/mongodb/deps/nodeunit/man1/nodeunit.1 deleted file mode 100644 index 450772d..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/man1/nodeunit.1 +++ /dev/null @@ -1,95 +0,0 @@ -.\" Generated with Ronnjs/v0.1 -.\" http://github.com/kapouer/ronnjs/ -. -.TH "NODEUNIT" "1" "October 2010" "" "" -. -.SH "NAME" -\fBnodeunit\fR \-\- simple node\.js unit testing tool -. -.SH "SYNOPSIS" -. -.nf -nodeunit [options] [ \.\.\.] -. -.fi -. -.SH "DESCRIPTION" -Nodeunit is a simple unit testing tool based on the node\.js assert module\. -. -.IP "\(bu" 4 -Simple to use -. -.IP "\(bu" 4 -Just export the tests from a module -. -.IP "\(bu" 4 -Helps you avoid common pitfalls when testing asynchronous code -. -.IP "\(bu" 4 -Easy to add test cases with setUp and tearDown functions if you wish -. -.IP "\(bu" 4 -Allows the use of mocks and stubs -. -.IP "" 0 -. -.SH "OPTIONS" - \fB\-\-config FILE\fR: -. -.br - Load config options from a JSON file, allows the customisation - of color schemes for the default test reporter etc\. - See bin/nodeunit\.json for current available options\. -. -.P - \fB\-\-reporter FILE\fR: -. -.br - You can set the test reporter to a custom module or on of the modules - in nodeunit/lib/reporters, when omitted, the default test runner is used\. -. -.P - \fB\-\-list\-reporters\fR: -. -.br - List available build\-in reporters\. -. -.P - \fB\-h\fR, \fB\-\-help\fR: -. -.br - Display the help and exit\. -. -.P - \fB\-v\fR, \fB\-\-version\fR: -. -.br - Output version information and exit\. -. -.P - \fB\fR: - You can run nodeunit on specific files or on all \fI*\.js\fR files inside -. -.br - a directory\. -. -.SH "AUTHORS" -Written by Caolan McMahon and other nodeunit contributors\. -. -.br -Contributors list: \fIhttp://github\.com/caolan/nodeunit/contributors\fR\|\. -. -.SH "REPORTING BUGS" -Report nodeunit bugs to \fIhttp://github\.com/caolan/nodeunit/issues\fR\|\. -. -.SH "COPYRIGHT" -Copyright © 2010 Caolan McMahon\. -. -.br -Nodeunit has been released under the MIT license: -. -.br -\fIhttp://github\.com/caolan/nodeunit/raw/master/LICENSE\fR\|\. -. -.SH "SEE ALSO" -node(1) diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/nodelint.cfg b/node_modules/reg/node_modules/mongodb/deps/nodeunit/nodelint.cfg deleted file mode 100644 index d6a3aad..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/nodelint.cfg +++ /dev/null @@ -1,7 +0,0 @@ -//See: http://www.jslint.com/lint.html#options -var options = { - //white: false, // if false, strict whitespace rules should be enforced. - indent: 4, - onevar: false, - vars: true // allow multiple var statement per function. -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/package.json b/node_modules/reg/node_modules/mongodb/deps/nodeunit/package.json deleted file mode 100644 index 6a5d86e..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/package.json +++ /dev/null @@ -1,65 +0,0 @@ -{ "name": "nodeunit" -, "description": "Easy unit testing for node.js and the browser." -, "maintainers": - [ { "name": "Caolan McMahon" - , "web": "https://github.com/caolan" - } - ] -, "contributors" : - [ { "name": "Romain Beauxis" - , "web": "https://github.com/toots" - } - , { "name": "Alex Gorbatchev" - , "web": "https://github.com/alexgorbatchev" - } - , { "name": "Alex Wolfe" - , "web": "https://github.com/alexkwolfe" - } - , { "name": "Carl Fürstenberg" - , "web": "https://github.com/azatoth" - } - , { "name": "Gerad Suyderhoud" - , "web": "https://github.com/gerad" - } - , { "name": "Kadir Pekel" - , "web": "https://github.com/coffeemate" - } - , { "name": "Oleg Efimov" - , "web": "https://github.com/Sannis" - } - , { "name": "Orlando Vazquez" - , "web": "https://github.com/orlandov" - } - , { "name": "Ryan Dahl" - , "web": "https://github.com/ry" - } - , { "name": "Sam Stephenson" - , "web": "https://github.com/sstephenson" - } - , { "name": "Thomas Mayfield" - , "web": "https://github.com/thegreatape" - } - , { "name": "Elijah Insua ", - "web": "http://tmpvar.com" - } - ] -, "version": "0.6.4" -, "repository" : - { "type" : "git" - , "url" : "http://github.com/caolan/nodeunit.git" - } -, "devDependencies": - { "uglify-js": ">=1.1.0" } -, "bugs" : { "url" : "http://github.com/caolan/nodeunit/issues" } -, "licenses" : - [ { "type" : "MIT" - , "url" : "http://github.com/caolan/nodeunit/raw/master/LICENSE" - } - ] -, "directories" : { "lib": "./lib", "doc" : "./doc", "man" : "./man1" } -, "bin" : { "nodeunit" : "./bin/nodeunit" } -, "dependencies" : - { "tap-assert": ">=0.0.9" - , "tap-producer": ">=0.0.1" - } -} diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/share/junit.xml.ejs b/node_modules/reg/node_modules/mongodb/deps/nodeunit/share/junit.xml.ejs deleted file mode 100644 index c1db5bb..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/share/junit.xml.ejs +++ /dev/null @@ -1,19 +0,0 @@ - -<% for (var i=0; i < suites.length; i++) { %> - <% var suite=suites[i]; %> - - <% for (var j=0; j < suite.testcases.length; j++) { %> - <% var testcase=suites[i].testcases[j]; %> - - <% if (testcase.failure) { %> - - <% if (testcase.failure.backtrace) { %><%= testcase.failure.backtrace %><% } %> - - <% } %> - - <% } %> - -<% } %> diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/share/license.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/share/license.js deleted file mode 100644 index f0f326f..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/share/license.js +++ /dev/null @@ -1,11 +0,0 @@ -/*! - * Nodeunit - * https://github.com/caolan/nodeunit - * Copyright (c) 2010 Caolan McMahon - * MIT Licensed - * - * json2.js - * http://www.JSON.org/json2.js - * Public Domain. - * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - */ diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/share/nodeunit.css b/node_modules/reg/node_modules/mongodb/deps/nodeunit/share/nodeunit.css deleted file mode 100644 index 274434a..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/share/nodeunit.css +++ /dev/null @@ -1,70 +0,0 @@ -/*! - * Styles taken from qunit.css - */ - -h1#nodeunit-header, h1.nodeunit-header { - padding: 15px; - font-size: large; - background-color: #06b; - color: white; - font-family: 'trebuchet ms', verdana, arial; - margin: 0; -} - -h1#nodeunit-header a { - color: white; -} - -h2#nodeunit-banner { - height: 2em; - border-bottom: 1px solid white; - background-color: #eee; - margin: 0; - font-family: 'trebuchet ms', verdana, arial; -} -h2#nodeunit-banner.pass { - background-color: green; -} -h2#nodeunit-banner.fail { - background-color: red; -} - -h2#nodeunit-userAgent, h2.nodeunit-userAgent { - padding: 10px; - background-color: #eee; - color: black; - margin: 0; - font-size: small; - font-weight: normal; - font-family: 'trebuchet ms', verdana, arial; - font-size: 10pt; -} - -div#nodeunit-testrunner-toolbar { - background: #eee; - border-top: 1px solid black; - padding: 10px; - font-family: 'trebuchet ms', verdana, arial; - margin: 0; - font-size: 10pt; -} - -ol#nodeunit-tests { - font-family: 'trebuchet ms', verdana, arial; - font-size: 10pt; -} -ol#nodeunit-tests li strong { - cursor:pointer; -} -ol#nodeunit-tests .pass { - color: green; -} -ol#nodeunit-tests .fail { - color: red; -} - -p#nodeunit-testresult { - margin-left: 1em; - font-size: 10pt; - font-family: 'trebuchet ms', verdana, arial; -} diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/coffee/mock_coffee_module.coffee b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/coffee/mock_coffee_module.coffee deleted file mode 100644 index a1c069b..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/coffee/mock_coffee_module.coffee +++ /dev/null @@ -1,4 +0,0 @@ -j = 0 -j += i for i in [0..5] - -exports.name = "mock_coffee_#{j}" diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module3.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module3.js deleted file mode 100644 index 3021776..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module3.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module3'; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module4.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module4.js deleted file mode 100644 index 876f9ca..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/dir/mock_module4.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module4'; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module1.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module1.js deleted file mode 100644 index 4c093ad..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module1.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module1'; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module2.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module2.js deleted file mode 100644 index a63d012..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/mock_module2.js +++ /dev/null @@ -1 +0,0 @@ -exports.name = 'mock_module2'; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode1.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode1.js deleted file mode 100644 index 2ef7115..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode1.js +++ /dev/null @@ -1,3 +0,0 @@ -function hello_world(arg) { - return "_" + arg + "_"; -} diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode2.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode2.js deleted file mode 100644 index 55a764e..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode2.js +++ /dev/null @@ -1,3 +0,0 @@ -function get_a_variable() { - return typeof a_variable; -} diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode3.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode3.js deleted file mode 100644 index 1fd1e78..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/fixtures/raw_jscode3.js +++ /dev/null @@ -1 +0,0 @@ -var t=t?t+1:1; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-base.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-base.js deleted file mode 100644 index 64b8c8b..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-base.js +++ /dev/null @@ -1,219 +0,0 @@ -/* - * This module is not a plain nodeunit test suite, but instead uses the - * assert module to ensure a basic level of functionality is present, - * allowing the rest of the tests to be written using nodeunit itself. - * - * THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var assert = require('assert'), // @REMOVE_LINE_FOR_BROWSER - async = require('../deps/async'), // @REMOVE_LINE_FOR_BROWSER - nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - - -// NOT A TEST - util function to make testing faster. -// retries the assertion until it passes or the timeout is reached, -// at which point it throws the assertion error -var waitFor = function (fn, timeout, callback, start) { - start = start || new Date().getTime(); - callback = callback || function () {}; - try { - fn(); - callback(); - } - catch (e) { - if (e instanceof assert.AssertionError) { - var now = new Date().getTime(); - if (now - start >= timeout) { - throw e; - } - else { - async.nextTick(function () { - waitFor(fn, timeout, callback, start); - }); - } - } - else { - throw e; - } - } -}; - - -// TESTS: - -// Are exported tests actually run? - store completed tests in this variable -// for checking later -var tests_called = {}; - -// most basic test that should run, the tests_called object is tested -// at the end of this module to ensure the tests were actually run by nodeunit -exports.testCalled = function (test) { - tests_called.testCalled = true; - test.done(); -}; - -// generates test functions for nodeunit assertions -var makeTest = function (method, args_pass, args_fail) { - return function (test) { - var test1_called = false; - var test2_called = false; - - // test pass - nodeunit.runTest( - 'testname', - function (test) { - test[method].apply(test, args_pass); - test.done(); - }, - {testDone: function (name, assertions) { - assert.equal(assertions.length, 1); - assert.equal(assertions.failures(), 0); - }}, - function () { - test1_called = true; - } - ); - - // test failure - nodeunit.runTest( - 'testname', - function (test) { - test[method].apply(test, args_fail); - test.done(); - }, - {testDone: function (name, assertions) { - assert.equal(assertions.length, 1); - assert.equal(assertions.failures(), 1); - }}, - function () { - test2_called = true; - } - ); - - // ensure tests were run - waitFor(function () { - assert.ok(test1_called); - assert.ok(test2_called); - tests_called[method] = true; - }, 500, test.done); - }; -}; - -// ensure basic assertions are working: -exports.testOk = makeTest('ok', [true], [false]); -exports.testEquals = makeTest('equals', [1, 1], [1, 2]); -exports.testSame = makeTest('same', - [{test: 'test'}, {test: 'test'}], - [{test: 'test'}, {monkey: 'penguin'}] -); - -// from the assert module: -exports.testEqual = makeTest('equal', [1, 1], [1, 2]); -exports.testNotEqual = makeTest('notEqual', [1, 2], [1, 1]); -exports.testDeepEqual = makeTest('deepEqual', - [{one: 1}, {one: 1}], [{one: 1}, {two: 2}] -); -exports.testNotDeepEqual = makeTest('notDeepEqual', - [{one: 1}, {two: 2}], [{one: 1}, {one: 1}] -); -exports.testStrictEqual = makeTest('strictEqual', [1, 1], [1, true]); -exports.testNotStrictEqual = makeTest('notStrictEqual', [true, 1], [1, 1]); -exports.testThrows = makeTest('throws', - [function () { - throw new Error('test'); - }], - [function () { - return; - }] -); -exports.testDoesNotThrows = makeTest('doesNotThrow', - [function () { - return; - }], - [function () { - throw new Error('test'); - }] -); -exports.testIfError = makeTest('ifError', [false], [new Error('test')]); - - -exports.testExpect = function (test) { - var test1_called = false, - test2_called = false, - test3_called = false; - - // correct number of tests run - nodeunit.runTest( - 'testname', - function (test) { - test.expect(2); - test.ok(true); - test.ok(true); - test.done(); - }, - {testDone: function (name, assertions) { - test.equals(assertions.length, 2); - test.equals(assertions.failures(), 0); - }}, - function () { - test1_called = true; - } - ); - - // no tests run - nodeunit.runTest( - 'testname', - function (test) { - test.expect(2); - test.done(); - }, - {testDone: function (name, assertions) { - test.equals(assertions.length, 1); - test.equals(assertions.failures(), 1); - }}, - function () { - test2_called = true; - } - ); - - // incorrect number of tests run - nodeunit.runTest( - 'testname', - function (test) { - test.expect(2); - test.ok(true); - test.ok(true); - test.ok(true); - test.done(); - }, - {testDone: function (name, assertions) { - test.equals(assertions.length, 4); - test.equals(assertions.failures(), 1); - }}, - function () { - test3_called = true; - } - ); - - // ensure callbacks fired - waitFor(function () { - assert.ok(test1_called); - assert.ok(test2_called); - assert.ok(test3_called); - tests_called.expect = true; - }, 500, test.done); -}; - - -// tests are async, so wait for them to be called -waitFor(function () { - assert.ok(tests_called.testCalled); - assert.ok(tests_called.ok); - assert.ok(tests_called.equals); - assert.ok(tests_called.same); - assert.ok(tests_called.expect); -}, 10000); diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-failing-callbacks.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-failing-callbacks.js deleted file mode 100644 index 08f7eb5..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-failing-callbacks.js +++ /dev/null @@ -1,114 +0,0 @@ -var nodeunit = require('../lib/nodeunit'); - - -exports.testFailingLog = function (test) { - test.expect(3); - - // this is meant to bubble to the top, and will be ignored for the purposes - // of testing: - var ignored_error = new Error('ignore this callback error'); - var err_handler = function (err) { - if (err && err.message !== ignored_error.message) { - throw err; - } - }; - process.addListener('uncaughtException', err_handler); - - // A failing callback should not affect the test outcome - var testfn = function (test) { - test.ok(true, 'test.ok'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.ok(true, 'log called'); - throw ignored_error; - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'total'); - process.removeListener('uncaughtException', err_handler); - } - }, test.done); -}; - -exports.testFailingTestDone = function (test) { - test.expect(2); - - var ignored_error = new Error('ignore this callback error'); - var err_handler = function (err) { - if (err && err.message !== ignored_error.message) { - throw err; - } - }; - process.addListener('uncaughtException', err_handler); - - // A failing callback should not affect the test outcome - var testfn = function (test) { - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.ok(false, 'log should not be called'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 0, 'total'); - process.nextTick(function () { - process.removeListener('uncaughtException', err_handler); - test.done(); - }); - throw ignored_error; - } - }, function () {}); -}; - -exports.testAssertionObj = function (test) { - test.expect(4); - var testfn = function (test) { - test.ok(true, 'ok true'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.ok(assertion.passed() === true, 'assertion.passed'); - test.ok(assertion.failed() === false, 'assertion.failed'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'total'); - } - }, test.done); -}; - -exports.testLogOptional = function (test) { - test.expect(2); - var testfn = function (test) { - test.ok(true, 'ok true'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'total'); - } - }, test.done); -}; - -exports.testExpectWithFailure = function (test) { - test.expect(3); - var testfn = function (test) { - test.expect(1); - test.ok(false, 'test.ok'); - test.done(); - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.equals(assertion.method, 'ok', 'assertion.method'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 1, 'failures'); - test.equals(assertions.length, 1, 'total'); - } - }, test.done); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-httputil.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-httputil.js deleted file mode 100644 index e5ee25c..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-httputil.js +++ /dev/null @@ -1,55 +0,0 @@ -var nodeunit = require('../lib/nodeunit'); -var httputil = require('../lib/utils').httputil; - -exports.testHttpUtilBasics = function (test) { - - test.expect(6); - - httputil(function (req, resp) { - test.equal(req.method, 'PUT'); - test.equal(req.url, '/newpair'); - test.equal(req.headers.foo, 'bar'); - - resp.writeHead(500, {'content-type': 'text/plain'}); - resp.end('failed'); - }, function (server, client) { - client.fetch('PUT', '/newpair', {'foo': 'bar'}, function (resp) { - test.equal(resp.statusCode, 500); - test.equal(resp.headers['content-type'], 'text/plain'); - test.equal(resp.body, 'failed'); - - server.close(); - test.done(); - }); - }); -}; - -exports.testHttpUtilJsonHandling = function (test) { - - test.expect(9); - - httputil(function (req, resp) { - test.equal(req.method, 'GET'); - test.equal(req.url, '/'); - test.equal(req.headers.foo, 'bar'); - - var testdata = {foo1: 'bar', foo2: 'baz'}; - - resp.writeHead(200, {'content-type': 'application/json'}); - resp.end(JSON.stringify(testdata)); - - }, function (server, client) { - client.fetch('GET', '/', {'foo': 'bar'}, function (resp) { - test.equal(resp.statusCode, 200); - test.equal(resp.headers['content-type'], 'application/json'); - - test.ok(resp.bodyAsObject); - test.equal(typeof resp.bodyAsObject, 'object'); - test.equal(resp.bodyAsObject.foo1, 'bar'); - test.equal(resp.bodyAsObject.foo2, 'baz'); - - server.close(); - test.done(); - }); - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-runfiles.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-runfiles.js deleted file mode 100644 index ce1a4cd..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-runfiles.js +++ /dev/null @@ -1,214 +0,0 @@ -var assert = require('assert'), - fs = require('fs'), - path = require('path'), - nodeunit = require('../lib/nodeunit'); - - -var setup = function (fn) { - return function (test) { - process.chdir(__dirname); - var env = { - mock_module1: require(__dirname + '/fixtures/mock_module1'), - mock_module2: require(__dirname + '/fixtures/mock_module2'), - mock_module3: require(__dirname + '/fixtures/dir/mock_module3'), - mock_module4: require(__dirname + '/fixtures/dir/mock_module4') - }; - fn.call(env, test); - }; -}; - - -exports.testRunFiles = setup(function (test) { - test.expect(24); - var runModule_copy = nodeunit.runModule; - - var runModule_calls = []; - var modules = []; - - var opts = { - moduleStart: function () { - return 'moduleStart'; - }, - testDone: function () { - return 'testDone'; - }, - testStart: function () { - return 'testStart'; - }, - log: function () { - return 'log'; - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 4, 'length'); - test.ok(typeof assertions.duration === "number"); - - var called_with = function (name) { - return runModule_calls.some(function (m) { - return m.name === name; - }); - }; - test.ok(called_with('mock_module1'), 'mock_module1 ran'); - test.ok(called_with('mock_module2'), 'mock_module2 ran'); - test.ok(called_with('mock_module3'), 'mock_module3 ran'); - test.ok(called_with('mock_module4'), 'mock_module4 ran'); - test.equals(runModule_calls.length, 4); - - nodeunit.runModule = runModule_copy; - test.done(); - } - }; - - nodeunit.runModule = function (name, mod, options, callback) { - test.equals(options.testDone, opts.testDone); - test.equals(options.testStart, opts.testStart); - test.equals(options.log, opts.log); - test.ok(typeof name === "string"); - runModule_calls.push(mod); - var m = [{failed: function () { - return false; - }}]; - modules.push(m); - callback(null, m); - }; - - nodeunit.runFiles( - [__dirname + '/fixtures/mock_module1.js', - __dirname + '/fixtures/mock_module2.js', - __dirname + '/fixtures/dir'], - opts - ); -}); - -exports.testRunFilesEmpty = function (test) { - test.expect(3); - nodeunit.runFiles([], { - moduleStart: function () { - test.ok(false, 'should not be called'); - }, - testDone: function () { - test.ok(false, 'should not be called'); - }, - testStart: function () { - test.ok(false, 'should not be called'); - }, - log: function () { - test.ok(false, 'should not be called'); - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 0, 'length'); - test.ok(typeof assertions.duration === "number"); - test.done(); - } - }); -}; - - -exports.testEmptyDir = function (test) { - var dir2 = __dirname + '/fixtures/dir2'; - - // git doesn't like empty directories, so we have to create one - path.exists(dir2, function (exists) { - if (!exists) { - fs.mkdirSync(dir2, 0777); - } - - // runFiles on empty directory: - nodeunit.runFiles([dir2], { - moduleStart: function () { - test.ok(false, 'should not be called'); - }, - testDone: function () { - test.ok(false, 'should not be called'); - }, - testStart: function () { - test.ok(false, 'should not be called'); - }, - log: function () { - test.ok(false, 'should not be called'); - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 0, 'length'); - test.ok(typeof assertions.duration === "number"); - test.done(); - } - }); - }); -}; - - -var CoffeeScript; -try { - CoffeeScript = require('coffee-script'); -} catch (e) { -} - -if (CoffeeScript) { - exports.testCoffeeScript = function (test) { - process.chdir(__dirname); - var env = { - mock_coffee_module: require(__dirname + - '/fixtures/coffee/mock_coffee_module') - }; - - test.expect(9); - var runModule_copy = nodeunit.runModule; - - var runModule_calls = []; - var modules = []; - - var opts = { - moduleStart: function () { - return 'moduleStart'; - }, - testDone: function () { - return 'testDone'; - }, - testStart: function () { - return 'testStart'; - }, - log: function () { - return 'log'; - }, - done: function (assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 1, 'length'); - test.ok(typeof assertions.duration === "number"); - - var called_with = function (name) { - return runModule_calls.some(function (m) { - return m.name === name; - }); - }; - test.ok( - called_with('mock_coffee_15'), - 'mock_coffee_module ran' - ); - test.equals(runModule_calls.length, 1); - - nodeunit.runModule = runModule_copy; - test.done(); - } - }; - - nodeunit.runModule = function (name, mod, options, callback) { - test.equals(options.testDone, opts.testDone); - test.equals(options.testStart, opts.testStart); - test.equals(options.log, opts.log); - test.ok(typeof name === "string"); - runModule_calls.push(mod); - var m = [{failed: function () { - return false; - }}]; - modules.push(m); - callback(null, m); - }; - - nodeunit.runFiles( - [__dirname + 'fixtures/coffee/mock_coffee_module.coffee'], - opts - ); - }; -} diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-runmodule.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-runmodule.js deleted file mode 100644 index d07b47c..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-runmodule.js +++ /dev/null @@ -1,177 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - - -exports.testRunModule = function (test) { - test.expect(11); - var call_order = []; - var testmodule = { - test1: function (test) { - call_order.push('test1'); - test.ok(true, 'ok true'); - test.done(); - }, - test2: function (test) { - call_order.push('test2'); - test.ok(false, 'ok false'); - test.ok(false, 'ok false'); - test.done(); - }, - test3: function (test) { - call_order.push('test3'); - test.done(); - } - }; - nodeunit.runModule('testmodule', testmodule, { - log: function (assertion) { - call_order.push('log'); - }, - testStart: function (name) { - call_order.push('testStart'); - test.ok( - name.toString() === 'test1' || - name.toString() === 'test2' || - name.toString() === 'test3', - 'testStart called with test name ' - ); - }, - testDone: function (name, assertions) { - call_order.push('testDone'); - test.ok( - name.toString() === 'test1' || - name.toString() === 'test2' || - name.toString() === 'test3', - 'testDone called with test name' - ); - }, - moduleDone: function (name, assertions) { - call_order.push('moduleDone'); - test.equals(assertions.length, 3); - test.equals(assertions.failures(), 2); - test.equals(name, 'testmodule'); - test.ok(typeof assertions.duration === "number"); - test.same(call_order, [ - 'testStart', 'test1', 'log', 'testDone', - 'testStart', 'test2', 'log', 'log', 'testDone', - 'testStart', 'test3', 'testDone', - 'moduleDone' - ]); - } - }, test.done); -}; - - -exports.testRunModuleTestSpec = function (test) { - test.expect(6); - var call_order = []; - var testmodule = { - test1: function (test) { - test.ok(true, 'ok true'); - test.done(); - }, - test2: function (test) { - call_order.push('test2'); - test.ok(false, 'ok false'); - test.ok(false, 'ok false'); - test.done(); - }, - test3: function (test) { - test.done(); - } - }; - nodeunit.runModule('testmodule', testmodule, { - testspec: "test2", - log: function (assertion) { - call_order.push('log'); - }, - testStart: function (name) { - call_order.push('testStart'); - test.ok( - name.toString() === 'test2', - 'testStart called with test name ' - ); - }, - testDone: function (name, assertions) { - call_order.push('testDone'); - test.ok( - name.toString() === 'test2', - 'testDone called with test name' - ); - }, - moduleDone: function (name, assertions) { - call_order.push('moduleDone'); - test.equals(assertions.length, 2); - test.equals(name, 'testmodule'); - test.ok(typeof assertions.duration === "number"); - test.same(call_order, [ - 'testStart', 'test2', 'log', 'log', 'testDone', - 'moduleDone' - ]); - } - }, test.done); -}; - -exports.testRunModuleEmpty = function (test) { - nodeunit.runModule('module with no exports', {}, { - log: function (assertion) { - test.ok(false, 'log should not be called'); - }, - testStart: function (name) { - test.ok(false, 'testStart should not be called'); - }, - testDone: function (name, assertions) { - test.ok(false, 'testDone should not be called'); - }, - moduleDone: function (name, assertions) { - test.equals(assertions.length, 0); - test.equals(assertions.failures(), 0); - test.equals(name, 'module with no exports'); - test.ok(typeof assertions.duration === "number"); - } - }, test.done); -}; - - -exports.testNestedTests = function (test) { - var call_order = []; - var m = { - test1: function (test) { - test.done(); - }, - suite: { - t1: function (test) { - test.done(); - }, - t2: function (test) { - test.done(); - }, - another_suite: { - t3: function (test) { - test.done(); - } - } - } - }; - nodeunit.runModule('modulename', m, { - testStart: function (name) { - call_order.push(['testStart'].concat(name)); - }, - testDone: function (name, assertions) { - call_order.push(['testDone'].concat(name)); - } - }, function () { - test.same(call_order, [ - ['testStart', 'test1'], ['testDone', 'test1'], - ['testStart', 'suite', 't1'], ['testDone', 'suite', 't1'], - ['testStart', 'suite', 't2'], ['testDone', 'suite', 't2'], - ['testStart', 'suite', 'another_suite', 't3'], - ['testDone', 'suite', 'another_suite', 't3'] - ]); - test.done(); - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-runtest.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-runtest.js deleted file mode 100644 index 8fc3d52..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-runtest.js +++ /dev/null @@ -1,46 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - - -exports.testArgs = function (test) { - test.ok(test.expect instanceof Function, 'test.expect'); - test.ok(test.done instanceof Function, 'test.done'); - test.ok(test.ok instanceof Function, 'test.ok'); - test.ok(test.same instanceof Function, 'test.same'); - test.ok(test.equals instanceof Function, 'test.equals'); - test.done(); -}; - -exports.testDoneCallback = function (test) { - test.expect(4); - nodeunit.runTest('testname', exports.testArgs, { - testDone: function (name, assertions) { - test.equals(assertions.failures(), 0, 'failures'); - test.equals(assertions.length, 5, 'length'); - test.ok(typeof assertions.duration === "number"); - test.equals(name, 'testname'); - } - }, test.done); -}; - -exports.testThrowError = function (test) { - test.expect(3); - var err = new Error('test'); - var testfn = function (test) { - throw err; - }; - nodeunit.runTest('testname', testfn, { - log: function (assertion) { - test.same(assertion.error, err, 'assertion.error'); - }, - testDone: function (name, assertions) { - test.equals(assertions.failures(), 1); - test.equals(assertions.length, 1); - } - }, test.done); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-sandbox.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-sandbox.js deleted file mode 100644 index 1b249d7..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-sandbox.js +++ /dev/null @@ -1,31 +0,0 @@ -var nodeunit = require('../lib/nodeunit'); -var sandbox = require('../lib/utils').sandbox; -var testCase = nodeunit.testCase; - -exports.testSimpleSandbox = function (test) { - var raw_jscode1 = sandbox(__dirname + '/fixtures/raw_jscode1.js'); - test.equal(raw_jscode1.hello_world('foo'), '_foo_', 'evaluation ok'); - test.done(); -}; - -exports.testSandboxContext = function (test) { - var a_variable = 42; // should not be visible in the sandbox - var raw_jscode2 = sandbox(__dirname + '/fixtures/raw_jscode2.js'); - a_variable = 42; // again for the win - test.equal( - raw_jscode2.get_a_variable(), - 'undefined', - 'the variable should not be defined' - ); - test.done(); -}; - -exports.testSandboxMultiple = function (test) { - var raw_jscode3 = sandbox([ - __dirname + '/fixtures/raw_jscode3.js', - __dirname + '/fixtures/raw_jscode3.js', - __dirname + '/fixtures/raw_jscode3.js' - ]); - test.equal(raw_jscode3.t, 3, 'two files loaded'); - test.done(); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-testcase-legacy.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-testcase-legacy.js deleted file mode 100644 index 1dfd9a7..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-testcase-legacy.js +++ /dev/null @@ -1,257 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER -var testCase = nodeunit.testCase; - -exports.testTestCase = function (test) { - test.expect(7); - var call_order = []; - var s = testCase({ - setUp: function (callback) { - call_order.push('setUp'); - test.equals(this.one, undefined); - this.one = 1; - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - test.ok(true, 'tearDown called'); - callback(); - }, - test1: function (t) { - call_order.push('test1'); - test.equals(this.one, 1); - this.one = 2; - t.done(); - }, - test2: function (t) { - call_order.push('test2'); - test.equals(this.one, 1); - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function () { - test.same(call_order, [ - 'setUp', 'test1', 'tearDown', - 'setUp', 'test2', 'tearDown' - ]); - test.done(); - }); -}; - -exports.tearDownAfterError = function (test) { - test.expect(1); - var s = testCase({ - tearDown: function (callback) { - test.ok(true, 'tearDown called'); - callback(); - }, - test: function (t) { - throw new Error('some error'); - } - }); - nodeunit.runSuite(null, s, {}, function () { - test.done(); - }); -}; - -exports.catchSetUpError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - setUp: function (callback) { - throw test_error; - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.setUpErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - setUp: function (callback) { - callback(test_error); - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.catchTearDownError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - tearDown: function (callback) { - throw test_error; - }, - test: function (t) { - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.tearDownErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = testCase({ - tearDown: function (callback) { - callback(test_error); - }, - test: function (t) { - t.done(); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.testErrorAndtearDownError = function (test) { - test.expect(3); - var error1 = new Error('test error one'); - var error2 = new Error('test error two'); - var s = testCase({ - tearDown: function (callback) { - callback(error2); - }, - test: function (t) { - t.done(error1); - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 2); - test.equal(assertions[0].error, error1); - test.equal(assertions[1].error, error2); - test.done(); - }); -}; - -exports.testCaseGroups = function (test) { - var call_order = []; - var s = testCase({ - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: { - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - } - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.test2', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.nestedTestCases = function (test) { - var call_order = []; - var s = testCase({ - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: testCase({ - setUp: function (callback) { - call_order.push('group1.setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('group1.tearDown'); - callback(); - }, - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - }) - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.setUp', - 'group1.test2', - 'group1.tearDown', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.deepNestedTestCases = function (test) { - var val = 'foo'; - var s = testCase({ - setUp: function (callback) { - val = 'bar'; - callback(); - }, - group1: testCase({ - test: testCase({ - test2: function (test) { - test.equal(val, 'bar'); - test.done(); - } - }) - }) - }); - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.ok(!assertions[0].failed()); - test.equal(assertions.length, 1); - test.done(); - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-testcase.js b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-testcase.js deleted file mode 100644 index 5d33b0b..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test-testcase.js +++ /dev/null @@ -1,256 +0,0 @@ -/* THIS FILE SHOULD BE BROWSER-COMPATIBLE JS! - * You can use @REMOVE_LINE_FOR_BROWSER to remove code from the browser build. - * Only code on that line will be removed, its mostly to avoid requiring code - * that is node specific - */ - -var nodeunit = require('../lib/nodeunit'); // @REMOVE_LINE_FOR_BROWSER - -exports.testTestCase = function (test) { - test.expect(7); - var call_order = []; - var s = { - setUp: function (callback) { - call_order.push('setUp'); - test.equals(this.one, undefined, 'in setUp, this.one not set'); - this.one = 1; - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - test.ok(true, 'tearDown called'); - callback(); - }, - test1: function (t) { - call_order.push('test1'); - test.equals(this.one, 1, 'in test1, this.one is 1'); - this.one = 2; - t.done(); - }, - test2: function (t) { - call_order.push('test2'); - test.equals(this.one, 1, 'in test2, this.one is still 1'); - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function () { - test.same(call_order, [ - 'setUp', 'test1', 'tearDown', - 'setUp', 'test2', 'tearDown' - ]); - test.done(); - }); -}; - -exports.tearDownAfterError = function (test) { - test.expect(1); - var s = { - tearDown: function (callback) { - test.ok(true, 'tearDown called'); - callback(); - }, - test: function (t) { - throw new Error('some error'); - } - }; - nodeunit.runSuite(null, s, {}, function () { - test.done(); - }); -}; - -exports.catchSetUpError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - setUp: function (callback) { - throw test_error; - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.setUpErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - setUp: function (callback) { - callback(test_error); - }, - test: function (t) { - test.ok(false, 'test function should not be called'); - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.catchTearDownError = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - tearDown: function (callback) { - throw test_error; - }, - test: function (t) { - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.tearDownErrorCallback = function (test) { - test.expect(2); - var test_error = new Error('test error'); - var s = { - tearDown: function (callback) { - callback(test_error); - }, - test: function (t) { - t.done(); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 1); - test.equal(assertions[0].error, test_error); - test.done(); - }); -}; - -exports.testErrorAndtearDownError = function (test) { - test.expect(3); - var error1 = new Error('test error one'); - var error2 = new Error('test error two'); - var s = { - tearDown: function (callback) { - callback(error2); - }, - test: function (t) { - t.done(error1); - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.equal(assertions.length, 2); - test.equal(assertions[0].error, error1); - test.equal(assertions[1].error, error2); - test.done(); - }); -}; - -exports.testCaseGroups = function (test) { - var call_order = []; - var s = { - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: { - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.test2', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.nestedTestCases = function (test) { - var call_order = []; - var s = { - setUp: function (callback) { - call_order.push('setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('tearDown'); - callback(); - }, - test1: function (test) { - call_order.push('test1'); - test.done(); - }, - group1: { - setUp: function (callback) { - call_order.push('group1.setUp'); - callback(); - }, - tearDown: function (callback) { - call_order.push('group1.tearDown'); - callback(); - }, - test2: function (test) { - call_order.push('group1.test2'); - test.done(); - } - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.same(call_order, [ - 'setUp', - 'test1', - 'tearDown', - 'setUp', - 'group1.setUp', - 'group1.test2', - 'group1.tearDown', - 'tearDown' - ]); - test.done(); - }); -}; - -exports.deepNestedTestCases = function (test) { - var val = 'foo'; - var s = { - setUp: function (callback) { - val = 'bar'; - callback(); - }, - group1: { - test: { - test2: function (test) { - test.equal(val, 'bar'); - test.done(); - } - } - } - }; - nodeunit.runSuite(null, s, {}, function (err, assertions) { - test.ok(!assertions[0].failed()); - test.equal(assertions.length, 1); - test.done(); - }); -}; diff --git a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test.html b/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test.html deleted file mode 100644 index e0826de..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/nodeunit/test/test.html +++ /dev/null @@ -1,28 +0,0 @@ - - - Nodeunit Test Suite - - - - - - - - - - -

Nodeunit Test Suite

- - - diff --git a/node_modules/reg/node_modules/mongodb/deps/step/README.markdown b/node_modules/reg/node_modules/mongodb/deps/step/README.markdown deleted file mode 100644 index abf1f2b..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/step/README.markdown +++ /dev/null @@ -1,71 +0,0 @@ -# Step - -A simple control-flow library for node.JS that makes parallel execution, serial execution, and error handling painless. - -## How to install - -Simply copy or link the lib/step.js file into your `$HOME/.node_libraries` folder. - -## How to use - -The step library exports a single function I call `Step`. It accepts any number of functions as arguments and runs them in serial order using the passed in `this` context as the callback to the next step. - - Step( - function readSelf() { - fs.readFile(__filename, this); - }, - function capitalize(err, text) { - if (err) throw err; - return text.toUpperCase(); - }, - function showIt(err, newText) { - if (err) throw err; - console.log(newText); - } - ); - -Notice that we pass in `this` as the callback to `fs.readFile`. When the file read completes, step will send the result as the arguments to the next function in the chain. Then in the `capitalize` function we're doing synchronous work so we can simple return the new value and Step will route it as if we called the callback. - -The first parameter is reserved for errors since this is the node standard. Also any exceptions thrown are caught and passed as the first argument to the next function. As long as you don't nest callback functions inline your main functions this prevents there from ever being any uncaught exceptions. This is very important for long running node.JS servers since a single uncaught exception can bring the whole server down. - -Also there is support for parallel actions: - - Step( - // Loads two files in parallel - function loadStuff() { - fs.readFile(__filename, this.parallel()); - fs.readFile("/etc/passwd", this.parallel()); - }, - // Show the result when done - function showStuff(err, code, users) { - if (err) throw err; - sys.puts(code); - sys.puts(users); - } - ) - -Here we pass `this.parallel()` instead of `this` as the callback. It internally keeps track of the number of callbacks issued and preserves their order then giving the result to the next step after all have finished. If there is an error in any of the parallel actions, it will be passed as the first argument to the next step. - -Also you can use group with a dynamic number of common tasks. - - Step( - function readDir() { - fs.readdir(__dirname, this); - }, - function readFiles(err, results) { - if (err) throw err; - // Create a new group - var group = this.group(); - results.forEach(function (filename) { - if (/\.js$/.test(filename)) { - fs.readFile(__dirname + "/" + filename, 'utf8', group()); - } - }); - }, - function showAll(err , files) { - if (err) throw err; - sys.p(files); - } - ); - -*Note* that we both call `this.group()` and `group()`. The first reserves a slot in the parameters of the next step, then calling `group()` generates the individual callbacks and increments the internal counter. diff --git a/node_modules/reg/node_modules/mongodb/deps/step/lib/step.js b/node_modules/reg/node_modules/mongodb/deps/step/lib/step.js deleted file mode 100644 index 546c14d..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/step/lib/step.js +++ /dev/null @@ -1,154 +0,0 @@ -/* -Copyright (c) 2011 Tim Caswell - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ - -// Inspired by http://github.com/willconant/flow-js, but reimplemented and -// modified to fit my taste and the node.JS error handling system. -function Step() { - var steps = Array.prototype.slice.call(arguments), - pending, counter, results, lock; - - // Define the main callback that's given as `this` to the steps. - function next() { - - // Check if there are no steps left - if (steps.length === 0) { - // Throw uncaught errors - if (arguments[0]) { - throw arguments[0]; - } - return; - } - - // Get the next step to execute - var fn = steps.shift(); - counter = pending = 0; - results = []; - - // Run the step in a try..catch block so exceptions don't get out of hand. - try { - lock = true; - var result = fn.apply(next, arguments); - } catch (e) { - // Pass any exceptions on through the next callback - next(e); - } - - - // If a syncronous return is used, pass it to the callback - if (result !== undefined) { - next(undefined, result); - } - lock = false; - } - - // Add a special callback generator `this.parallel()` that groups stuff. - next.parallel = function () { - var index = 1 + counter++; - pending++; - - function check() { - if (pending === 0) { - // When they're all done, call the callback - next.apply(null, results); - } - } - process.nextTick(check); // Ensures that check is called at least once - - return function () { - pending--; - // Compress the error from any result to the first argument - if (arguments[0]) { - results[0] = arguments[0]; - } - // Send the other results as arguments - results[index] = arguments[1]; - if (!lock) { check(); } - }; - }; - - // Generates a callback generator for grouped results - next.group = function () { - var localCallback = next.parallel(); - var counter = 0; - var pending = 0; - var result = []; - var error = undefined; - - function check() { - if (pending === 0) { - // When group is done, call the callback - localCallback(error, result); - } - } - process.nextTick(check); // Ensures that check is called at least once - - // Generates a callback for the group - return function () { - var index = counter++; - pending++; - return function () { - pending--; - // Compress the error from any result to the first argument - if (arguments[0]) { - error = arguments[0]; - } - // Send the other results as arguments - result[index] = arguments[1]; - if (!lock) { check(); } - }; - }; - }; - - // Start the engine an pass nothing to the first step. - next(); -} - -// Tack on leading and tailing steps for input and output and return -// the whole thing as a function. Basically turns step calls into function -// factories. -Step.fn = function StepFn() { - var steps = Array.prototype.slice.call(arguments); - return function () { - var args = Array.prototype.slice.call(arguments); - - // Insert a first step that primes the data stream - var toRun = [function () { - this.apply(null, args); - }].concat(steps); - - // If the last arg is a function add it as a last step - if (typeof args[args.length-1] === 'function') { - toRun.push(args.pop()); - } - - - Step.apply(null, toRun); - } -} - - -// Hook into commonJS module systems -if (typeof module !== 'undefined' && "exports" in module) { - module.exports = Step; -} diff --git a/node_modules/reg/node_modules/mongodb/deps/step/package.json b/node_modules/reg/node_modules/mongodb/deps/step/package.json deleted file mode 100644 index 062ace0..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/step/package.json +++ /dev/null @@ -1,11 +0,0 @@ -{ "name": "step", - "version": "0.0.4", - "description": "A simple control-flow library for node.JS that makes parallel execution, serial execution, and error handling painless.", - "engine": [ "node >=0.2.0" ], - "author": "Tim Caswell ", - "repository": - { "type" : "git", - "url" : "http://github.com/creationix/step.git" - }, - "main": "lib/step" -} diff --git a/node_modules/reg/node_modules/mongodb/deps/step/test/callbackTest.js b/node_modules/reg/node_modules/mongodb/deps/step/test/callbackTest.js deleted file mode 100644 index 2fc2351..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/step/test/callbackTest.js +++ /dev/null @@ -1,26 +0,0 @@ -require('./helper'); - -var selfText = fs.readFileSync(__filename, 'utf8'); - -// This example tests passing async results and sync results to the next layer - -expect('one'); -expect('two'); -expect('three'); -Step( - function readSelf() { - fulfill("one"); - fs.readFile(__filename, 'utf8', this); - }, - function capitalize(err, text) { - fulfill("two"); - if (err) throw err; - assert.equal(selfText, text, "Text Loaded"); - return text.toUpperCase(); - }, - function showIt(err, newText) { - fulfill("three"); - if (err) throw err; - assert.equal(selfText.toUpperCase(), newText, "Text Uppercased"); - } -); diff --git a/node_modules/reg/node_modules/mongodb/deps/step/test/errorTest.js b/node_modules/reg/node_modules/mongodb/deps/step/test/errorTest.js deleted file mode 100644 index 30af683..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/step/test/errorTest.js +++ /dev/null @@ -1,27 +0,0 @@ -require('./helper'); - -var exception = new Error('Catch me!'); - -expect('one'); -expect('timeout'); -expect('two'); -expect('three'); -Step( - function () { - fulfill('one'); - var callback = this; - setTimeout(function () { - fulfill('timeout'); - callback(exception); - }, 0); - }, - function (err) { - fulfill('two'); - assert.equal(exception, err, "error should passed through"); - throw exception; - }, - function (err) { - fulfill('three'); - assert.equal(exception, err, "error should be caught"); - } -); diff --git a/node_modules/reg/node_modules/mongodb/deps/step/test/fnTest.js b/node_modules/reg/node_modules/mongodb/deps/step/test/fnTest.js deleted file mode 100644 index 1964a35..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/step/test/fnTest.js +++ /dev/null @@ -1,21 +0,0 @@ -require('./helper'); - - -var myfn = Step.fn( - function (name) { - fs.readFile(name, 'utf8', this); - }, - function capitalize(err, text) { - if (err) throw err; - return text.toUpperCase(); - } -); - -var selfText = fs.readFileSync(__filename, 'utf8'); - -expect('result'); -myfn(__filename, function (err, result) { - fulfill('result'); - if (err) throw err; - assert.equal(selfText.toUpperCase(), result, "It should work"); -}); diff --git a/node_modules/reg/node_modules/mongodb/deps/step/test/groupTest.js b/node_modules/reg/node_modules/mongodb/deps/step/test/groupTest.js deleted file mode 100644 index c1124ab..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/step/test/groupTest.js +++ /dev/null @@ -1,102 +0,0 @@ -require('./helper'); - -var dirListing = fs.readdirSync(__dirname), - dirResults = dirListing.map(function (filename) { - return fs.readFileSync(__dirname + "/" + filename, 'utf8'); - }); - -expect('one'); -expect('two'); -expect('three'); -Step( - function readDir() { - fulfill('one'); - fs.readdir(__dirname, this); - }, - function readFiles(err, results) { - fulfill('two'); - if (err) throw err; - // Create a new group - assert.deepEqual(dirListing, results); - var group = this.group(); - results.forEach(function (filename) { - if (/\.js$/.test(filename)) { - fs.readFile(__dirname + "/" + filename, 'utf8', group()); - } - }); - }, - function showAll(err , files) { - fulfill('three'); - if (err) throw err; - assert.deepEqual(dirResults, files); - } -); - -expect('four'); -expect('five'); -// When the group is empty, it should fire with an empty array -Step( - function start() { - var group = this.group(); - fulfill('four'); - }, - function readFiles(err, results) { - if (err) throw err; - fulfill('five'); - assert.deepEqual(results, []); - } -); - -// Test lock functionality with N sized groups -expect("test3: 1"); -expect("test3: 1,2,3"); -expect("test3: 2"); -Step( - function() { - return 1; - }, - function makeGroup(err, num) { - if(err) throw err; - fulfill("test3: " + num); - var group = this.group(); - - setTimeout((function(callback) { return function() { callback(null, 1); } })(group()), 100); - group()(null, 2); - setTimeout((function(callback) { return function() { callback(null, 3); } })(group()), 0); - }, - function groupResults(err, results) { - if(err) throw err; - fulfill("test3: " + results); - return 2 - }, - function terminate(err, num) { - if(err) throw err; - fulfill("test3: " + num); - } -); - -// Test lock functionality with zero sized groups -expect("test4: 1"); -expect("test4: empty array"); -expect("test4: group of zero terminated"); -expect("test4: 2"); -Step( - function() { - return 1; - }, - function makeGroup(err, num) { - if(err) throw err; - fulfill("test4: " + num); - this.group(); - }, - function groupResults(err, results) { - if(err) throw err; - if(results.length === 0) { fulfill("test4: empty array"); } - fulfill('test4: group of zero terminated'); - return 2 - }, - function terminate(err, num) { - if(err) throw err; - fulfill("test4: " + num); - } -); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/deps/step/test/helper.js b/node_modules/reg/node_modules/mongodb/deps/step/test/helper.js deleted file mode 100644 index bd4ca8e..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/step/test/helper.js +++ /dev/null @@ -1,17 +0,0 @@ -global.assert = require('assert'); -global.fs = require('fs'); -global.Step = require('../lib/step'); - -// A mini expectations module to ensure expected callback fire at all. -var expectations = {}; -global.expect = function expect(message) { - expectations[message] = new Error("Missing expectation: " + message); -} -global.fulfill = function fulfill(message) { - delete expectations[message]; -} -process.addListener('exit', function () { - Object.keys(expectations).forEach(function (message) { - throw expectations[message]; - }); -}); diff --git a/node_modules/reg/node_modules/mongodb/deps/step/test/parallelTest.js b/node_modules/reg/node_modules/mongodb/deps/step/test/parallelTest.js deleted file mode 100644 index baba74e..0000000 --- a/node_modules/reg/node_modules/mongodb/deps/step/test/parallelTest.js +++ /dev/null @@ -1,49 +0,0 @@ -require('./helper'); - -var selfText = fs.readFileSync(__filename, 'utf8'), - etcText = fs.readFileSync('/etc/passwd', 'utf8'); - -expect('one'); -expect('two'); -Step( - // Loads two files in parallel - function loadStuff() { - fulfill('one'); - fs.readFile(__filename, this.parallel()); - fs.readFile("/etc/passwd", this.parallel()); - }, - // Show the result when done - function showStuff(err, code, users) { - fulfill('two'); - if (err) throw err; - assert.equal(selfText, code, "Code should come first"); - assert.equal(etcText, users, "Users should come second"); - } -); - -// Test lock functionality with N parallel calls -expect("test2: 1"); -expect("test2: 1,2,3"); -expect("test2: 2"); -Step( - function() { - return 1; - }, - function makeParallelCalls(err, num) { - if(err) throw err; - fulfill("test2: " + num); - - setTimeout((function(callback) { return function() { callback(null, 1); } })(this.parallel()), 100); - this.parallel()(null, 2); - setTimeout((function(callback) { return function() { callback(null, 3); } })(this.parallel()), 0); - }, - function parallelResults(err, one, two, three) { - if(err) throw err; - fulfill("test2: " + [one, two, three]); - return 2 - }, - function terminate(err, num) { - if(err) throw err; - fulfill("test2: " + num); - } -) \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/dev/benchmark/bson_benchmark.js b/node_modules/reg/node_modules/mongodb/dev/benchmark/bson_benchmark.js deleted file mode 100644 index 884f9ea..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/benchmark/bson_benchmark.js +++ /dev/null @@ -1,86 +0,0 @@ -var BSON = require('../lib/mongodb').BSONNative.BSON, - ObjectID = require('../lib/mongodb').BSONNative.ObjectID, - Code = require('../lib/mongodb').BSONNative.Code, - Long = require('../lib/mongodb').BSONNative.Long, - Binary = require('../lib/mongodb').BSONNative.Binary, - debug = require('util').debug, - inspect = require('util').inspect; - -// var BSON = require('../lib/mongodb').BSONPure.BSON, -// ObjectID = require('../lib/mongodb').BSONPure.ObjectID, -// Code = require('../lib/mongodb').BSONPure.Code, -// Long = require('../lib/mongodb').BSONPure.Long, -// Binary = require('../lib/mongodb').BSONPure.Binary; - -var COUNT = 1000; -var COUNT = 100; - -var object = { - string: "Strings are great", - decimal: 3.14159265, - bool: true, - integer: 5, - long: Long.fromNumber(100), - bin: new Binary(), - - subObject: { - moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", - longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin." - }, - - subArray: [1,2,3,4,5,6,7,8,9,10], - anotherString: "another string", - code: new Code("function() {}", {i:1}) -} - -// Number of objects -var numberOfObjects = 100; -// var numberOfObjects = 2; - -// Object serialized -objectBSON = BSON.serialize(object, null, true) - -// Buffer With copies of the objectBSON -var data = new Buffer(objectBSON.length * numberOfObjects); -var index = 0; - -// Copy the buffer 1000 times to create a strea m of objects -for(var i = 0; i < numberOfObjects; i++) { - // Copy data - objectBSON.copy(data, index); - // Adjust index - index = index + objectBSON.length; -} - -// console.log("-----------------------------------------------------------------------------------") -// console.dir(objectBSON) - -var x, start, end, j -var objectBSON, objectJSON - -// Allocate the return array (avoid concatinating everything) -var results = new Array(numberOfObjects); - -console.log(COUNT + "x (objectBSON = BSON.serialize(object))") -start = new Date - -// var objects = BSON.deserializeStream(data, 0, numberOfObjects); -// console.log("----------------------------------------------------------------------------------- 0") -// var objects = BSON.deserialize(data); -// console.log("----------------------------------------------------------------------------------- 1") -// console.dir(objects) - -for (j=COUNT; --j>=0; ) { - var nextIndex = BSON.deserializeStream(data, 0, numberOfObjects, results, 0); -} - -end = new Date -var opsprsecond = COUNT / ((end - start)/1000); -console.log("bson size (bytes): ", objectBSON.length); -console.log("time = ", end - start, "ms -", COUNT / ((end - start)/1000), " ops/sec"); -console.log("MB/s = " + ((opsprsecond*objectBSON.length)/1024)); - -// console.dir(nextIndex) -// console.dir(results) - - diff --git a/node_modules/reg/node_modules/mongodb/dev/benchmark/bson_buffalo_benchmark.js b/node_modules/reg/node_modules/mongodb/dev/benchmark/bson_buffalo_benchmark.js deleted file mode 100644 index 43848b2..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/benchmark/bson_buffalo_benchmark.js +++ /dev/null @@ -1,299 +0,0 @@ -var BSON = require('/Users/christiankvalheim/coding/checkout/node-buffalo/buffalo') -var mongoNative = require('../lib/mongodb'), - assert = require('assert'), - Long = require('../lib/mongodb/bson/long').Long, - ObjectID = require('../lib/mongodb/bson/bson').ObjectID, - Binary = require('../lib/mongodb/bson/bson').Binary, - Code = require('../lib/mongodb/bson/bson').Code, - DBRef = require('../lib/mongodb/bson/bson').DBRef, - Symbol = require('../lib/mongodb/bson/bson').Symbol, - Double = require('../lib/mongodb/bson/bson').Double, - MaxKey = require('../lib/mongodb/bson/bson').MaxKey, - MinKey = require('../lib/mongodb/bson/bson').MinKey, - Timestamp = require('../lib/mongodb/bson/bson').Timestamp; - -var BSONPure = new mongoNative.BSONPure.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]); -var BSONNative = new mongoNative.BSONNative.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]); - -var COUNT = 100000 -// var COUNT = 20000 -// var COUNT = 10000 -// var COUNT = 1 - -// Function with scope -var function2 = function() {}; -function2.scope = {a:1}; - -// var COUNT = 1 -var object = { - string: "Strings are great", - decimal: 3.14159265, - 'undefined': undefined, - bool: true, - integer: 5, - regexp:/fdfdfd/, - // regexp:/fdfdfd/mig, - subObject: { - moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", - longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin.", - - subObject: { - moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", - longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin.", - }, - }, - date: new Date(), - code: function() {}, - function2: function2, - buffer:new Buffer('hello world'), - 'null': null, - subArray: [1,2,3,4,5,6,7,8,9,10], - anotherString: "another string" -} - -// var object2 = { -// string: "Strings are great", -// obj: { -// string2: "This is String 2", -// }, -// -// decimal: 3.14159265, -// 'undefined': undefined, -// bool: true, -// integer: 5, -// regexp:/fdfdfd/mig, -// regexp:/fdfdfd/, -// subObject: { -// moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", -// longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin.", -// -// subObject: { -// moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", -// longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin." -// } -// }, -// dbref: new DBRef('collection', new ObjectID(), 'db'), -// long: Long.fromNumber(1000), -// double: new Double(3.14), -// code1: new Code((function() {}).toString(), {a:1}), -// code: new Code((function() {}).toString()), -// minKey: new MinKey(), -// maxKey: new MaxKey(), -// objectId: new ObjectID(), -// binary: new Binary('hello world'), -// symbol: new Symbol('hello'), -// timestamp: Timestamp.fromNumber(1000), -// date: new Date(), -// function1: function() {}, -// function2: function2, -// buffer:new Buffer('hello world'), -// 'null': null, -// subArray: [1,2,3,4,5,6,7,8,9,10], -// anotherString: "another string" -// } -// -// var object2 = { -// cursorId: Long.fromString("3688496768165567218"), -// } - -// Serialize the object -var serializedDoc = BSONPure.serialize(object, null, true); - -// Read a test doc -// var bufferData = require('fs').readFileSync("/Users/christiankvalheim/coding/projects/node-mongodb-native/1325633340440_18.txt", 'ascii'); -// Serialized doc -// var serializedDoc = new Buffer(bufferData, 'hex'); - -// console.dir(serializedDoc) -// var index = 0; -// var binary_reply = serializedDoc; -// -// console.log("---------------------------------------------------------") -// while(index < serializedDoc.length) { -// // Read the size of the bson object -// var bsonObjectSize = binary_reply[index] | binary_reply[index + 1] << 8 | binary_reply[index + 2] << 16 | binary_reply[index + 3] << 24; -// // var d_doc = BSONNative.deserialize(binary_reply.slice(index, index + bsonObjectSize)); -// var d_doc = BSONPure.deserialize(binary_reply.slice(index, index + bsonObjectSize)); -// console.dir(d_doc); -// index = index + bsonObjectSize; -// } -// -// Deserialize the object -// var d_doc = BSONPure.deserialize2(serializedDoc, {evalFunctions:true, cacheFunctions:true}); -// var d_doc = BSONPure.deserialize(serializedDoc); -// var d_doc = BSONNative.deserialize(serializedDoc); -// -// console.log("---------------------------------------------------------") -// console.dir(d_doc); -// return - -// Warm up the method -for(var i = 0 ; i < COUNT; i++) { - BSONPure.deserialize(serializedDoc); - BSON.parse(serializedDoc); - BSONNative.deserialize(serializedDoc); -} - -// var object2 = { authenticate: 1, -// user: 'admin', -// nonce: '2e8e9e9533db3dae', -// key: 'e75fea840d9f52bab39903b011898b8f' } -// -// var object2 = {'name' : 'child', 'parent' : new DBRef("test_resave_dbref", new ObjectID())} -// -// var object2 = {'doc': {'doc2': new Code('this.a > i', {i:1})}}; -// // var object2 = {'doc2': new Code('this.a > i', {i:1})}; -// var object2 = {'doc': {'doc2': new Code('this.a > i', {})}}; -// -// var object3 = { -// // function2: new Code((function() {}).toString(), {a:1}), -// // function1: new Code((function() {}).toString()), -// } - -// // object2 = object; -// var x, start, end, i -// var serializedBSON, serializedBSONPure, serializedBSONNative, serializedJSON -// var deserializedBSON, deserializedBSONPure, deserializedBSONNative, deserializedJSON -// -// for (i=COUNT; --i>=0; ) { -// calculate1 = BSON.calculate(object) -// // calculate2 = BSONPure.calculateObjectSize(object2, true) -// calculate3 = BSONPure.calculateObjectSize2(object2, true) -// calculate4 = BSONNative.calculateObjectSize(object2) -// } -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// calculate1 = BSON.calculate(object) -// } -// end = new Date -// console.log(COUNT + "x buffalo.calculate(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// calculate2 = BSONPure.calculateObjectSize2(object, true) -// } -// end = new Date -// console.log(COUNT + "x BSONPure.calculateObjectSize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// calculate3 = BSONPure.calculateObjectSize2(object2) -// } -// end = new Date -// console.log(COUNT + "x BSONPure.calculateObjectSize2(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// -// console.log("==================================================================") -// console.dir("BSON.calculate :: " + calculate1) -// // console.dir("BSONPure.calculateObjectSize :: " + calculate2) -// console.dir("BSONPure.calculateObjectSize2 :: " + calculate3) -// console.dir("BSONNative.calculateObjectSize :: " + calculate4) - -// console.log("========================================================== serialize") -// console.log("BSON.serialize :: ") -// console.dir(BSON.serialize(object).toString('hex')) -// console.log("BSONPure.serialize2 :: ") -// console.dir(BSONPure.serialize2(object2, null, true).toString('hex')) -// console.dir(BSONPure.serialize2(object2, null, true).toString('ascii')) -// console.log("BSONPure.serialize :: ") -// console.dir(BSONPure.serialize(object, null, true).toString('hex')) -// console.log("BSONNative.serialize :: ") -// console.dir(BSONNative.serialize(object2, null, true).toString('hex')) -// console.dir(BSONNative.serialize(object2, null, true).toString('ascii')) - -// // Serialize -// var a = BSONPure.serialize(object2, null, true); -// var b = BSONNative.serialize(object2, null, true); -// -// console.log("==================================== check") -// for(var i = 0; i < b.length; i++) { -// console.log("[" + a[i] + "] = [" + b[i] + "] :: " + (a[i] === b[i] ? 'true' : "FALSE FALSE FALSE")); -// } -// -// assert.equal(BSONNative.serialize(object2, null, true).toString('hex'), -// BSONPure.serialize2(object2, null, true).toString('hex')) -// -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// serializedBSON = BSON.serialize(object) -// } -// end = new Date -// console.log(COUNT + "x buffalo.serialize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// serializedBSONPure = BSONPure.serialize2(object, null, true) -// } -// end = new Date -// console.log(COUNT + "x mongodb.BSONPure.serialize2(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -// start = new Date -// for (i=COUNT; --i>=0; ) { -// serializedBSONPure = BSONPure.serialize(object, null, true) -// } -// end = new Date -// console.log(COUNT + "x mongodb.BSONPure.serialize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// if (BSONNative) { -// start = new Date -// for (i=COUNT; --i>=0; ) { -// serializedBSONNative = BSONNative.serialize(object, null, true) -// } -// end = new Date -// console.log(COUNT + "x mongodb.BSONNative.serialize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// } -// -// start = new Date -// for (i=COUNT; --i>=0; ) { -// serializedJSON = JSON.stringify(object) -// } -// end = new Date -// console.log(COUNT + "x JSON.stringify(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -// start = new Date -// for (i=COUNT; --i>=0; ) { -// deserializedBSONPure = BSONPure.deserialize2(serializedDoc) -// } -// end = new Date -// console.log(COUNT + "x mongodb.BSONPure.deserialize2(buffer) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -start = new Date -for (i=COUNT; --i>=0; ) { - deserializedBSON = BSON.parse(serializedDoc) -} -end = new Date -console.log(COUNT + "x buffalo.parse(buffer) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -if (BSONNative) { - start = new Date - for (i=COUNT; --i>=0; ) { - deserializedBSONNative = BSONNative.deserialize(serializedDoc) - } - end = new Date - console.log(COUNT + "x mongodb.BSONNative.deserialize(buffer) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -} - -start = new Date -for (i=COUNT; --i>=0; ) { - deserializedBSONPure = BSONPure.deserialize(serializedDoc) -} -end = new Date -console.log(COUNT + "x mongodb.BSONPure.deserialize(buffer) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -console.log("---------------------------------------------------------") -console.dir(deserializedBSON) -console.dir(deserializedBSONNative) -console.dir(deserializedBSONPure) - -function compare(b1, b2) { - try { - require('assert').deepEqual(b1,b2) - return true - } catch (e) { - console.error(e) - return false - } -} diff --git a/node_modules/reg/node_modules/mongodb/dev/benchmark/bson_native_benchmark.js b/node_modules/reg/node_modules/mongodb/dev/benchmark/bson_native_benchmark.js deleted file mode 100644 index 09d6afd..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/benchmark/bson_native_benchmark.js +++ /dev/null @@ -1,112 +0,0 @@ -var BSON = require('/Users/christiankvalheim/coding/checkout/node-buffalo/buffalo') -var mongoNative = require('../lib/mongodb'), - assert = require('assert'), - Long = require('../lib/mongodb/bson/long').Long, - ObjectID = require('../lib/mongodb/bson/bson').ObjectID, - Binary = require('../lib/mongodb/bson/bson').Binary, - Code = require('../lib/mongodb/bson/bson').Code, - DBRef = require('../lib/mongodb/bson/bson').DBRef, - Symbol = require('../lib/mongodb/bson/bson').Symbol, - Double = require('../lib/mongodb/bson/bson').Double, - MaxKey = require('../lib/mongodb/bson/bson').MaxKey, - MinKey = require('../lib/mongodb/bson/bson').MinKey, - Timestamp = require('../lib/mongodb/bson/bson').Timestamp; - -var BSONPure = new mongoNative.BSONPure.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]); -var BSONNative = new mongoNative.BSONNative.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]); - -var COUNT = 500000 -// var COUNT = 100000 -// var COUNT = 20000 -// var COUNT = 10000 -// var COUNT = 1 - -// Function with scope -var function2 = function() {}; -function2.scope = {a:1}; - -var object = { - string: "Strings are great", - // obj: { - // string2: "This is String 2", - // }, - // - // decimal: 3.14159265, - // 'undefined': undefined, - // bool: true, - // integer: 5, - // regexp:/fdfdfd/mig, - // regexp:/fdfdfd/, - // subObject: { - // moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", - // longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin.", - // - // subObject: { - // moreText: "Bacon ipsum dolor sit amet cow pork belly rump ribeye pastrami andouille. Tail hamburger pork belly, drumstick flank salami t-bone sirloin pork chop ribeye ham chuck pork loin shankle. Ham fatback pork swine, sirloin shankle short loin andouille shank sausage meatloaf drumstick. Pig chicken cow bresaola, pork loin jerky meatball tenderloin brisket strip steak jowl spare ribs. Biltong sirloin pork belly boudin, bacon pastrami rump chicken. Jowl rump fatback, biltong bacon t-bone turkey. Turkey pork loin boudin, tenderloin jerky beef ribs pastrami spare ribs biltong pork chop beef.", - // longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly boudin shoulder ribeye pork chop brisket biltong short ribs. Salami beef pork belly, t-bone sirloin meatloaf tail jowl spare ribs. Sirloin biltong bresaola cow turkey. Biltong fatback meatball, bresaola tail shankle turkey pancetta ham ribeye flank bacon jerky pork chop. Boudin sirloin shoulder, salami swine flank jerky t-bone pork chop pork beef tongue. Bresaola ribeye jerky andouille. Ribeye ground round sausage biltong beef ribs chuck, shank hamburger chicken short ribs spare ribs tenderloin meatloaf pork loin." - // } - // }, - // dbref: new DBRef('collection', new ObjectID(), 'db'), - // long: Long.fromNumber(1000), - // double: new Double(3.14), - // code1: new Code((function() {}).toString(), {a:1}), - // code: new Code((function() {}).toString()), - // minKey: new MinKey(), - // maxKey: new MaxKey(), - // objectId: new ObjectID(), - // binary: new Binary('hello world'), - // symbol: new Symbol('hello'), - // timestamp: Timestamp.fromNumber(1000), - // date: new Date(), - // function1: function() {}, - // function2: function2, - // buffer:new Buffer('hello world'), - // 'null': null, - // subArray: [1,2,3,4,5,6,7,8,9,10], - // anotherString: "another string" -} - -var start = new Date -for (i=COUNT; --i>=0; ) { - // calculate1 = BSONPure.calculateObjectSize(object, true); - serialize1 = BSONPure.serialize(object, null, true) -} -var end = new Date -console.log(COUNT + "x BSONPure.calculateObjectSize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -start = new Date -for (i=COUNT; --i>=0; ) { - // calculate2 = BSONNative.calculateObjectSize(object, true); - serialize2 = BSONNative.serialize(object, null, true) -} -end = new Date -console.log(COUNT + "x BSONNative.calculateObjectSize(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - - -start = new Date -for (i=COUNT; --i>=0; ) { - // calculate3 = BSONNative.calculateObjectSize2(object) - serialize3 = BSONNative.serialize2(object, null, true) -} -end = new Date -console.log(COUNT + "x BSONNative.calculateObjectSize2(object) time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - -// console.log("----------------------------------------------------------------------- size"); -// console.log("calculate1 = " + calculate1); -// console.log("calculate2 = " + calculate2); -// console.log("calculate3 = " + calculate3); - -console.log("----------------------------------------------------------------------- serialize"); -console.log(serialize1.toString('hex')) -console.log(serialize2.toString('hex')) -console.log(serialize3.toString('hex')) - -function compare(b1, b2) { - try { - require('assert').deepEqual(b1,b2) - return true - } catch (e) { - console.error(e) - return false - } -} diff --git a/node_modules/reg/node_modules/mongodb/dev/benchmark/emit_benchmark.js b/node_modules/reg/node_modules/mongodb/dev/benchmark/emit_benchmark.js deleted file mode 100644 index aa365de..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/benchmark/emit_benchmark.js +++ /dev/null @@ -1,49 +0,0 @@ -var debug = require('util').debug, - inspect = require('util').inspect, - inherits = require('util').inherits, - net = require('net'), - EventEmitter = require("events").EventEmitter; - -var COUNT = 1000000; - -var Emitter = function() { -} - -inherits(Emitter, EventEmitter); - -Emitter.prototype.start = function() { - for(var i = 0; i < COUNT; i++) { - this.emit("data", "============================================== data") - } -} - -Emitter.prototype.start2 = function(callback) { - for(var i = 0; i < COUNT; i++) { - callback(null, "============================================== data") - } -} - -// Create test object -var emitObj = new Emitter(); -emitObj.on("data", function(data) { -}) - -console.log(COUNT + "x (objectBSON = BSON.serialize(object))") -start = new Date - -emitObj.start(); - -end = new Date -console.log("time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - - -console.log(COUNT + "x (objectBSON = BSON.serialize(object))") -start = new Date - -emitObj.start2(function(err, data) { - // debug(data) -}); - -end = new Date -console.log("time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") - diff --git a/node_modules/reg/node_modules/mongodb/dev/benchmark/grid_fs_write_benchmark.js b/node_modules/reg/node_modules/mongodb/dev/benchmark/grid_fs_write_benchmark.js deleted file mode 100644 index ae454f2..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/benchmark/grid_fs_write_benchmark.js +++ /dev/null @@ -1,25 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Server = require('../lib/mongodb').Server, - ObjectID = require('../lib/mongodb').ObjectID, - GridStore = require('../lib/mongodb').GridStore; - -var simulated_buffer = new Buffer(1024*1000*10).toString(); - -new Db('grid_fs_write_benchmark', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {}).open(function(err, new_client) { - new_client.dropDatabase(function(err, result) { - new_client.close(); - - for(var i = 0; i < 1; i++) { - new Db('grid_fs_write_benchmark', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {}).open(function(err, client) { - var gridStore = new GridStore(client, "foobar" + i, "w"); - gridStore.open(function(err, gridStore) { - gridStore.write(simulated_buffer.toString(), function(err, gridStore) { - gridStore.close(function(err, result) { - client.close(); - }); - }); - }); - }); - } - }) -}); diff --git a/node_modules/reg/node_modules/mongodb/dev/benchmark/gridfs_benchmark.js b/node_modules/reg/node_modules/mongodb/dev/benchmark/gridfs_benchmark.js deleted file mode 100644 index 23d7aa5..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/benchmark/gridfs_benchmark.js +++ /dev/null @@ -1,104 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Server = require('../lib/mongodb').Server, - ObjectID = require('../lib/mongodb').ObjectID, - GridStore = require('../lib/mongodb').GridStore; - -var Mongolian = require('mongolian'); -var COUNT = 1000; -var currentWritingIndex = 0; -var server = new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:1, native_parser:true}); - -// Read in the test file -var fileData = require('fs').readFileSync("./test/gridstore/iya_logo_final_bw.jpg"); - -// ------------------------------------------------------------------------------ -// TEST MONGODB NATIVE -// ------------------------------------------------------------------------------ -// Open a db for the file -new Db('gridfs_benchmark', server, {}).open(function(err, new_client) { - new_client.dropDatabase(function(err, result) { - new_client.close(); - - new Db('gridfs_benchmark', server, {}).open(function(err, client) { - // Start Time - var startTime = new Date().getTime(); - - // Iterate COUNT times writing file to gridfs - for(var i = 0; i < COUNT; i++) { - var gridStore = new GridStore(client, "foobar" + i, "w"); - gridStore.open(function(err, gridStore) { - gridStore.writeBuffer(fileData, true, function(err, gridStore) { - // Update current write index - currentWritingIndex = currentWritingIndex + 1; - - // finish up - if(currentWritingIndex >= COUNT) { - // Start Time - var endTime = new Date().getTime(); - var totalTime = (endTime - startTime); - var msPerOperation = totalTime/COUNT; - var operationsPrSecond = 1000/msPerOperation; - var bytesPrSecond = Math.floor(fileData.length * operationsPrSecond); - var mbsPrSecond = (bytesPrSecond/1024)/1024 ; - - console.log("-------------------------------------------------- DONE NATIVE") - console.log("total time ms :: " + totalTime); - console.log("ms pr operation :: " + msPerOperation); - console.log("operations pr second :: " + operationsPrSecond); - console.log("bytes pr second :: " + bytesPrSecond); - console.log("MB pr second :: " + mbsPrSecond); - // Close db - client.close(); - // Execute mongolian test - executeMongolianTest(); - } - }) - }); - } - }); - }) -}); - -// ------------------------------------------------------------------------------ -// TEST MONGODB NATIVE -// ------------------------------------------------------------------------------ -var executeMongolianTest = function() { - var db = new Mongolian('mongo://localhost/mongolian_test', { log:false }) - var gridfs = db.gridfs('testfs') - - // Number of executed operations - var currentWritingIndexM = 0; - // Start Time - var startTime = new Date().getTime(); - - // Execute Mongolian Count times writing data - for(var i = 0; i < COUNT; i++) { - var stream = gridfs.create('foo' + i).writeStream(); - stream.on('close', function() { - currentWritingIndexM = currentWritingIndexM + 1; - - if(currentWritingIndexM >= COUNT) { - // Start Time - var endTime = new Date().getTime(); - var totalTime = (endTime - startTime); - var msPerOperation = totalTime/COUNT; - var operationsPrSecond = 1000/msPerOperation; - var bytesPrSecond = Math.floor(fileData.length * operationsPrSecond); - var mbsPrSecond = (bytesPrSecond/1024)/1024 ; - - console.log("-------------------------------------------------- DONE MONGOLIAN") - console.log("total time ms :: " + totalTime); - console.log("ms pr operation :: " + msPerOperation); - console.log("operations pr second :: " + operationsPrSecond); - console.log("bytes pr second :: " + bytesPrSecond); - console.log("MB pr second :: " + mbsPrSecond); - - // Close connection - db.server.close() - } - }); - - // Write file - stream.end(fileData); - } -} diff --git a/node_modules/reg/node_modules/mongodb/dev/benchmark/hammer.js b/node_modules/reg/node_modules/mongodb/dev/benchmark/hammer.js deleted file mode 100644 index fa8d533..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/benchmark/hammer.js +++ /dev/null @@ -1,143 +0,0 @@ -var BSON = require('../../lib/mongodb').BSONNative.BSON, - ObjectID = require('../../lib/mongodb').BSONNative.ObjectID, - Code = require('../../lib/mongodb').BSONNative.Code, - debug = require('util').debug, - inspect = require('util').inspect, - mongodb = require('../../lib/mongodb'), - Db = mongodb.Db, - Server = mongodb.Server, - Step = require("../../deps/step/lib/step"); - -var BSON = require('../../lib/mongodb').BSONPure.BSON, - ObjectID = require('../../lib/mongodb').BSONPure.ObjectID; - -// Open the db connection -new Db('hammer_db', new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: false}).open(function(err, db) { - db.dropCollection('hammer_collection', function(err, result) { - db.admin().authenticate('admin', 'admin', function(err, result) { - var i = 0; - // Fire random command - setInterval(function() { - var command = Math.round(Math.random() * 4); - // command = 1; - - // debug("================= execute :: " + i++ + " = " + command) - - // Execute the command - if(command == 1) { - // Execute an insert - db.collection('hammer_collection', function(err, collection) { - collection.insert(randomDoc(), {safe:false}, function(err, result) { - debug("---------------------------------------- INSERT") - }); - }); - } else if(command == 2) { - // Update some random record - db.collection('hammer_collection', function(err, collection) { - collection.findOne({}, function(err, item) { - if(!err && item != null) { - // Grab key before we bork it - var _id = item._id; - var keys = Object.keys(item); - var objLength = keys.length; - var pickRandomItem = Math.round(Math.random() * objLength); - // Show a random doc in - item[keys[pickRandomItem]] = randomDoc(); - // Update doc - collection.update({'_id':_id}, item, {safe:false}, function(err, result) { - debug("---------------------------------------- UPDATE") - }); - } - }) - }); - } else if(command == 3) { - // Update some random record - db.collection('hammer_collection', function(err, collection) { - collection.findOne({}, function(err, item) { - if(!err && item != null) { - // Update doc - collection.remove({'_id':item._id}, {safe:false}, function(err, result) { - debug("---------------------------------------- REMOVE") - }); - } - }) - }); - } else if(command == 4) { - db.collection('hammer_collection', function(err, collection) { - collection.find().limit(100).toArray(function(err, items) { - debug("---------------------------------------- QUERY :: " + items.length) - }) - }) - } - }, 0); - }) - }); -}); - -// -// Create a random document -var randomDoc = function() { - var numberOfElements = Math.round(Math.random() * 100); - var object = {}; - - for(var i = 0; i< numberOfElements; i++) { - // Pick an element and add it - var element = Math.round(Math.random() * 4); - var name = randomName(); - - if(element == 1) { - object[name] = randomString(); - } else if(element == 2) { - object[name] = Math.round(Math.random() * 4294967295); - } else if(element == 3) { - object[name] = Math.round(Math.random() * -4294967295); - } else if(element == 4) { - - } - } - - return object; -} - -// -// Create a random name -var randomName = function() { - var numberOfElements = Math.round(Math.random() * 250); - var buffer = new Buffer(numberOfElements); - - for(var i = 0; i< numberOfElements; i++) { - buffer[i] = 97 + Math.round(Math.random() * (122-97)); - } - - return buffer.toString(); -} - -// -// Create a random string -var randomString = function() { - var numberOfElements = Math.round(Math.random() * 250); - var buffer = new Buffer(numberOfElements); - - for(var i = 0; i< numberOfElements; i++) { - buffer[i] = Math.round(Math.random() * 255); - } - - return buffer.toString(); -} - - - - - - - - - - - - - - - - - diff --git a/node_modules/reg/node_modules/mongodb/dev/benchmark/hammer_replicaset.js b/node_modules/reg/node_modules/mongodb/dev/benchmark/hammer_replicaset.js deleted file mode 100644 index fc2d038..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/benchmark/hammer_replicaset.js +++ /dev/null @@ -1,197 +0,0 @@ -var BSON = require('../../lib/mongodb').BSONNative.BSON, - ObjectID = require('../../lib/mongodb').BSONNative.ObjectID, - Code = require('../../lib/mongodb').BSONNative.Code, - debug = require('util').debug, - inspect = require('util').inspect, - mongodb = require('../../lib/mongodb'), - Db = mongodb.Db, - Server = mongodb.Server, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager, - Step = require("../../deps/step/lib/step"); - -var BSON = require('../../lib/mongodb').BSONPure.BSON, - ObjectID = require('../../lib/mongodb').BSONPure.ObjectID; - -var db = null; -var poolSize = 1; -var RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true, poolSize: poolSize } ), - // new Server( RS.host, RS.ports[0], { auto_reconnect: true, poolSize: poolSize } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true, poolSize: poolSize } ) - ], - {rs_name:RS.name, readPreference:Server.READ_SECONDARY, poolSize: poolSize} - ); - - // Open the db connection - new Db('hammer_db', replSet, {native_parser: false, retryMiliSeconds: 1000}).open(function(err, p_db) { - db = p_db; - if(err != null) throw err; - // Start hammering - hammerTime(); - }); -}); - -// Hammer the set -var hammerTime = function() { - db.dropCollection('hammer_collection', function(err, result) { - var i = 0; - // Fire random command - setInterval(function() { - var command = Math.round(Math.random() * 4); - // command = 2; - - debug("================= execute :: " + i++ + " = " + command) - - // Execute the command - if(command == 1) { - // Execute an insert - db.collection('hammer_collection', function(err, collection) { - collection.insert(randomDoc(), {safe:false}, function(err, result) { - debug("---------------------------------------- INSERT ") - debug(inspect(err)) - }); - }); - } else if(command == 2) { - // Update some random record - db.collection('hammer_collection', function(err, collection) { - // console.log("================================================================== update :: 0") - if(err != null) { - console.log("------------------------------------- error update 1") - console.dir(err) - } - - collection.findOne({}, function(err, item) { - if(err == null && item != null) { - // console.log("================================================================== update :: 1") - // Grab key before we bork it - var _id = item._id; - var keys = Object.keys(item); - var objLength = keys.length; - var pickRandomItem = Math.round(Math.random() * objLength); - // Show a random doc in - item[keys[pickRandomItem]] = randomDoc(); - // Update doc - collection.update({'_id':_id}, item, {safe:false}, function(err, result) { - debug("---------------------------------------- UPDATE") - }); - } else { - console.log("------------------------------------- error update 2") - console.dir(err) - } - }) - }); - } else if(command == 3) { - // Update some random record - db.collection('hammer_collection', function(err, collection) { - // if(err != null) { - // console.log("------------------------------------- error remove 1") - // console.dir(err) - // } - - collection.findOne({}, function(err, item) { - // debug(inspect(err)) - // debug(inspect(item)) - - if(err == null && item != null) { - // Update doc - collection.remove({'_id':item._id}, {safe:false}, function(err, result) { - debug("---------------------------------------- REMOVE") - }); - } else { - // console.log("------------------------------------- error remove 2") - // console.dir(err) - } - }) - }); - } else if(command == 4) { - db.collection('hammer_collection', function(err, collection) { - // if(err != null) { - // console.log("------------------------------------- error query 1") - // console.dir(err) - // } - - collection.find().limit(100).toArray(function(err, items) { - if(err != null) { - console.log("------------------------------------- error query 2") - console.dir(err) - } else { - debug("---------------------------------------- QUERY :: " + items.length) - } - }) - }) - } - }, 100); - }); -} - -// -// Create a random document -var randomDoc = function() { - var numberOfElements = Math.round(Math.random() * 100); - var object = {}; - - for(var i = 0; i< numberOfElements; i++) { - // Pick an element and add it - var element = Math.round(Math.random() * 4); - var name = randomName(); - - if(element == 1) { - object[name] = randomString(); - } else if(element == 2) { - object[name] = Math.round(Math.random() * 4294967295); - } else if(element == 3) { - object[name] = Math.round(Math.random() * -4294967295); - } else if(element == 4) { - - } - } - - return object; -} - -// -// Create a random name -var randomName = function() { - var numberOfElements = Math.round(Math.random() * 250); - var buffer = new Buffer(numberOfElements); - - for(var i = 0; i< numberOfElements; i++) { - buffer[i] = 97 + Math.round(Math.random() * (122-97)); - } - - return buffer.toString(); -} - -// -// Create a random string -var randomString = function() { - var numberOfElements = Math.round(Math.random() * 250); - var buffer = new Buffer(numberOfElements); - - for(var i = 0; i< numberOfElements; i++) { - buffer[i] = Math.round(Math.random() * 255); - } - - return buffer.toString(); -} - - - - - - - - - - - - - - - - - diff --git a/node_modules/reg/node_modules/mongodb/dev/benchmark/streaming_benchmark.js b/node_modules/reg/node_modules/mongodb/dev/benchmark/streaming_benchmark.js deleted file mode 100644 index 44014da..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/benchmark/streaming_benchmark.js +++ /dev/null @@ -1,43 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Server = require('../lib/mongodb').Server, - Cursor = require('../lib/mongodb').Cursor, - Collection = require('../lib/mongodb').Collection, - sys = require('util'), - debug = require('util').debug, - inspect = require('util').inspect; - -var parser = require('../lib/mongodb').BSONPure; -var objectID = require('../lib/mongodb').ObjectID; - -var db = new Db('streaming_benchmark', new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:4}), {}) -// Open the db -db.open(function(err, client) { - client.collection('streaming_benchmark', function(err, collection) { - collection.remove({}, function(err, result) { - // Benchmark - var started_at = new Date().getTime(); - // Add documents - for(var i = 0; i < 100000; i++) { - // for(var i = 0; i < 10000; i++) { - collection.save({'i':i, 'a':i, 'c':i, 'd':{'i':i}}, function(err, result){}); - } - sys.puts("save recs: " + ((new Date().getTime() - started_at)/1000) + "seconds"); - - // Benchmark - var started_at = new Date().getTime(); - var count = 0; - collection.find(function(err, cursor) { - var stream = cursor.streamRecords(function(er,item) {}); - stream.addListener('end', function() { - client.close(); - }); - stream.addListener('data',function(data){ - if(count == 0) started_at = new Date().getTime(); - count++; - if ((count%10000)==0) sys.puts("recs:" + count + " :: " + - ((new Date().getTime() - started_at)/10000) + "seconds"); - }); - }); - }) - }) -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/dev/harness/memory_leak_harness.js b/node_modules/reg/node_modules/mongodb/dev/harness/memory_leak_harness.js deleted file mode 100644 index e61ba73..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/harness/memory_leak_harness.js +++ /dev/null @@ -1,46 +0,0 @@ -var http = require('http'), - Server = require('../lib/mongodb').Server, - ObjectID = require('../lib/mongodb').ObjectID, - Db = require('../lib/mongodb').Db; - -// Set up the mongodb instance -var db = new Db('memory_leak_harness', new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser:false}); - -// Set up http server -var server = http.createServer(); -server.on('request', function(request, response) { - // Fetch the url - var url = request.url; - - // Switch on the url - if(url === "/findAndModify") { - findAndModifyCommand(request, response); - } else { - response.end('Command not supported'); - } -}) - -// Open the db connection -db.open(function(err, db) { - server.listen(8080, '127.0.0.1'); -}); - -// Find And Modify Command -var findAndModifyCommand = function(request, response) { - // Perform an insert and the modify that one - var objectId = new ObjectID(); - // Fetch collection and insert document then modify it - db.createCollection('findAndModify', function(err, collection) { - collection.insert({_id:objectId, a:1, b:true, date:new Date()}, {safe:true}, function(err, result) { - if(err != null) { - response.end("findAndModifyCommand ERROR :: " + err.toString()); - return; - } - - // Perform the modifyAndModify - collection.findAndModify({_id:objectId}, [['_id', 1]], {'$set':{'a':2}}, {'new':true, safe:true}, function(err, updated_doc) { - response.end("findAndModifyCommand SUCCESS :: " + JSON.stringify(updated_doc)); - }); - }) - }); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/dev/tools/build-docs.js b/node_modules/reg/node_modules/mongodb/dev/tools/build-docs.js deleted file mode 100644 index c44d29c..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/tools/build-docs.js +++ /dev/null @@ -1,162 +0,0 @@ -var fs = require('fs'), - dox = require('dox'), - parseJS = require('uglify-js').parser, - ejs = require('ejs'), - exec = require('child_process').exec, - format = require('util').format, - format = require('util').format, - docs = require('./docs'); - -// ---------------------------------------------------------------------------- -// INITALIZE -// ---------------------------------------------------------------------------- -// All source files for the api generation -var apiClasses = [ - {tag:"admin", path:"./lib/mongodb/admin.js"}, - {tag:"collection", path:"./lib/mongodb/collection.js"}, - {tag:"db", path:"./lib/mongodb/db.js"}, - {tag:"cursor", path:"./lib/mongodb/cursor.js"}, - {tag:"cursorstream", path:"./lib/mongodb/cursorstream.js"}, - {tag:"gridstore", path:"./lib/mongodb/gridfs/gridstore.js"}, - {tag:"readstream", path:"./lib/mongodb/gridfs/readstream.js"}, - {tag:"grid", path:"./lib/mongodb/gridfs/grid.js"} - ]; - -// All test files -var testClasses = [ - {path:"./test/admin_test.js"}, - {path:"./test/objectid_test.js"}, - {path:"./test/insert_test.js"}, - {path:"./test/remove_test.js"}, - {path:"./test/collection_test.js"}, - {path:"./test/db_test.js"}, - {path:"./test/find_test.js"}, - {path:"./test/map_reduce_test.js"}, - {path:"./test/index_test.js"}, - {path:"./test/geo_search_test.js"}, - {path:"./test/replicaset/connect_test.js"}, - {path:"./test/connect_test.js"}, - {path:"./test/multiple_dbs_on_connection_pool_test.js"}, - {path:"./test/cursor_test.js"}, - {path:"./test/cursorstream_test.js"}, - {path:"./test/gridstore/grid_store_test.js"}, - {path:"./test/gridstore/grid_store_file_test.js"}, - {path:"./test/gridstore/grid_store_stream_test.js"}, - {path:"./test/gridstore/readstream_test.js"}, - {path:"./test/gridstore/grid_test.js"}, - {path:"./test/bson_types_test.js"}, - {path:"./test/bson/bson_test.js"} - ] - -// Read all the templates -var templates = [ - {tag:'index', path:'./dev/tools/doc-templates/index.ejs'}, - {tag:'changelog', path:'./dev/tools/doc-templates/changelog.ejs'}, - {tag:'index_no_header', path:'./dev/tools/doc-templates/index_no_header.ejs'}, - {tag:'class', path:'./dev/tools/doc-templates/class.ejs'}, - {tag:'function', path:'./dev/tools/doc-templates/function.ejs'} -] - -// Output directory -var outputDirectory = "./docs/sphinx-docs/source/api-generated" - -// Force create the directory for the generated docs -exec('rm -rf ' + outputDirectory, function (error, stdout, stderr) {}); -exec('mkdir ' + outputDirectory, function (error, stdout, stderr) {}); - -// ---------------------------------------------------------------------------- -// PROCESS Driver API -// ---------------------------------------------------------------------------- -// Extract meta data from source files -var dataObjects = docs.extractLibraryMetaData(apiClasses); -// Filter out and prepare the test Objects hash -var testObjects = docs.buildTestHash(docs.extractLibraryMetaData(testClasses)); -// Read all the templates -var templates = docs.readAllTemplates(templates); -// Render all the classes that are decorated -docs.renderAllTemplates(outputDirectory, templates, dataObjects, testObjects, {index_title:'Driver API'}); - -// ---------------------------------------------------------------------------- -// PROCESS BSON API -// ---------------------------------------------------------------------------- -// Output directory -var outputDirectory2 = "./docs/sphinx-docs/source/api-bson-generated" -// Force create the directory for the generated docs -exec('rm -rf ' + outputDirectory2, function (error, stdout, stderr) {}); -exec('mkdir ' + outputDirectory2, function (error, stdout, stderr) {}); - -var apiClasses2 = [ - {tag:"objectid", path:"./lib/mongodb/bson/objectid.js"}, - {tag:"binary", path:"./lib/mongodb/bson/binary.js"}, - {tag:"code", path:"./lib/mongodb/bson/code.js"}, - {tag:"code", path:"./lib/mongodb/bson/db_ref.js"}, - {tag:"double", path:"./lib/mongodb/bson/double.js"}, - {tag:"minkey", path:"./lib/mongodb/bson/min_key.js"}, - {tag:"maxkey", path:"./lib/mongodb/bson/max_key.js"}, - {tag:"symbol", path:"./lib/mongodb/bson/symbol.js"}, - {tag:"timestamp", path:"./lib/mongodb/bson/timestamp.js"}, - {tag:"long", path:"./lib/mongodb/bson/long.js"}, - {tag:"bson", path:"./lib/mongodb/bson/bson.js"} - ]; - -// Read all the templates -var templates2 = [ - {tag:'index', path:'./dev/tools/doc-templates/index.ejs'}, - {tag:'changelog', path:'./dev/tools/doc-templates/changelog.ejs'}, - {tag:'index_no_header', path:'./dev/tools/doc-templates/index_no_header.ejs'}, - {tag:'class', path:'./dev/tools/doc-templates/class.ejs'}, - {tag:'function', path:'./dev/tools/doc-templates/function.ejs'} -] - -// Extract meta data from source files -var dataObjects2 = docs.extractLibraryMetaData(apiClasses2); -// Filter out and prepare the test Objects hash -var testObjects2 = docs.buildTestHash(docs.extractLibraryMetaData(testClasses)); -// Render all the classes that are decorated -docs.renderAllTemplates(outputDirectory2, templates, dataObjects2, testObjects2, {index_title:'Binary JSON API'}); - -// ---------------------------------------------------------------------------- -// PROCESS MARKDOWN DOCUMENTS TO STRUCTURED TEXT -// ---------------------------------------------------------------------------- - -// Transform the tutorials -var articles = [ - {name:"NodeKOArticle1", output:"NodeKOArticle1.rst", path:"./docs/articles/NodeKOArticle1.md"}, - {name:"NodeKOArticle2", output:"NodeKOArticle2.rst", path:"./docs/articles/NodeKOArticle2.md"} - ]; -// Tranform the markdown to restructured text -docs.writeMarkDownFile("./docs/sphinx-docs/source/api-articles", articles, templates, - {title:'Articles', template:'index'}); - -// Transform the tutorials -var articles = [ - {name:"collections", output:"collections.rst", path:"./docs/collections.md"}, - {name:"database", output:"database.rst", path:"./docs/database.md"}, - {name:"gridfs", output:"gridfs.rst", path:"./docs/gridfs.md"}, - {name:"indexes", output:"indexes.rst", path:"./docs/indexes.md"}, - {name:"insert", output:"insert.rst", path:"./docs/insert.md"}, - {name:"queries", output:"queries.rst", path:"./docs/queries.md"}, - {name:"replicaset", output:"replicaset.rst", path:"./docs/replicaset.md"}, - ]; -// Tranform the markdown to restructured text -docs.writeMarkDownFile("./docs/sphinx-docs/source/markdown-docs", articles, templates, - {title:'Using the driver', template:'index_no_header'}); - -// ---------------------------------------------------------------------------- -// WRITE CHANGELOG TO THE DOCUMENTATION -// ---------------------------------------------------------------------------- - -// Outputdiectory -var outputDirectory = "./docs/sphinx-docs/source/changelog"; -// Force create the directory for the generated docs -exec('rm -rf ' + outputDirectory, function (error, stdout, stderr) {}); -exec('mkdir ' + outputDirectory, function (error, stdout, stderr) { - // Read the changelog - var changelog = fs.readFileSync('./HISTORY').toString(); - // Just write out the index - var content = ejs.render(templates["changelog"], {content:changelog}); - // Write it out - fs.writeFileSync(format("%s/changelog.rst", outputDirectory), content); -}); - - diff --git a/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/changelog.ejs b/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/changelog.ejs deleted file mode 100644 index 54626d1..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/changelog.ejs +++ /dev/null @@ -1,5 +0,0 @@ -========= -Changelog -========= - -<%= content %> \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/class.ejs b/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/class.ejs deleted file mode 100644 index 333b0f8..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/class.ejs +++ /dev/null @@ -1,317 +0,0 @@ -<% -for(var i = 0; i < entries.length; i++) { - if(isClass(entries[i].tags)) { - - } -} - -var addLine = function(char, length) { - var chars = []; - for(var i = 0; i < length; i++) chars[i] = char; - return chars.join(''); -} - -// Contains the current class name -var className = null; - -for(var i = 0; i < entries.length; i++) { - if(isClass(entries[i].tags)) { - var _name = entries[i].ctx.string.trim(); - - %><%= format("%s\n%s\n%s\n", addLine("=", _name.length), _name, addLine("=", _name.length)) %><% - className = entries[i].ctx.string.replace("()", ""); - - %><%= format("\n------------------\nConstructor\n------------------\n") %><% - - // Get full description and clean it - var fullDescription = entries[i].description.summary; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/strong\>/g, "**") - .replace(/\|\<\/em\>/g, "*") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - %><%- format("%s\n\n", fullDescription) %><% - %><%= format("\n .. js:class:: %s\n\n", entries[i].ctx.string) %><% - - for(var ti = 0; ti < entries[i].tags.length; ti++) { - // Get the current tag - var tag = entries[i].tags[ti]; - // If we have a parameter render it - if(tag.type == 'param') { - // Unpack the tag - var type = tag.types[0].toLowerCase(); - var name = tag.name; - var description = tag.description; - // Render the parameter - %><%= format(" :param %s %s: %s\n", type, name, description) %><% - } else if(tag.type == 'return') { - // Unpack the tag - var type = tag.types[0].toLowerCase(); - var description = tag.description; - // Render the parameter - %><%= format(" :returns: %s %s\n", type, description) %><% - } - } - - // Get full description and clean it - var fullDescription = entries[i].description.body; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/strong\>/g, "**") - .replace(/\|\<\/em\>/g, "*") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - %><%- format("%s\n\n", fullDescription) %><% - } -} - -for(var i = 0; i < entries.length; i++) { - if(isClassConstant(entries[i])) { - %><%= format("\n------------------\nConstants\n------------------\n") %><% -%> -.. csv-table:: - :header: "Constant Name", "Value", "Description" - :widths: 15, 10, 30 - -<% - break; - } -} - -for(var i = 0; i < entries.length; i++) { - if(isClassConstant(entries[i])) { - // Extract values - var attributeName = format("%s = %s;", entries[i].ctx.string, entries[i].ctx.value); - var getterSetters = []; - var type = ""; - - // Get full description and clean it - var fullDescription = entries[i].description.full; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - - // Write out the class definition row - %><%- format(" \"%s\", \"%s\", \"%s\"\n", entries[i].ctx.string.trim(), entries[i].ctx.value.trim(), fullDescription.trim()) %><% - } -} - -for(var i = 0; i < entries.length; i++) { - if(isProperty(entries[i])) { - %><%= format("\n------------------\nProperties\n------------------\n") %><% - break; - } -} - -for(var i = 0; i < entries.length; i++) { - if(isProperty(entries[i])) { - // Extract values - var attributeName = ""; - var getterSetters = []; - var type = ""; - - // Loop over all tags - for(var ti = 0; ti < entries[i].tags.length; ti++) { - if(entries[i].tags[ti].type == 'field') attributeName = entries[i].tags[ti].string; - if(entries[i].tags[ti].type == 'getter') getterSetters.push("Getter"); - if(entries[i].tags[ti].type == 'setter') getterSetters.push("Setter"); - if(entries[i].tags[ti].type == 'type') type = entries[i].tags[ti].types[0].toLowerCase(); - } - - // Get full description and clean it - var fullDescription = entries[i].description.full; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - - // Write out the text - %><%- format("%s\n\n", fullDescription) %><% - %><%= format(".. js:attribute:: %s %s [%s]\n\n", attributeName, type, getterSetters.join("|")) %><% - - // If we have examples render them - if(examples != null && examples[attributeName]) { - %><%= format("\n**Examples**\n\n") %><% - var examplesArray = examples[attributeName]; - // Iterate over all the examples - for(var ei = 0; ei < examplesArray.length; ei++) { - // Fetch an example - var example = examplesArray[ei]; - var code = example.code; - code = code.replace(", ssl:useSSL", "") - .replace("native_parser: native_parser", "native_parser: false") - .replace(/test\.ok/g, "assert.ok") - .replace(/test\.equal/g, "assert.equal") - .replace(/test\.deepEqual/g, "assert.deepEqual") - .replace(/\n[ |\t]*test\.done\(\)\;/, ""); - - // Split and adjust code - var codeLines = code.split(/\n/); - for(var ci = 0; ci < codeLines.length; ci++) { - codeLines[ci] = " " + codeLines[ci]; - } - - var fullDescription = example.description.full; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - - // Split up and move - var fullDescriptionLines = fullDescription.split(/\n/); - for(var ci = 0; ci < fullDescriptionLines.length; ci++) { - fullDescriptionLines[ci] = " " + fullDescriptionLines[ci]; - } - - // Starting template Lines - var startingTemplateLines = [ - " var Db = require('mongodb').Db,", - " Server = require('mongodb').Server,", - " ReplSetServers = require('mongodb').ReplSetServers,", - " ObjectID = require('mongodb').ObjectID,", - " Binary = require('mongodb').Binary,", - " GridStore = require('mongodb').GridStore,", - " Code = require('mongodb').Code,", - " BSON = require('mongodb').pure().BSON,", - " assert = require('assert');\n\n" - ]; - - // Let's render it - %><%- format("%s\n\n", fullDescriptionLines.join("\n")) %><% - %><%- format(" .. code-block:: javascript\n\n%s%s\n\n", startingTemplateLines.join("\n"), codeLines.join("\n")) %><% - } - } - } -} - -for(var i = 0; i < entries.length; i++) { - // If it's a function parse it - if(isFunction(entries[i])) { - var paramsStrings = []; - var paramNames = []; - - for(var ti = 0; ti < entries[i].tags.length; ti++) { - // Get the current tag - var tag = entries[i].tags[ti]; - // If we have a parameter render it - if(tag.type == 'param') { - // Unpack the tag - var type = tag.types[0].toLowerCase(); - var name = tag.name; - var description = tag.description; - // Add to list of params - paramNames.push(name); - // Render the parameter - paramsStrings.push(format(" :param %s %s: %s\n", type, name, description)); - } else if(tag.type == 'return') { - // Unpack the tag - var type = tag.types[0].toLowerCase(); - var description = tag.description; - // Render the parameter - paramsStrings.push(format(" :returns: %s %s\n\n", type, description)); - } - } - - // Reformat any optional parameters from ,[] to [,] - var paramsString = paramNames.join(", ").replace(/\, \[/, "[, "); - // Write out the methods - var fullDescription = entries[i].description.full; - - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/strong\>/g, "**") - .replace(/\|\<\/em\>/g, "*") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - - // The name of examples - var examplesName = entries[i].ctx.name; - - // Write header depending on if it's class or instance level - if(entries[i].ctx.receiver != null) { - // Change examples Name to include class name - var examplesName = format("%s.%s", className, entries[i].ctx.name); - var _length = format("%s.%s", className, entries[i].ctx.name).length; - %><%= format("\n%s\n%s.%s\n%s\n", addLine("-", _length), className, entries[i].ctx.name, addLine("-", _length)) %><% - %><%- format("%s\n\n", fullDescription) %><% - %><%= format(".. js:function:: %s.%s(%s)\n\n", className, entries[i].ctx.name, paramsString) %><% - } else { - var _length = entries[i].ctx.name.length; - %><%= format("\n%s\n%s\n%s\n", addLine("-", _length), entries[i].ctx.name, addLine("-", _length)) %><% - %><%- format("%s\n\n", fullDescription) %><% - %><%= format(".. js:function:: %s(%s)\n\n", entries[i].ctx.name, paramsString) %><% - } - - %><%= Array.isArray(paramsStrings) ? paramsStrings.join("") : paramsStrings %><% - - // If we have examples render them - if(examples != null && examples[examplesName]) { - %><%= format("\n**Examples**\n\n") %><% - var examplesArray = examples[examplesName]; - // Iterate over all the examples - for(var ei = 0; ei < examplesArray.length; ei++) { - // Fetch an example - var example = examplesArray[ei]; - var code = example.code; - code = code.replace(", ssl:useSSL", "") - .replace("native_parser: native_parser", "native_parser: false") - .replace(/test\.ok/g, "assert.ok") - .replace(/test\.equal/g, "assert.equal") - .replace(/test\.deepEqual/g, "assert.deepEqual") - .replace(/\n[ |\t]*test\.done\(\)\;/, ""); - - // Split and adjust code - var codeLines = code.split(/\n/); - for(var ci = 0; ci < codeLines.length; ci++) { - codeLines[ci] = " " + codeLines[ci]; - } - - var fullDescription = example.description.full; - fullDescription = fullDescription.replace(/\\/g, ".. code-block:: javascript\n\n ") - .replace(/\<\/code\>\<\/pre\>/g, "") - .replace(/\|\<\/h2\>/g, "**") - .replace(/\/g, "\n\n") - .replace(/\<\/p\>/g, "") - .replace(/\|\<\/br[ ]*\>|\/g, "\n"); - - // Split up and move - var fullDescriptionLines = fullDescription.split(/\n/); - for(var ci = 0; ci < fullDescriptionLines.length; ci++) { - fullDescriptionLines[ci] = " " + fullDescriptionLines[ci]; - } - - // Starting template Lines - var startingTemplateLines = [ - " var Db = require('mongodb').Db,", - " Server = require('mongodb').Server,", - " ReplSetServers = require('mongodb').ReplSetServers,", - " ObjectID = require('mongodb').ObjectID,", - " Binary = require('mongodb').Binary,", - " GridStore = require('mongodb').GridStore,", - " Code = require('mongodb').Code,", - " BSON = require('mongodb').pure().BSON,", - " assert = require('assert');\n\n" - ]; - - // Let's render it - %><%- format("%s\n\n", fullDescriptionLines.join("\n")) %><% - %><%- format(" .. code-block:: javascript\n\n%s%s\n\n", startingTemplateLines.join("\n"), codeLines.join("\n")) %><% - } - } - } -} -%> \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/function.ejs b/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/function.ejs deleted file mode 100644 index 1ff17c5..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/function.ejs +++ /dev/null @@ -1 +0,0 @@ -Function \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/index.ejs b/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/index.ejs deleted file mode 100644 index 453e61d..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/index.ejs +++ /dev/null @@ -1,15 +0,0 @@ -================== -<%- title %> -================== - -.. toctree:: - :maxdepth: 2 - -<% - for(var i = 0; i < entries.length; i++) { - // Classname - var name = entries[i]; - // Write out the name - %><%= format(" %s\n", name) %><% - } -%> \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/index_no_header.ejs b/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/index_no_header.ejs deleted file mode 100644 index 62b582a..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/tools/doc-templates/index_no_header.ejs +++ /dev/null @@ -1,11 +0,0 @@ -.. toctree:: - :maxdepth: 1 - -<% - for(var i = 0; i < entries.length; i++) { - // Classname - var name = entries[i]; - // Write out the name - %><%= format(" %s\n", name) %><% - } -%> \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/dev/tools/docs.js b/node_modules/reg/node_modules/mongodb/dev/tools/docs.js deleted file mode 100644 index c370c9b..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/tools/docs.js +++ /dev/null @@ -1,312 +0,0 @@ -var fs = require('fs'), - dox = require('dox'), - parseJS = require('uglify-js').parser, - ejs = require('ejs'), - exec = require('child_process').exec, - markdown = require('markdown').markdown, - format = require('util').format; - -// ----------------------------------------------------------------------------------------------------- -// -// Markdown converter -// -// ----------------------------------------------------------------------------------------------------- - -// Parse markdown to Rich text format -var transformMarkdownToStructuredText = exports.transformMarkdownToStructuredText = function(markDownText) { - // Parse the md file and generate a json tree - var jsonTree = markdown.parse(markDownText); - var documentLines = []; - return convert_tree_to_rs(jsonTree, documentLines).join('\n'); -} - -var addLine = function(char, length) { - var chars = []; - for(var i = 0; i < length; i++) chars[i] = char; - return chars.join(''); -} - -var convert_tree_to_rs = function(nodes, documentLines) { - if(!Array.isArray(nodes)) throw new Error("Malformed tree structure"); - // Go through all the tags and render - for(var i = 0; i < nodes.length; i++) { - var line = nodes[i]; - // console.dir(line) - - if(Array.isArray(line)) { - switch(line[0]) { - case 'header': - // Unpack the parts - var options = line[1]; - var title = line[2]; - // Add lines to the document - if(options.level == 1) { - documentLines.push(addLine("=", title.length)) - documentLines.push(title); - documentLines.push(addLine("=", title.length)) - } else if(options.level == 2) { - documentLines.push(addLine("-", title.length)) - documentLines.push(title); - documentLines.push(addLine("-", title.length)) - } - break; - case 'para': - var paraLines = []; - paraLines.push("\n"); - - for(var j = 1; j < line.length; j++) { - // bullet list item - if(Array.isArray(line[j])) { - var subdocs = []; - convert_tree_to_rs([line[j]], subdocs); - paraLines.push(subdocs.join('')); - } else { - paraLines.push(line[j]); - } - } - - // Merge the docs in - documentLines.push(paraLines.join(' ')); - documentLines.push('\n'); - break; - case 'link': - documentLines.push(format("`%s <%s>`_", line[2], line[1].href.replace(".md", ".html"))); - break; - case 'inlinecode': - documentLines.push(format("``%s``", line[1])); - break; - case 'code_block': - // Unpack code block - var codeLines = line[1].split("\n"); - // Format all the lines - documentLines.push(" .. code-block:: javascript\n"); - for(var j = 0; j < codeLines.length; j++) { - documentLines.push(format(" %s", codeLines[j])); - } - - documentLines.push("\n"); - break; - case 'bulletlist': - // Render the list (line.length - 1) - for(var j = 1; j < line.length; j++) { - // bullet list item - if(Array.isArray(line[j])) { - var subdocs = []; - convert_tree_to_rs([line[j]], subdocs); - documentLines.push(subdocs.join(' ')); - } else { - documentLines.push(line[j]); - } - } - - // Add an empty line - documentLines.push("\n"); - break; - case 'listitem': - var listitemLines = []; - - for(var j = 1; j < line.length; j++) { - // bullet list item - if(Array.isArray(line[j])) { - var subdocs = []; - convert_tree_to_rs([line[j]], subdocs); - listitemLines.push(subdocs.join(' ')); - } else { - listitemLines.push(line[j]); - } - } - - // Merge the docs in - documentLines.push(format(" * %s", listitemLines.join(' ').trim())); - break; - case 'em': - documentLines.push(format("*%s*", line[1])); - break; - case 'strong': - documentLines.push(format("**%s**", line[1])); - break; - default: - console.dir(line) - break; - } - } - } - - return documentLines; -} - -exports.writeMarkDownFile = function(outputDirectory, articles, templates, options) { - // Force create the directory for the generated docs - exec('rm -rf ' + outputDirectory, function (error, stdout, stderr) {}); - exec('mkdir ' + outputDirectory, function (error, stdout, stderr) {}); - - // Contains all the names for the index - var names = []; - - // Process all the articles - for(var i = 0 ; i < articles.length; i++) { - // Fetch the article markdown content - var article = fs.readFileSync(articles[i].path).toString(); - // Convert the text into restructured text for sphinx - var text = transformMarkdownToStructuredText(article); - // Write out the content - fs.writeFileSync(format("%s/%s", outputDirectory, articles[i].output.toLowerCase()), text); - names.push(articles[i].name.toLowerCase()); - } - - // Just write out the index - var indexContent = ejs.render(templates[options.template], {entries:names, format:format, title:options.title}); - fs.writeFileSync(format("%s/%s", outputDirectory, 'index.rst'), indexContent); -} - -// ----------------------------------------------------------------------------------------------------- -// -// API Doc generation -// -// ----------------------------------------------------------------------------------------------------- -// Parses all the files and extracts the dox data for the library -exports.extractLibraryMetaData = function(sourceFiles) { - var dataObjects = {}; - // Iterate over all source files - for(var i = 0; i < sourceFiles.length; i++) { - // Read source file content - var sourceFile = fs.readFileSync(sourceFiles[i].path); - // Parse the content - var metaData = dox.parseComments(sourceFile.toString()); - // Save the metadata - dataObjects[sourceFiles[i]["tag"] != null ? sourceFiles[i].tag : i] = metaData; - } - - // Return all objects - return dataObjects; -} - -// Build a hash to easy access to the objects -exports.buildTestHash = function(objects) { - // Organize the objects by class-function so we can query them - var objectsByClassAndMethod = {}; - var objectKeys = Object.keys(objects); - - // Get all the objects - for(var i = 0; i < objectKeys.length; i++) { - // Get the object with the metadata - var object = objects[objectKeys[i]]; - // Go through each example and pull them out - for(var j = 0; j < object.length; j++) { - var block = object[j]; - var tags = block.tags; - - // Build a class type - var tagObject = {}; - - // Check for the _class tag - for(var tagIndex = 0; tagIndex < tags.length; tagIndex++) { - // Get the tag - var tag = tags[tagIndex]; - // Grab the tag if it's got it - if(tag['type'] != null && tag['string'] != null) { - tagObject[tag['type']] = tag['string']; - } - } - - // Check if we have the tags _class and _function signaling a test - if(tagObject['_class'] != null && tagObject['_function'] != null) { - // Add a class reference if none exists - if(objectsByClassAndMethod[tagObject['_class']] == null) { - objectsByClassAndMethod[tagObject['_class']] = {}; - } - - // Add a method reference if none exists - if(objectsByClassAndMethod[tagObject['_class']][tagObject['_function']] == null) { - objectsByClassAndMethod[tagObject['_class']][tagObject['_function']] = []; - } - - // Push the object on the list - objectsByClassAndMethod[tagObject['_class']][tagObject['_function']].push(block); - - // Format the block code - var codeLines = block.code.split(/\n/); - // Drop first and last line - codeLines = codeLines.slice(1, codeLines.length - 1); - // Indent the code - for(var k = 0; k < codeLines.length; k++) { - codeLines[k] = codeLines[k].replace(/^ /, "") - } - // Reasign the code block - block.code = codeLines.join("\n"); - } - } - } - - // Return the object mapped by _class and _function - return objectsByClassAndMethod; -} - -// Render all the templates -exports.renderAllTemplates = function(outputDirectory, templates, dataObjects, testObjects, attributeTags) { - // Helper methods used in the rendering - var isClass = function(tags) { - for(var k = 0; k < tags.length; k++) { - if(tags[k].type == 'class') return true; - } - return false; - } - - var isFunction = function(entry) { - return entry.ctx != null && entry.ctx.type == 'method' && entry.isPrivate == false; - } - - var isProperty = function(entry) { - var tags = entry.tags; - for(var k = 0; k < tags.length; k++) { - if(tags[k].type == 'property') return true; - } - return false; - } - - var isClassConstant = function(entry) { - var tags = entry.tags; - for(var k = 0; k < tags.length; k++) { - if(tags[k].type == 'classconstant') return true; - } - return false; - } - - // Iterate over all classes - var classNames = Object.keys(dataObjects); - - // For each class generate output - for(var i = 0; i < classNames.length; i++) { - var className = classNames[i]; - // The meta data object - var classMetaData = dataObjects[className]; - // Grab the examples for this Metadata class - var classExamplesData = testObjects[className]; - // Render the class template - var classContent = ejs.render(templates['class'], - {entries:classMetaData, examples:classExamplesData, isClass:isClass, - isFunction:isFunction, isProperty:isProperty, isClassConstant:isClassConstant, - format:format}); - // Write out the content to disk - fs.writeFileSync(format("%s/%s.rst", outputDirectory, className), classContent); - } - - // Let's render the index api file - var indexContent = ejs.render(templates['index'], - {entries:classNames, isClass:isClass, isFunction:isFunction, isProperty:isProperty, - isClassConstant:isClassConstant, format:format, title:attributeTags['index_title']}); - // Write out the api index to disk - fs.writeFileSync(format("%s/%s.rst", outputDirectory, "index"), indexContent); -} - -// Read all the templates -exports.readAllTemplates = function(templates) { - var finishedTemplates = {}; - // Read in all the templates - for(var i = 0; i < templates.length; i++) { - finishedTemplates[templates[i].tag] = fs.readFileSync(templates[i].path).toString(); - } - - // Return the finished templates - return finishedTemplates; -} diff --git a/node_modules/reg/node_modules/mongodb/dev/tools/gleak.js b/node_modules/reg/node_modules/mongodb/dev/tools/gleak.js deleted file mode 100644 index 0a1bc6d..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/tools/gleak.js +++ /dev/null @@ -1,5 +0,0 @@ - -var gleak = require('../../deps/gleak')(); -gleak.ignore('AssertionError'); - -module.exports = gleak; diff --git a/node_modules/reg/node_modules/mongodb/dev/tools/test_all.js b/node_modules/reg/node_modules/mongodb/dev/tools/test_all.js deleted file mode 100644 index 6fa8918..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/tools/test_all.js +++ /dev/null @@ -1,176 +0,0 @@ -var nodeunit = require('../../deps/nodeunit'), - debug = require('util').debug, - inspect = require('util').inspect, - fs = require('fs'), - exec = require('child_process').exec, - spawn = require('child_process').spawn, - Step = require('../../deps/step/lib/step'), - ServerManager = require('../../test/tools/server_manager').ServerManager, - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager; - -// Manage the test server -var serverManager = new ServerManager(); -var replicaSetManager = new ReplicaSetManager(); -// test directories -var files = []; -var directories = [{dir: __dirname + "/../../test", path: "/test/"}, - {dir: __dirname + "/../../test/gridstore", path: "/test/gridstore/"}, - {dir: __dirname + "/../../test/connection", path: "/test/connection/"}, - {dir: __dirname + "/../../test/bson", path: "/test/bson/"}]; - -// Generate a list of tests -directories.forEach(function(dirEntry) { - // Add the files - files = files.concat(fs.readdirSync(dirEntry.dir).filter(function(item) { - return /_test\.js$/i.test(item); - }).map(function(file) { - return dirEntry.path + file; - })); -}); - -// Replicasetfiles -var replicasetFiles = fs.readdirSync(__dirname + "/../../test/replicaset").filter(function(item) { - return /_test\.js$/i.test(item); -}).map(function(file) { - return "/test/replicaset/" + file; -}); - -var specifedParameter = function(arguments, param) { - for(var i = 0; i < arguments.length; i++) { - if(arguments[i] == param) return true; - } - return false; -} - -// Different options -var junit = specifedParameter(process.argv, '--junit', false); -var noReplicaSet = specifedParameter(process.argv, '--noreplicaset', false); -var boot = specifedParameter(process.argv, '--boot', false); -// Basic default test runner -var runner = nodeunit.reporters.default; -var options = { error_prefix: '\u001b[31m', - error_suffix: '\u001b[39m', - ok_prefix: '\u001b[32m', - ok_suffix: '\u001b[39m', - bold_prefix: '\u001b[1m', - bold_suffix: '\u001b[22m', - assertion_prefix: '\u001b[35m', - assertion_suffix: '\u001b[39m' }; - -// cleanup output directory -exec('rm -rf ./output', function(err, stdout, stderr) { - // if we have a junit reporter - if(junit) { - // Remove directory - fs.mkdirSync("./output", 0777); - // Set up options - options.output = './output'; - options.junit = true; - } - - // Run all tests including replicaset ones - if(!noReplicaSet) { - // Boot up the test server and run the tests - Step( - // Start the single server - function startSingleServer() { - if(boot) { - serverManager.start(true, {purgedirectories:true}, this); - } else { - this(null, null); - } - }, - - // Run all the integration tests using the pure js bson parser - function runPureJS() { - options.suffix = 'pure'; - var test_set_runner = spawn('node', ['./dev/tools/test_set_runner.js', JSON.stringify(files), JSON.stringify(options)]); - test_set_runner.stdout.on('data', function(data) { - process.stdout.write(data.toString()); - }); - test_set_runner.stderr.on('data', function(data) { - process.stdout.write("err: " + data.toString()); - }); - - test_set_runner.on('exit', this); - }, - - // Execute all the replicaset tests - function executeReplicaSetTests() { - options.suffix = 'pure'; - var test_set_runner = spawn('node', ['./dev/tools/test_set_runner.js', JSON.stringify(replicasetFiles), JSON.stringify(options)]); - test_set_runner.stdout.on('data', function(data) { - process.stdout.write(data.toString()); - }); - test_set_runner.stderr.on('data', function(data) { - process.stdout.write("err: " + data.toString()); - }); - - test_set_runner.on('exit', this); - }, - - function done() { - if(boot) { - // Kill all mongod server - replicaSetManager.killAll(function() { - // Force exit - process.exit(); - }) - } else { - process.exit(); - } - } - ); - } else { - // Execute without replicaset tests - Step( - function startSingleServer() { - if(boot) { - serverManager.start(true, {purgedirectories:true}, this); - } else { - this(null, null); - } - }, - - function runPureJS() { - options.suffix = 'pure'; - var test_set_runner = spawn('node', ['./dev/tools/test_set_runner.js', JSON.stringify(files), JSON.stringify(options)]); - test_set_runner.stdout.on('data', function(data) { - process.stdout.write(data.toString()); - }); - test_set_runner.stderr.on('data', function(data) { - process.stdout.write("err: " + data.toString()); - }); - - test_set_runner.on('exit', this); - }, - - function runNativeJS() { - options.suffix = 'native'; - options.native = true; - - var test_set_runner = spawn('node', ['./dev/tools/test_set_runner.js', JSON.stringify(files), JSON.stringify(options)]); - test_set_runner.stdout.on('data', function(data) { - process.stdout.write(data.toString()); - }); - test_set_runner.stderr.on('data', function(data) { - process.stdout.write("err: " + data.toString()); - }); - - test_set_runner.on('exit', this); - }, - - function done() { - if(boot) { - // Kill all mongod server - replicaSetManager.killAll(function() { - // Force exit - process.exit(); - }) - } else { - process.exit(); - } - } - ); - } -}); diff --git a/node_modules/reg/node_modules/mongodb/dev/tools/test_set_runner.js b/node_modules/reg/node_modules/mongodb/dev/tools/test_set_runner.js deleted file mode 100644 index 6cfb6b1..0000000 --- a/node_modules/reg/node_modules/mongodb/dev/tools/test_set_runner.js +++ /dev/null @@ -1,27 +0,0 @@ -var nodeunit = require('../../deps/nodeunit'); - -// Let's parse the argv (ensure we have all the number of parameters) -if(process.argv.length === 4) { - // Pop the arguments off - var options = JSON.parse(process.argv.pop()); - var files = JSON.parse(process.argv.pop()); - - // Basic default test runner - var runner = options['junit'] == true ? nodeunit.reporters.junit : nodeunit.reporters.default; - var nativeExecution = options['native'] == null ? false : options['native']; - // Remove junit tag if it exists - delete options['junit']; - delete options['native']; - - // Set native process - if(nativeExecution) { - process.env['TEST_NATIVE'] = 'TRUE'; - } - - // Let's set up nodeunit to run - runner.run(files, options, function() { - process.exit(0); - }); -} else { - console.error("Must pass in a list of files and options object"); -} diff --git a/node_modules/reg/node_modules/mongodb/docs/sphinx-docs/build/html/.buildinfo b/node_modules/reg/node_modules/mongodb/docs/sphinx-docs/build/html/.buildinfo deleted file mode 100644 index c99c1eb..0000000 --- a/node_modules/reg/node_modules/mongodb/docs/sphinx-docs/build/html/.buildinfo +++ /dev/null @@ -1,4 +0,0 @@ -# Sphinx build info version 1 -# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: c17150b5838a3e308c3c7bec6e59b487 -tags: fbb0d17656682115ca4d033fb2f83ba1 diff --git a/node_modules/reg/node_modules/mongodb/docs/sphinx-docs/build/singlehtml/.buildinfo b/node_modules/reg/node_modules/mongodb/docs/sphinx-docs/build/singlehtml/.buildinfo deleted file mode 100644 index 0885fbe..0000000 --- a/node_modules/reg/node_modules/mongodb/docs/sphinx-docs/build/singlehtml/.buildinfo +++ /dev/null @@ -1,4 +0,0 @@ -# Sphinx build info version 1 -# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: -tags: diff --git a/node_modules/reg/node_modules/mongodb/docs/sphinx-docs/source/static/.mongodb b/node_modules/reg/node_modules/mongodb/docs/sphinx-docs/source/static/.mongodb deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/reg/node_modules/mongodb/docs/sphinx-docs/templates/.mongodb b/node_modules/reg/node_modules/mongodb/docs/sphinx-docs/templates/.mongodb deleted file mode 100644 index e69de29..0000000 diff --git a/node_modules/reg/node_modules/mongodb/examples/admin.js b/node_modules/reg/node_modules/mongodb/examples/admin.js deleted file mode 100644 index 2619e7e..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/admin.js +++ /dev/null @@ -1,53 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropDatabase(function(err, result){ - db.dropCollection('test', function(err, result) { - db.createCollection('test', function(err, collection) { - - // Erase all records in collection - collection.remove({}, function(err, r) { - db.admin(function(err, admin) { - - // Profiling level set/get - admin.profilingLevel(function(err, profilingLevel) { - console.log("Profiling level: " + profilingLevel); - }); - - // Start profiling everything - admin.setProfilingLevel('all', function(err, level) { - console.log("Profiling level: " + level); - - // Read records, creating a profiling event - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - // Stop profiling - admin.setProfilingLevel('off', function(err, level) { - // Print all profiling info - admin.profilingInfo(function(err, info) { - console.dir(info); - - // Validate returns a hash if all is well or return an error hash if there is a - // problem. - admin.validateCollection(collection.collectionName, function(err, result) { - console.dir(result); - db.close(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/blog.js b/node_modules/reg/node_modules/mongodb/examples/blog.js deleted file mode 100644 index ff9c16b..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/blog.js +++ /dev/null @@ -1,102 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -var LINE_SIZE = 120; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-blog', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropDatabase(function(err, result) { - console.log("==================================================================================="); - console.log(">> Adding Authors"); - db.collection('authors', function(err, collection) { - collection.createIndex(["meta", ['_id', 1], ['name', 1], ['age', 1]], function(err, indexName) { - console.log("==================================================================================="); - var authors = {}; - - // Insert authors - collection.insert([{'name':'William Shakespeare', 'email':'william@shakespeare.com', 'age':587}, - {'name':'Jorge Luis Borges', 'email':'jorge@borges.com', 'age':123}], function(err, docs) { - docs.forEach(function(doc) { - console.dir(doc); - authors[doc.name] = doc; - }); - }); - - console.log("==================================================================================="); - console.log(">> Authors ordered by age ascending"); - console.log("==================================================================================="); - collection.find({}, {'sort':[['age', 1]]}, function(err, cursor) { - cursor.each(function(err, author) { - if(author != null) { - console.log("[" + author.name + "]:[" + author.email + "]:[" + author.age + "]"); - } else { - console.log("==================================================================================="); - console.log(">> Adding users"); - console.log("==================================================================================="); - db.collection('users', function(err, userCollection) { - var users = {}; - - userCollection.insert([{'login':'jdoe', 'name':'John Doe', 'email':'john@doe.com'}, - {'login':'lsmith', 'name':'Lucy Smith', 'email':'lucy@smith.com'}], function(err, docs) { - docs.forEach(function(doc) { - console.dir(doc); - users[doc.login] = doc; - }); - }); - - console.log("==================================================================================="); - console.log(">> Users ordered by login ascending"); - console.log("==================================================================================="); - userCollection.find({}, {'sort':[['login', 1]]}, function(err, cursor) { - cursor.each(function(err, user) { - if(user != null) { - console.log("[" + user.login + "]:[" + user.name + "]:[" + user.email + "]"); - } else { - console.log("==================================================================================="); - console.log(">> Adding articles"); - console.log("==================================================================================="); - db.collection('articles', function(err, articlesCollection) { - articlesCollection.insert([ - { 'title':'Caminando por Buenos Aires', - 'body':'Las callecitas de Buenos Aires tienen ese no se que...', - 'author_id':authors['Jorge Luis Borges']._id}, - { 'title':'I must have seen thy face before', - 'body':'Thine eyes call me in a new way', - 'author_id':authors['William Shakespeare']._id, - 'comments':[{'user_id':users['jdoe']._id, 'body':"great article!"}] - } - ], function(err, docs) { - docs.forEach(function(doc) { - console.dir(doc); - }); - }) - - console.log("==================================================================================="); - console.log(">> Articles ordered by title ascending"); - console.log("==================================================================================="); - articlesCollection.find({}, {'sort':[['title', 1]]}, function(err, cursor) { - cursor.each(function(err, article) { - if(article != null) { - console.log("[" + article.title + "]:[" + article.body + "]:[" + article.author_id.toHexString() + "]"); - console.log(">> Closing connection"); - db.close(); - } - }); - }); - }); - } - }); - }); - }); - } - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/capped.js b/node_modules/reg/node_modules/mongodb/examples/capped.js deleted file mode 100644 index fb98911..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/capped.js +++ /dev/null @@ -1,27 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropCollection('test', function(err, result) { - // A capped collection has a max size and optionally a max number of records. - // Old records get pushed out by new ones once the size or max num records is - // reached. - db.createCollection('test', {'capped':true, 'size':1024, 'max':12}, function(err, collection) { - for(var i = 0; i < 100; i++) { collection.insert({'a':i}); } - - // We will only see the last 12 records - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - console.log("The number of records: " + items.length); - db.close(); - }) - }) - }); - }); -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/cursor.js b/node_modules/reg/node_modules/mongodb/examples/cursor.js deleted file mode 100644 index cd5c5f3..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/cursor.js +++ /dev/null @@ -1,70 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.collection('test', function(err, collection) { - // Erase all records from collection, if any - collection.remove(function(err, result) { - - // Insert 3 records - for(var i = 0; i < 3; i++) { - collection.insert({'a':i}); - } - - // Cursors don't run their queries until you actually attempt to retrieve data - // from them. - - // Find returns a Cursor, which is Enumerable. You can iterate: - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) console.dir(item); - }); - }); - - // You can turn it into an array - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - console.log("count: " + items.length); - }); - }); - - // You can iterate after turning it into an array (the cursor will iterate over - // the copy of the array that it saves internally.) - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - cursor.each(function(err, item) { - if(item != null) console.dir(item); - }); - }); - }); - - // You can get the next object - collection.find(function(err, cursor) { - cursor.nextObject(function(err, item) { - if(item != null) console.dir(item); - }); - }); - - // next_object returns null if there are no more objects that match - collection.find(function(err, cursor) { - cursor.nextObject(function(err, item) { - cursor.nextObject(function(err, item) { - cursor.nextObject(function(err, item) { - cursor.nextObject(function(err, item) { - console.log("nextObject returned: "); - console.dir(item); - db.close(); - }); - }); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/gridfs.js b/node_modules/reg/node_modules/mongodb/examples/gridfs.js deleted file mode 100644 index 359af25..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/gridfs.js +++ /dev/null @@ -1,149 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - GridStore = require('../lib/mongodb').GridStore; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log(">> Connecting to " + host + ":" + port); -var db1 = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db1.open(function(err, db) { - // Write a new file - var gridStore = new GridStore(db, "foobar", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - // Read the file and dump the contents - dump(db, 'foobar'); - - // Append more data - gridStore = new GridStore(db, 'foobar', "w+"); - gridStore.open(function(err, gridStore) { - gridStore.write('\n', function(err, gridStore) { - gridStore.puts('line two', function(err, gridStore) { - gridStore.close(function(err, result) { - dump(db, 'foobar'); - - // Overwrite - gridStore = new GridStore(db, 'foobar', "w"); - gridStore.open(function(err, gridStore) { - gridStore.write('hello, sailor!', function(err, gridStore) { - gridStore.close(function(err, result) { - dump(db, 'foobar', function() { - db.close(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -}); - -var db2 = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db2.open(function(err, db) { - // File existence tests - var gridStore = new GridStore(db, "foobar2", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write( 'hello sailor', function(err, gridStore) { - gridStore.close(function(err, result) { - GridStore.exist(db, 'foobar2', function(err, result) { - console.log("File 'foobar2' exists: " + result); - }); - - GridStore.exist(db, 'does-not-exist', function(err, result) { - console.log("File 'does-not-exist' exists: " + result); - }); - - // Read with offset(uses seek) - GridStore.read(db, 'foobar2', 6, 7, function(err, data) { - console.log(data); - }); - - // Rewind/seek/tell - var gridStore2 = new GridStore(db, 'foobar2', 'w'); - gridStore2.open(function(err, gridStore) { - gridStore.write('hello, world!', function(err, gridStore){}); - gridStore.rewind(function(){}); - gridStore.write('xyzzz', function(err, gridStore){}); - gridStore.tell(function(tell) { - console.log("tell: " + tell); // Should be 5 - }); - gridStore.seek(4, function(err, gridStore){}); - gridStore.write('y', function(){}); - gridStore.close(function() { - dump(db, 'foobar2'); - - // Unlink file (delete) - GridStore.unlink(db, 'foobar2', function(err, gridStore) { - GridStore.exist(db, 'foobar2', function(err, result) { - console.log("File 'foobar2' exists: " + result); - db.close(); - }); - }); - }); - }); - }); - }); - }); -}); - -var db3 = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db3.open(function(err, db) { - // Metadata - var gridStore = new GridStore(db, "foobar3", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write('hello, world!', function(err, gridStore){}); - gridStore.close(function(err, gridStore) { - gridStore = new GridStore(db, 'foobar3', "r"); - gridStore.open(function(err, gridStore) { - console.log("contentType: " + gridStore.contentType); - console.log("uploadDate: " + gridStore.uploadDate); - console.log("chunkSize: " + gridStore.chunkSize); - console.log("metadata: " + gridStore.metadata); - }); - - // Add some metadata - gridStore = new GridStore(db, 'foobar3', "w+"); - gridStore.open(function(err, gridStore) { - gridStore.contentType = 'text/xml'; - gridStore.metadata = {'a':1}; - gridStore.close(function(err, gridStore) { - // Print the metadata - gridStore = new GridStore(db, 'foobar3', "r"); - gridStore.open(function(err, gridStore) { - console.log("contentType: " + gridStore.contentType); - console.log("uploadDate: " + gridStore.uploadDate); - console.log("chunkSize: " + gridStore.chunkSize); - console.log("metadata: " + gridStore.metadata); - db.close(); - }); - }); - }); - }); - }); - - // You can also set meta data when initially writing to a file - // setting root means that the file and its chunks are stored in a different root - // collection: instead of gridfs.files and gridfs.chunks, here we use - // my_files.files and my_files.chunks - var gridStore = new GridStore(db, "foobar3", "w", {'content_type':'text/plain', - 'metadata':{'a':1}, 'chunk_size': 1024*4, 'root':'my_files'}); - gridStore.open(function(err, gridStore) { - gridStore.write('hello, world!', function(err, gridStore){}); - gridStore.close(function() { - }); - }); -}); - -function dump(db, filename, callback) { - GridStore.read(db, filename, function(err, data) { - console.log(data); - if(callback != null) callback(); - }); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/index.js b/node_modules/reg/node_modules/mongodb/examples/index.js deleted file mode 100644 index 73d3348..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/index.js +++ /dev/null @@ -1,62 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - mongo = require('../lib/mongodb'); - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log(">> Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - console.log(">> Dropping collection test"); - db.dropCollection('test', function(err, result) { - console.log("dropped: "); - console.dir(result); - }); - - console.log(">> Creating collection test"); - db.collection('test', function(err, collection) { - console.log("created: "); - console.dir(collection); - - var objectCount = 100; - var objects = []; - var messages = ["hola", "hello", "aloha", "ciao"]; - console.log(">> Generate test data"); - for(var i = 0; i < objectCount; i++) { - objects.push({'number':i, 'rndm':((5*Math.random()) + 1), 'msg':messages[parseInt(4*Math.random())]}) - } - console.log("generated"); - - console.log(">> Inserting data (" + objects.length + ")"); - collection.insert(objects); - console.log("inserted"); - - console.log(">> Creating index") - collection.createIndex([['all'], ['_id', 1], ['number', 1], ['rndm', 1], ['msg', 1]], function(err, indexName) { - console.log("created index: " + indexName); - - console.log(">> Gathering index information"); - - collection.indexInformation(function(err, doc) { - console.log("indexInformation: "); - console.dir(doc); - - console.log(">> Dropping index"); - collection.dropIndex('all_1__id_1_number_1_rndm_1_msg_1', function(err, result) { - console.log("dropped: "); - console.dir(result); - - console.log(">> Gathering index information"); - collection.indexInformation(function(err, doc) { - console.log("indexInformation: "); - console.dir(doc); - console.log(">> Closing connection"); - db.close(); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/info.js b/node_modules/reg/node_modules/mongodb/examples/info.js deleted file mode 100644 index 54ca60c..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/info.js +++ /dev/null @@ -1,48 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.collection('test', function(err, collection) { - - // Remove all existing documents in collection - collection.remove(function(err, result) { - - // Insert 3 records - for(var i = 0; i < 3; i++) { - collection.insert({'a':i}); - } - - // Show collection names in the database - db.collectionNames(function(err, names) { - names.forEach(function(name) { - console.dir(name); - }); - }); - - // More information about each collection - db.collectionsInfo(function(err, cursor) { - cursor.toArray(function(err, items) { - items.forEach(function(item) { - console.dir(item); - }); - }); - }) - - // Index information - db.createIndex('test', 'a', function(err, indexName) { - db.indexInformation('test', function(err, doc) { - console.dir(doc); - collection.drop(function(err, result) { - db.close(); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/oplog.js b/node_modules/reg/node_modules/mongodb/examples/oplog.js deleted file mode 100644 index 4441a61..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/oplog.js +++ /dev/null @@ -1,114 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - Cursor = require('../lib/mongodb').Cursor; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -Slave = function() { - this.running = false; - this.callbacks = []; - //no native_parser right now (because timestamps) - //no strict mode (because system db signed with $ db.js line 189) - //connect without dbName for querying not only "local" db - console.log("Connecting to " + host + ":" + port); - this.db = new Db('testing', new Server(host, port, {}), {}); -} - -//start watching -Slave.prototype.start = function() { - var self = this; - if (this.running) return; - - this.db.open(function(err, db) { - if (err) { - console.log('> MongoSlave error' + err); - process.exit(1); - } - - db.collection('local.oplog.$main', function(err, collection) { - if (! collection) { - console.log('> MongoSlave - local.oplog.$main not found'); - self.stop(); - return false; - } - - process.on('SIGINT', function () { - self.stop(); //tailable cursor should be stopped manually - }); - - //get last row for init TS - collection.find({}, {'limit': 1, 'sort': [['$natural', -1]]}, function(err, cursor) { - cursor.toArray(function(err, items) { - if (items.length) { - console.log('> MongoSlave started'); - self.running = true; - self._runSlave(collection, items[0]['ts']); - } else if (err) { - console.log(err); - self.stop(); - } - }); - }); - }); - }); -} - -//stop watching -Slave.prototype.stop = function() { - if (!this.running) return; - console.log('> MongoSlave stopped'); - this.running = false; - this.db.close(); -} - -Slave.prototype._runSlave = function(collection, time) { - - var self = this; - - //watch oplog INFINITE (until Slave.stop()) - collection.find({'ts': {'$gt': time}}, {'tailable': 1, 'sort': [['$natural', 1]]}, function(err, cursor) { - cursor.each(function(err, item) { - if (cursor.state == Cursor.CLOSED) { //broken cursor - self.running && self._runSlave(collection, time); - return; - } - time = item['ts']; - - switch(item['op']) { - case 'i': //inserted - self._emitObj(item['o']); - break; - case 'u': //updated - self.db.collection(item['ns'], function(err, collection) { - collection.findOne(item['o2']['_id'], {}, function(err, item) { - item && self._emitObj(item); - }); - }); - break; - case 'd': //deleted - //nothing to do - break; - } - }); - }); -} - -Slave.prototype._emitObj = function (obj) { - for(var i in this.callbacks) this.callbacks[i].call(this, obj); -} - -Slave.prototype.onObject = function(callback) { - this.callbacks.push(callback); -} - - -//just for example -var watcher = new Slave(); - -watcher.onObject(function(obj) { - console.dir(obj); -}); - -watcher.start(); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/queries.js b/node_modules/reg/node_modules/mongodb/examples/queries.js deleted file mode 100644 index 19cc473..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/queries.js +++ /dev/null @@ -1,125 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); - -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropDatabase(function() { - // Fetch the collection test - db.collection('test', function(err, collection) { - // Remove all records in collection if any - collection.remove(function(err, result) { - // Insert three records - collection.insert([{'a':1}, {'a':2}, {'b':3}], function(docs) { - // Count the number of records - collection.count(function(err, count) { - console.log("There are " + count + " records."); - }); - - // Find all records. find() returns a cursor - collection.find(function(err, cursor) { - // Print each row, each document has an _id field added on insert - // to override the basic behaviour implement a primary key factory - // that provides a 12 byte value - console.log("Printing docs from Cursor Each") - cursor.each(function(err, doc) { - if(doc != null) console.log("Doc from Each "); - console.dir(doc); - }) - }); - // Cursor has an to array method that reads in all the records to memory - collection.find(function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Printing docs from Array") - docs.forEach(function(doc) { - console.log("Doc from Array "); - console.dir(doc); - }); - }); - }); - - // Different methods to access records (no printing of the results) - - // Locate specific document by key - collection.find({'a':1}, function(err, cursor) { - cursor.nextObject(function(err, doc) { - console.log("Returned #1 documents"); - }); - }); - - // Find records sort by 'a', skip 1, limit 2 records - // Sort can be a single name, array, associate array or ordered hash - collection.find({}, {'skip':1, 'limit':1, 'sort':'a'}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }) - }); - - // Find all records with 'a' > 1, you can also use $lt, $gte or $lte - collection.find({'a':{'$gt':1}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - collection.find({'a':{'$gt':1, '$lte':3}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Find all records with 'a' in a set of values - collection.find({'a':{'$in':[1,2]}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Find by regexp - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Print Query explanation - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - }) - }); - - // Use a hint with a query, hint's can also be store in the collection - // and will be applied to each query done through the collection. - // Hint's can also be specified by query which will override the - // hint's associated with the collection - collection.createIndex('a', function(err, indexName) { - collection.hint = 'a'; - - // You will see a different explanation now that the hint was set - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - }) - }); - - collection.find({'a':/[1|2]/}, {'hint':'a'}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - db.close(); - }) - }); - }); - }); - }); - }); - }); -}); diff --git a/node_modules/reg/node_modules/mongodb/examples/replSetServersQueries.js b/node_modules/reg/node_modules/mongodb/examples/replSetServersQueries.js deleted file mode 100644 index ab82ac6..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/replSetServersQueries.js +++ /dev/null @@ -1,138 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - ReplSetServers = require('../lib/mongodb').ReplSetServers; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -var port1 = 27018; -var port2 = 27019; -var server = new Server(host, port, {}); -var server1 = new Server(host, port1, {}); -var server2 = new Server(host, port2, {}); -var servers = new Array(); -servers[0] = server2; -servers[1] = server1; -servers[2] = server; - -var replStat = new ReplSetServers(servers); -console.log("Connecting to " + host + ":" + port); -console.log("Connecting to " + host1 + ":" + port1); -console.log("Connecting to " + host2 + ":" + port2); -var db = new Db('node-mongo-examples', replStat, {native_parser:true}); -db.open(function(err, db) { - db.dropDatabase(function() { - // Fetch the collection test - db.collection('test', function(err, collection) { - // Remove all records in collection if any - collection.remove(function(err, collection) { - // Insert three records - collection.insert([{'a':1}, {'a':2}, {'b':3}], function(docs) { - // Count the number of records - collection.count(function(err, count) { - console.log("There are " + count + " records."); - }); - - // Find all records. find() returns a cursor - collection.find(function(err, cursor) { - // Print each row, each document has an _id field added on insert - // to override the basic behaviour implement a primary key factory - // that provides a 12 byte value - console.log("Printing docs from Cursor Each") - cursor.each(function(err, doc) { - if(doc != null) console.log("Doc from Each "); - console.dir(doc); - }) - }); - // Cursor has an to array method that reads in all the records to memory - collection.find(function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Printing docs from Array") - docs.forEach(function(doc) { - console.log("Doc from Array "); - console.dir(doc); - }); - }); - }); - - // Different methods to access records (no printing of the results) - - // Locate specific document by key - collection.find({'a':1}, function(err, cursor) { - cursor.nextObject(function(err, doc) { - console.log("Returned #1 documents"); - }); - }); - - // Find records sort by 'a', skip 1, limit 2 records - // Sort can be a single name, array, associate array or ordered hash - collection.find({}, {'skip':1, 'limit':1, 'sort':'a'}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }) - }); - - // Find all records with 'a' > 1, you can also use $lt, $gte or $lte - collection.find({'a':{'$gt':1}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - collection.find({'a':{'$gt':1, '$lte':3}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Find all records with 'a' in a set of values - collection.find({'a':{'$in':[1,2]}}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Find by regexp - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.toArray(function(err, docs) { - console.log("Returned #" + docs.length + " documents"); - }); - }); - - // Print Query explanation - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - }) - }); - - // Use a hint with a query, hint's can also be store in the collection - // and will be applied to each query done through the collection. - // Hint's can also be specified by query which will override the - // hint's associated with the collection - collection.createIndex('a', function(err, indexName) { - collection.hint = 'a'; - - // You will see a different explanation now that the hint was set - collection.find({'a':/[1|2]/}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - }) - }); - - collection.find({'a':/[1|2]/}, {'hint':'a'}, function(err, cursor) { - cursor.explain(function(err, doc) { - console.log("-------------------------- Explanation"); - console.dir(doc); - db.close(); - }) - }); - }); - }); - }); - }); - }); -}); diff --git a/node_modules/reg/node_modules/mongodb/examples/replSetServersSimple.js b/node_modules/reg/node_modules/mongodb/examples/replSetServersSimple.js deleted file mode 100644 index 9ca3f3f..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/replSetServersSimple.js +++ /dev/null @@ -1,66 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Admin = require('../lib/mongodb').Admin, - DbCommand = require('../lib/mongodb/commands/db_command').DbCommand, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - ReplSetServers = require('../lib/mongodb').ReplSetServers, - CheckMaster = require('../lib/mongodb').CheckMaster; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -var port1 = 27018; -var port2 = 27019; - - -console.log("Connecting to " + host + ":" + port); -console.log("Connecting to " + host + ":" + port1); -console.log("Connecting to " + host + ":" + port2); - -var server = new Server(host, port, {}); -var server1 = new Server(host, port1, {}); -var server2 = new Server(host, port2, {}); -var servers = new Array(); -servers[0] = server2; -servers[1] = server1; -servers[2] = server; - -var replStat = new ReplSetServers(servers); - -var db = new Db('mongo-example', replStat, {native_parser:true}); -db.open(function(err, db) { - - db.dropDatabase(function(err, result) { - db.collection('test', function(err, collection) { - collection.remove(function(err, collection) { - // Insert 3 records - for(var i = 0; i < 3; i++) { - collection.insert({'a':i}); - } - - collection.count(function(err, count) { - console.log("There are " + count + " records in the test collection. Here they are:"); - - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - console.dir(item); - console.log("created at " + new Date(item._id.generationTime) + "\n") - } - // Null signifies end of iterator - if(item == null) { - // Destory the collection - collection.drop(function(err, collection) { - db.close(); - }); - } - }); - }); - }); - }); - }); - }); -}); - - - diff --git a/node_modules/reg/node_modules/mongodb/examples/simple.js b/node_modules/reg/node_modules/mongodb/examples/simple.js deleted file mode 100644 index 9bcdf25..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/simple.js +++ /dev/null @@ -1,42 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropDatabase(function(err, result) { - db.collection('test', function(err, collection) { - // Erase all records from the collection, if any - collection.remove({}, function(err, result) { - // Insert 3 records - for(var i = 0; i < 3; i++) { - collection.insert({'a':i}); - } - - collection.count(function(err, count) { - console.log("There are " + count + " records in the test collection. Here they are:"); - - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - console.dir(item); - console.log("created at " + new Date(item._id.generationTime) + "\n") - } - // Null signifies end of iterator - if(item == null) { - // Destory the collection - collection.drop(function(err, collection) { - db.close(); - }); - } - }); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/strict.js b/node_modules/reg/node_modules/mongodb/examples/strict.js deleted file mode 100644 index 45c739c..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/strict.js +++ /dev/null @@ -1,36 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); -db.open(function(err, db) { - db.dropCollection('does-not-exist', function(err, result) { - db.createCollection('test', function(err, collection) { - db.strict = true; - - // Can't reference collections that does not exist in strict mode - db.collection('does-not-exist', function(err, collection) { - if(err instanceof Error) { - console.log("expected error: " + err.message); - } - - // Can't create collections that does not exist in strict mode - db.createCollection('test', function(err, collection) { - if(err instanceof Error) { - console.log("expected error: " + err.message); - } - - // Remove the strict mode - db.strict = false; - db.dropCollection('test', function(err, collection) { - db.close(); - }); - }); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/types.js b/node_modules/reg/node_modules/mongodb/examples/types.js deleted file mode 100644 index efff89a..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/types.js +++ /dev/null @@ -1,42 +0,0 @@ -var Db = require('../lib/mongodb').Db, - Connection = require('../lib/mongodb').Connection, - Server = require('../lib/mongodb').Server, - BSON = require('../lib/mongodb').BSONPure; - -var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; -var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; - -console.log("Connecting to " + host + ":" + port); -var db = new Db('node-mongo-examples', new Server(host, port, {}), {}); -db.open(function(err, db) { - db.collection('test', function(err, collection) { - // Remove all existing documents in collection - collection.remove(function(err, result) { - // Insert record with all the available types of values - collection.insert({ - 'array':[1,2,3], - 'string':'hello', - 'hash':{'a':1, 'b':2}, - 'date':new Date(), // Stores only milisecond resolution - 'oid':new BSON.ObjectID(), - 'binary':new BSON.Binary("123"), - 'int':42, - 'float':33.3333, - 'regexp':/foobar/i, - 'regexp2':/foobar2/, - 'boolean':true, - 'where':new BSON.Code('this.x == 3'), - 'dbref':new BSON.DBRef(collection.collectionName, new BSON.ObjectID()), - 'null':null - }, function(err, doc) { - // Locate the first document - collection.findOne(function(err, document) { - console.dir(document); - collection.remove(function(err, collection) { - db.close(); - }); - }) - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/examples/url.js b/node_modules/reg/node_modules/mongodb/examples/url.js deleted file mode 100644 index b04c29f..0000000 --- a/node_modules/reg/node_modules/mongodb/examples/url.js +++ /dev/null @@ -1,12 +0,0 @@ -var Db = require('../lib/mongodb').Db, - connect = require('../lib/mongodb').connect; - -console.log('Connecting to ' + Db.DEFAULT_URL); -connect(Db.DEFAULT_URL, function(err, db) { - db.dropDatabase(function(err, result) { - db.collection('test', function(err, collection) { - collection.insert({'a':1}); - db.close(); - }); - }); -}); diff --git a/node_modules/reg/node_modules/mongodb/lib/mongodb/admin.js b/node_modules/reg/node_modules/mongodb/lib/mongodb/admin.js index e85bcae..89ca706 100644 --- a/node_modules/reg/node_modules/mongodb/lib/mongodb/admin.js +++ b/node_modules/reg/node_modules/mongodb/lib/mongodb/admin.js @@ -141,17 +141,26 @@ Admin.prototype.logout = function(callback) { * Add a user to the MongoDB server, if the user exists it will * overwrite the current password * + * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. + * * @param {String} username The user name for the authentication. * @param {String} password The password for the authentication. + * @param {Object} [options] additional options during update. * @param {Function} callback Callback function of format `function(err, result) {}`. * @return {null} Returns no result * @api public */ -Admin.prototype.addUser = function(username, password, callback) { +Admin.prototype.addUser = function(username, password, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() : {}; + var self = this; var databaseName = this.db.databaseName; this.db.databaseName = 'admin'; - this.db.addUser(username, password, function(err, result) { + this.db.addUser(username, password, options, function(err, result) { self.db.databaseName = databaseName; return callback(err, result); }) @@ -160,16 +169,25 @@ Admin.prototype.addUser = function(username, password, callback) { /** * Remove a user from the MongoDB server * + * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. + * * @param {String} username The user name for the authentication. + * @param {Object} [options] additional options during update. * @param {Function} callback Callback function of format `function(err, result) {}`. * @return {null} Returns no result * @api public */ -Admin.prototype.removeUser = function(username, callback) { +Admin.prototype.removeUser = function(username, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + var self = this; var databaseName = this.db.databaseName; this.db.databaseName = 'admin'; - this.db.removeUser(username, function(err, result) { + this.db.removeUser(username, options, function(err, result) { self.db.databaseName = databaseName; return callback(err, result); }) diff --git a/node_modules/reg/node_modules/mongodb/lib/mongodb/collection.js b/node_modules/reg/node_modules/mongodb/lib/mongodb/collection.js index c9e883e..f875bd3 100644 --- a/node_modules/reg/node_modules/mongodb/lib/mongodb/collection.js +++ b/node_modules/reg/node_modules/mongodb/lib/mongodb/collection.js @@ -899,6 +899,11 @@ Collection.prototype.findOne = function findOne () { * @api public */ Collection.prototype.createIndex = function createIndex (fieldOrSpec, options, callback) { + // Clean up call + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + // Execute create index this.db.createIndex(this.collectionName, fieldOrSpec, options, callback); }; @@ -921,6 +926,11 @@ Collection.prototype.createIndex = function createIndex (fieldOrSpec, options, c * @api public */ Collection.prototype.ensureIndex = function ensureIndex (fieldOrSpec, options, callback) { + // Clean up call + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + // Execute create index this.db.ensureIndex(this.collectionName, fieldOrSpec, options, callback); }; @@ -1020,10 +1030,10 @@ Collection.prototype.reIndex = function(callback) { */ Collection.prototype.mapReduce = function mapReduce (map, reduce, options, callback) { if ('function' === typeof options) callback = options, options = {}; - - // Set default to go to the inline table otherwise it will break against - // previous versions of mongodb - if(null == options.out) options.out = "inline"; + // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers) + if(null == options.out) { + throw new Error("the out option parameter must be defined, see mongodb docs for possible values"); + } if ('function' === typeof map) { map = map.toString(); diff --git a/node_modules/reg/node_modules/mongodb/lib/mongodb/db.js b/node_modules/reg/node_modules/mongodb/lib/mongodb/db.js index f34b4b0..ec6a5d8 100644 --- a/node_modules/reg/node_modules/mongodb/lib/mongodb/db.js +++ b/node_modules/reg/node_modules/mongodb/lib/mongodb/db.js @@ -605,13 +605,29 @@ Db.prototype.authenticate = function(username, password, callback) { /** * Add a user to the database. * + * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. + * * @param {String} username username. * @param {String} password password. + * @param {Object} [options] additional options during update. * @param {Function} callback returns the results. * @return {null} * @api public */ -Db.prototype.addUser = function(username, password, callback) { +Db.prototype.addUser = function(username, password, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + // Figure out the safe mode settings + var safe = self.strict != null && self.strict == false ? true : self.strict; + // Override with options passed in if applicable + safe = options != null && options['safe'] != null ? options['safe'] : safe; + // Ensure it's at least set to safe + safe = safe == null ? true : safe; + // Use node md5 generator var md5 = crypto.createHash('md5'); // Generate keys used for authentication @@ -624,11 +640,11 @@ Db.prototype.addUser = function(username, password, callback) { if(err != null) return callback(err, null); // We have a user, let's update the password if(documents.length > 0) { - collection.update({user: username},{user: username, pwd: userPassword}, {safe:true}, function(err, results) { + collection.update({user: username},{user: username, pwd: userPassword}, {safe:safe}, function(err, results) { callback(err, documents); }); } else { - collection.insert({user: username, pwd: userPassword}, {safe:true}, function(err, documents) { + collection.insert({user: username, pwd: userPassword}, {safe:safe}, function(err, documents) { callback(err, documents); }); } @@ -639,17 +655,33 @@ Db.prototype.addUser = function(username, password, callback) { /** * Remove a user from a database * + * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. + * * @param {String} username username. + * @param {Object} [options] additional options during update. * @param {Function} callback returns the results. * @return {null} * @api public */ -Db.prototype.removeUser = function(username, callback) { +Db.prototype.removeUser = function(username, options, callback) { + var self = this; + var args = Array.prototype.slice.call(arguments, 1); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + // Figure out the safe mode settings + var safe = self.strict != null && self.strict == false ? true : self.strict; + // Override with options passed in if applicable + safe = options != null && options['safe'] != null ? options['safe'] : safe; + // Ensure it's at least set to safe + safe = safe == null ? true : safe; + // Fetch a user collection this.collection(DbCommand.SYSTEM_USER_COLLECTION, function(err, collection) { collection.findOne({user: username}, function(err, user) { if(user != null) { - collection.remove({user: username}, function(err, result) { + collection.remove({user: username}, {safe:safe}, function(err, result) { callback(err, true); }); } else { @@ -684,6 +716,14 @@ Db.prototype.createCollection = function(collectionName, options, callback) { callback = args.pop(); options = args.length ? args.shift() : null; var self = this; + + // Figure out the safe mode settings + var safe = self.strict != null && self.strict == false ? true : self.strict; + // Override with options passed in if applicable + safe = options != null && options['safe'] != null ? options['safe'] : safe; + // Ensure it's at least set to safe + safe = safe == null ? true : safe; + // Check if we have the name this.collectionNames(collectionName, function(err, collections) { if(err != null) return callback(err, null); @@ -706,7 +746,7 @@ Db.prototype.createCollection = function(collectionName, options, callback) { } // Create a new collection and return it - self._executeQueryCommand(DbCommand.createCreateCollectionCommand(self, collectionName, options), {read:false, safe:true}, function(err, result) { + self._executeQueryCommand(DbCommand.createCreateCollectionCommand(self, collectionName, options), {read:false, safe:safe}, function(err, result) { var document = result.documents[0]; // If we have no error let's return the collection if(err == null && document.ok == 1) { @@ -886,6 +926,7 @@ Db.prototype.resetErrorHistory = function(options, callback) { * Creates an index on the collection. * * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a getLastError command returning the results of the command on MongoDB. * - **unique** {Boolean, default:false}, creates an unique index. * - **sparse** {Boolean, default:false}, creates a sparse index. * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. @@ -901,11 +942,22 @@ Db.prototype.resetErrorHistory = function(options, callback) { * @api public */ Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callback) { - if(callback == null) { callback = options; options = null; } - var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + // Figure out the safe mode settings + var safe = self.strict != null && self.strict == false ? true : self.strict; + // Override with options passed in if applicable + safe = options != null && options['safe'] != null ? options['safe'] : safe; + // Ensure it's at least set to safe + safe = safe == null ? true : safe; + + // Create command + var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); // Execute insert command - this._executeInsertCommand(command, {read:false, safe:true}, function(err, result) { + this._executeInsertCommand(command, {read:false, safe:safe}, function(err, result) { if(err != null) return callback(err, null); result = result && result.documents; @@ -921,6 +973,7 @@ Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callba * Ensures that an index exists, if it does not it creates it * * Options + * - **safe** {true | {w:n, wtimeout:n} | {fsync:true}, default:false}, executes with a * - **unique** {Boolean, default:false}, creates an unique index. * - **sparse** {Boolean, default:false}, creates a sparse index. * - **background** {Boolean, default:false}, creates the index in the background, yielding whenever possible. @@ -937,7 +990,19 @@ Db.prototype.createIndex = function(collectionName, fieldOrSpec, options, callba * @api public */ Db.prototype.ensureIndex = function(collectionName, fieldOrSpec, options, callback) { - if(callback == null) { callback = options; options = null; } + var self = this; + var args = Array.prototype.slice.call(arguments, 2); + callback = args.pop(); + options = args.length ? args.shift() : {}; + + // Figure out the safe mode settings + var safe = self.strict != null && self.strict == false ? true : self.strict; + // Override with options passed in if applicable + safe = options != null && options['safe'] != null ? options['safe'] : safe; + // Ensure it's at least set to safe + safe = safe == null ? true : safe; + + // Create command var command = DbCommand.createCreateIndexCommand(this, collectionName, fieldOrSpec, options); var index_name = command.documents[0].name; var self = this; @@ -946,7 +1011,7 @@ Db.prototype.ensureIndex = function(collectionName, fieldOrSpec, options, callba if(err != null) return callback(err, null); if(!collectionInfo[index_name]) { - self._executeInsertCommand(command, {read:false, safe:true}, function(err, result) { + self._executeInsertCommand(command, {read:false, safe:safe}, function(err, result) { // Only callback if we have one specified if(typeof callback === 'function') { if(err != null) return callback(err, null); @@ -1385,6 +1450,7 @@ Db.prototype._executeQueryCommand = function(db_command, options, callback) { var __executeInsertCommand = function(self, db_command, options, callback) { // Always checkout a writer for this kind of operations var connection = self.serverConfig.checkoutWriter(); + // Get strict mode var safe = options['safe'] != null ? options['safe'] : false; var raw = options['raw'] != null ? options['raw'] : self.raw; var specifiedConnection = options['connection'] != null ? options['connection'] : null; diff --git a/node_modules/reg/node_modules/mongodb/lib/mongodb/gridfs/readstream.js b/node_modules/reg/node_modules/mongodb/lib/mongodb/gridfs/readstream.js index 423abd4..427cb4d 100644 --- a/node_modules/reg/node_modules/mongodb/lib/mongodb/gridfs/readstream.js +++ b/node_modules/reg/node_modules/mongodb/lib/mongodb/gridfs/readstream.js @@ -148,6 +148,9 @@ ReadStream.prototype.destroy = function() { * @api public */ ReadStream.prototype.resume = function() { + if (this.paused === false) { + return; + } this.paused = false; var self = this; if(self.pendingChunk != null) { diff --git a/node_modules/reg/node_modules/mongodb/package.json b/node_modules/reg/node_modules/mongodb/package.json index 8a9bf48..6011cb9 100644 --- a/node_modules/reg/node_modules/mongodb/package.json +++ b/node_modules/reg/node_modules/mongodb/package.json @@ -1,7 +1,7 @@ { "name" : "mongodb" , "description" : "A node.js driver for MongoDB" , "keywords" : ["mongodb", "mongo", "driver", "db"] -, "version" : "0.9.9" +, "version" : "0.9.9-1" , "author" : "Christian Amor Kvalheim " , "contributors" : [ "Aaron Heckmann", "Christoph Pojer", @@ -64,8 +64,11 @@ "dox": "0.1.3" , "uglify-js": "1.2.5" , "ejs": "0.6.1" - , "nodeunit": "0.6.4" - , "markdown": "0.3.1" + , "nodeunit": "0.7.3" + , "github3": ">=0.3.0" + , "markdown": "0.3.1" + , "gleak": "0.2.3" + , "step": "0.0.5" } , "config": { "native" : false } , "main": "./lib/mongodb/index" diff --git a/node_modules/reg/node_modules/mongodb/test/admin_test.js b/node_modules/reg/node_modules/mongodb/test/admin_test.js deleted file mode 100644 index 3c504d0..0000000 --- a/node_modules/reg/node_modules/mongodb/test/admin_test.js +++ /dev/null @@ -1,698 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/*! - * Module dependencies. - */ -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.shouldCorrectlyCallValidateCollection = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - fs_client.collection('test', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, doc) { - fs_client.admin(function(err, adminDb) { - adminDb.addUser('admin', 'admin', function(err, result) { - adminDb.authenticate('admin', 'admin', function(err, replies) { - adminDb.validateCollection('test', function(err, doc) { - // Pre 1.9.1 servers - if(doc.result != null) { - test.ok(doc.result != null); - test.ok(doc.result.match(/firstExtent/) != null); - } else { - test.ok(doc.firstExtent != null); - } - - fs_client.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Authenticate against MongoDB Admin user - * - * @_class admin - * @_function authenticate - * @ignore - */ -exports.shouldCorrectlyAuthenticate = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Grab a collection object - db.collection('test', function(err, collection) { - - // Force the creation of the collection by inserting a document - // Collections are not created until the first document is inserted - collection.insert({'a':1}, {safe:true}, function(err, doc) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Example showing how to access the Admin database for admin level operations. - * - * @_class db - * @_function admin - * @ignore - */ -exports.shouldCorrectlyAuthenticate = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); -} - -/** - * Retrieve the buildInfo for the current MongoDB instance - * - * @_class admin - * @_function buildInfo - * @ignore - */ -exports.shouldCorrectlyAuthenticate = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - // Retrive the build information for the MongoDB instance - adminDb.buildInfo(function(err, info) { - test.ok(err == null); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the buildInfo using the command function - * - * @_class admin - * @_function command - * @ignore - */ -exports.shouldCorrectlyAuthenticate = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - // Retrive the build information using the admin command - adminDb.command({buildInfo:1}, function(err, info) { - test.ok(err == null); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the current profiling level set for the MongoDB instance - * - * @_class admin - * @_function profilingLevel - * @ignore - */ -exports.shouldCorrectlySetDefaultProfilingLevel = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Grab a collection object - db.collection('test', function(err, collection) { - - // Force the creation of the collection by inserting a document - // Collections are not created until the first document is inserted - collection.insert({'a':1}, {safe:true}, function(err, doc) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, replies) { - - // Retrive the profiling level - adminDb.profilingLevel(function(err, level) { - test.equal("off", level); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * An example of how to use the setProfilingInfo - * Use this command to set the Profiling level on the MongoDB server - * - * @_class admin - * @_function setProfilingLevel - */ -exports.shouldCorrectlyChangeProfilingLevel = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Grab a collection object - db.collection('test', function(err, collection) { - - // Force the creation of the collection by inserting a document - // Collections are not created until the first document is inserted - collection.insert({'a':1}, {safe:true}, function(err, doc) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, replies) { - - // Set the profiling level to only profile slow queries - adminDb.setProfilingLevel('slow_only', function(err, level) { - - // Retrive the profiling level and verify that it's set to slow_only - adminDb.profilingLevel(function(err, level) { - test.equal('slow_only', level); - - // Turn profiling off - adminDb.setProfilingLevel('off', function(err, level) { - - // Retrive the profiling level and verify that it's set to off - adminDb.profilingLevel(function(err, level) { - test.equal('off', level); - - // Set the profiling level to log all queries - adminDb.setProfilingLevel('all', function(err, level) { - - // Retrive the profiling level and verify that it's set to all - adminDb.profilingLevel(function(err, level) { - test.equal('all', level); - - // Attempt to set an illegal profiling level - adminDb.setProfilingLevel('medium', function(err, level) { - test.ok(err instanceof Error); - test.equal("Error: illegal profiling level value medium", err.message); - - db.close(); - test.done(); - }); - }) - }); - }) - }); - }) - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * An example of how to use the profilingInfo - * Use this command to pull back the profiling information currently set for Mongodb - * - * @_class admin - * @_function profilingInfo - */ -exports.shouldCorrectlySetAndExtractProfilingInfo = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Grab a collection object - db.collection('test', function(err, collection) { - - // Force the creation of the collection by inserting a document - // Collections are not created until the first document is inserted - collection.insert({'a':1}, {safe:true}, function(doc) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, replies) { - - // Set the profiling level to all - adminDb.setProfilingLevel('all', function(err, level) { - - // Execute a query command - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - - // Turn off profiling - adminDb.setProfilingLevel('off', function(err, level) { - - // Retrive the profiling information - adminDb.profilingInfo(function(err, infos) { - test.ok(infos.constructor == Array); - test.ok(infos.length >= 1); - test.ok(infos[0].ts.constructor == Date); - test.ok(infos[0].millis.constructor == Number); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * An example of how to use the validateCollection command - * Use this command to check that a collection is valid (not corrupt) and to get various statistics. - * - * @_class admin - * @_function validateCollection - */ -exports.shouldCorrectlyCallValidateCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Grab a collection object - db.collection('test', function(err, collection) { - - // Force the creation of the collection by inserting a document - // Collections are not created until the first document is inserted - collection.insert({'a':1}, {safe:true}, function(err, doc) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, replies) { - - // Validate the 'test' collection - adminDb.validateCollection('test', function(err, doc) { - - // Pre 1.9.1 servers - if(doc.result != null) { - test.ok(doc.result != null); - test.ok(doc.result.match(/firstExtent/) != null); - } else { - test.ok(doc.firstExtent != null); - } - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * An example of how to add a user to the admin database - * - * @_class admin - * @_function ping - */ -exports.shouldCorrectlyPingTheMongoDbInstance = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - // Ping the server - adminDb.ping(function(err, pingResult) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An example of how add a user, authenticate and logout - * - * @_class admin - * @_function logout - */ -exports.shouldCorrectlyUseLogoutFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - // Logout the user - adminDb.logout(function(err, result) { - test.equal(true, result); - - db.close(); - test.done(); - }) - }); - }); - }); - }); - }); -} - - -/** - * An example of how to add a user to the admin database - * - * @_class admin - * @_function addUser - */ -exports.shouldCorrectlyAddAUserToAdminDb = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * An example of how to remove a user from the admin database - * - * @_class admin - * @_function removeUser - */ -exports.shouldCorrectlyAddAUserAndRemoveItFromAdminDb = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Drop the current database if it exists to avoid problems - db.dropDatabase(function(err, done) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // Add the new user to the admin database - adminDb.addUser('admin', 'admin', function(err, result) { - - // Authenticate using the newly added user - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(result); - - // Remove the user - adminDb.removeUser('admin', function(err, result) { - - // Authenticate using the removed user should fail - adminDb.authenticate('admin', 'admin', function(err, result) { - test.ok(err != null); - test.ok(!result); - - db.close(); - test.done(); - }); - }) - }); - }); - }); - }); - }); -} - -/** - * An example of listing all available databases. - * - * @_class admin - * @_function listDatabases - */ -exports.shouldCorrectlyListAllAvailableDatabases = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Use the admin database for the operation - db.admin(function(err, adminDb) { - - // List all the available databases - adminDb.listDatabases(function(err, dbs) { - test.equal(null, err); - test.ok(dbs.databases.length > 0); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/authentication_test.js b/node_modules/reg/node_modules/mongodb/test/authentication_test.js deleted file mode 100644 index 599b822..0000000 --- a/node_modules/reg/node_modules/mongodb/test/authentication_test.js +++ /dev/null @@ -1,171 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * Test the authentication method for the user - * - * @ignore - */ -exports.shouldCorrectlyAuthenticate = function(test) { - var user_name = 'spongebob'; - var password = 'squarepants'; - - client.authenticate('admin', 'admin', function(err, replies) { - test.ok(err instanceof Error); - test.ok(!replies); - - // Add a user - client.addUser(user_name, password, function(err, result) { - client.authenticate(user_name, password, function(err, replies) { - test.ok(!(err instanceof Error)); - test.ok(replies); - test.done(); - }); - }); - }); -} - -/** - * Test the authentication method for the user - * - * @ignore - */ -exports.shouldCorrectlyReAuthorizeReconnectedConnections = function(test) { - var user_name = 'spongebob2'; - var password = 'password'; - - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:3, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, automatic_connect_client) { - p_client.authenticate('admin', 'admin', function(err, replies) { - test.ok(err instanceof Error); - // Add a user - p_client.addUser(user_name, password, function(err, result) { - // Execute authentication - p_client.authenticate(user_name, password, function(err, replies) { - test.ok(err == null); - - // Kill a connection to force a reconnect - p_client.serverConfig.close(); - - p_client.createCollection('shouldCorrectlyReAuthorizeReconnectedConnections', function(err, collection) { - collection.insert({a:1}, {safe:true}, function(err, r) { - collection.insert({a:2}, {safe:true}, function(err, r) { - collection.insert({a:3}, {safe:true}, function(err, r) { - collection.count(function(err, count) { - test.equal(3, count); - p_client.close(); - test.done(); - }) - }) - }) - }) - }); - }); - }); - }); - }); -} - -exports.shouldCorrectlyAddAndRemoveUser = function(test) { - var user_name = 'spongebob2'; - var password = 'password'; - - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, automatic_connect_client) { - p_client.authenticate('admin', 'admin', function(err, replies) { - test.ok(err instanceof Error); - - // Add a user - p_client.addUser(user_name, password, function(err, result) { - p_client.authenticate(user_name, password, function(err, replies) { - test.ok(replies); - - // Remove the user and try to authenticate again - p_client.removeUser(user_name, function(err, result) { - p_client.authenticate(user_name, password, function(err, replies) { - test.ok(err instanceof Error); - - test.done(); - p_client.close(); - }); - }); - }); - }); - }); - }); -} - -// run this last -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/auxilliary/authentication_test.js b/node_modules/reg/node_modules/mongodb/test/auxilliary/authentication_test.js deleted file mode 100644 index 5facab6..0000000 --- a/node_modules/reg/node_modules/mongodb/test/auxilliary/authentication_test.js +++ /dev/null @@ -1,216 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server, - ServerManager = require('../../test/tools/server_manager').ServerManager, - Step = require("../../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var serverManager = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - serverManager.killAll(function(err, result) { - callback(); - }); -} - -exports.shouldCorrectlyAuthenticate = function(test) { - var db1 = new Db('mongo-ruby-test-auth1', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - var db2 = new Db('mongo-ruby-test-auth2', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - var admin = new Db('admin', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - - Step( - function bootTheServerWithNoAuth() { - serverManager = new ServerManager({auth:false, purgedirectories:true}) - serverManager.start(true, this); - }, - - function openDbs() { - db1.open(this.parallel()); - db2.open(this.parallel()); - admin.open(this.parallel()); - }, - - function addAdminUserToDatabase(err, db1, db2, admin) { - test.equal(null, err); - admin.addUser('admin', 'admin', this); - }, - - function restartServerInAuthMode(err, result) { - test.equal(null, err); - test.equal('7c67ef13bbd4cae106d959320af3f704', result.shift().pwd); - - db1.close(); - db2.close(); - admin.close(); - - serverManager = new ServerManager({auth:true, purgedirectories:false}) - serverManager.start(true, this); - }, - - function openDbs() { - db1.open(this.parallel()); - db2.open(this.parallel()); - admin.open(this.parallel()); - }, - - function authenticateAdminUser(err) { - test.equal(null, err); - - admin.authenticate('admin', 'admin', this.parallel()); - db1.admin().authenticate('admin', 'admin', this.parallel()); - db2.admin().authenticate('admin', 'admin', this.parallel()); - }, - - function addDbUsersForAuthentication(err, result1, result2, result3) { - test.equal(null, err); - test.ok(result1); - test.ok(result2); - test.ok(result3); - - db1.addUser('user1', 'secret', this.parallel()); - db2.addUser('user2', 'secret', this.parallel()); - }, - - function closeAdminConnection(err, result1, result2) { - test.ok(err == null); - test.ok(result1 != null); - test.ok(result2 != null); - admin.logout(this.parallel()); - db1.admin().logout(this.parallel()); - db2.admin().logout(this.parallel()); - }, - - function failAuthenticationWithDbs(err, result) { - var self = this; - - db1.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - - db2.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - }, - - function authenticateAgainstDbs(err, result) { - test.ok(err != null); - - db1.authenticate('user1', 'secret', this.parallel()); - db2.authenticate('user2', 'secret', this.parallel()); - }, - - function correctlyInsertRowToDbs(err, result1, result2) { - var self = this; - test.ok(err == null); - test.ok(result1); - test.ok(result2); - - db1.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - - db2.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - }, - - function validateCorrectInsertsAndBounceServer(err, result1, result2) { - test.ok(err == null); - test.ok(result1 != null); - test.ok(result2 != null); - - serverManager = new ServerManager({auth:true, purgedirectories:false}) - serverManager.start(true, this); - }, - - function reconnectAndVerifyThatAuthIsAutomaticallyApplied() { - var self = this; - db1.collection('stuff', function(err, collection) { - - collection.find({}).toArray(function(err, items) { - test.ok(err == null); - test.equal(1, items.length); - - db1.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - - db2.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - }) - }); - }, - - function logoutDb1(err, result1, result2) { - test.ok(err == null); - test.ok(result1 != null); - test.ok(result2 != null); - - db1.logout(this); - }, - - function insertShouldFail(err, result) { - var self = this; - db1.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, self.parallel()); - }); - }, - - function logoutDb2(err, result) { - test.ok(err != null); - db2.logout(this); - }, - - function insertShouldFail(err, result) { - var self = this; - db2.collection('stuff', function(err, collection) { - collection.insert({a:2}, {safe:true}, function(err, result) { - test.ok(err != null); - test.done(); - // Close all connections - db1.close(); - db2.close(); - admin.close(); - }); - }); - } - ) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/auxilliary/repl_set_ssl_test.js b/node_modules/reg/node_modules/mongodb/test/auxilliary/repl_set_ssl_test.js deleted file mode 100644 index 1bf21ef..0000000 --- a/node_modules/reg/node_modules/mongodb/test/auxilliary/repl_set_ssl_test.js +++ /dev/null @@ -1,80 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server, - ReplSetServers = mongodb.ReplSetServers, - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager, - Step = require("../../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var serverManager = null; -var RS = RS == null ? null : RS; -var ssl = true; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - RS = new ReplicaSetManager({retries:120, - ssl:ssl, - arbiter_count:1, - secondary_count:1, - passive_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - RS.restartKilledNodes(function(err, result) { - callback(); - }); -} - -exports.shouldCorrectlyConncetToSSLBasedReplicaset = function(test) { - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name, ssl:ssl} - ); - - // Connect to the replicaset - var slaveDb = null; - var db = new Db('foo', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - test.equal(null, err); - test.done(); - p_db.close(); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/auxilliary/replicaset_auth_test.js b/node_modules/reg/node_modules/mongodb/test/auxilliary/replicaset_auth_test.js deleted file mode 100644 index 34ab2ff..0000000 --- a/node_modules/reg/node_modules/mongodb/test/auxilliary/replicaset_auth_test.js +++ /dev/null @@ -1,242 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server, - ReplSetServers = mongodb.ReplSetServers, - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager, - Step = require("../../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var serverManager = null; -var RS = RS == null ? null : RS; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - RS = new ReplicaSetManager({retries:120, - auth:true, - arbiter_count:0, - secondary_count:1, - passive_count:0}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports.shouldCorrectlyAuthenticateWithMultipleLoginsAndLogouts = function(test) { - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name} - ); - - // Connect to the replicaset - var slaveDb = null; - var db = new Db('foo', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - Step( - function addUser() { - db.admin().addUser("me", "secret", this); - }, - - function ensureFailingInsert(err, result) { - // return - var self = this; - test.equal(null, err); - test.ok(result != null); - - db.collection("stuff", function(err, collection) { - collection.insert({a:2}, {safe: {w: 3}}, self); - }); - }, - - function authenticate(err, result) { - test.ok(err != null); - - db.admin().authenticate("me", "secret", this); - }, - - function changePassword(err, result) { - var self = this; - test.equal(null, err); - test.ok(result); - - db.admin().addUser("me", "secret2", this); - }, - - function authenticate(err, result) { - db.admin().authenticate("me", "secret2", this); - }, - - function insertShouldSuccedNow(err, result) { - var self = this; - test.equal(null, err); - test.ok(result); - - db.collection("stuff", function(err, collection) { - collection.insert({a:3}, {safe: true}, self); - }); - }, - - function queryShouldExecuteCorrectly(err, result) { - var self = this; - test.equal(null, err); - - db.collection("stuff", function(err, collection) { - collection.findOne(self); - }); - }, - - function logout(err, item) { - test.ok(err == null); - test.equal(3, item.a); - - db.admin().logout(this); - }, - - function findShouldFailDueToLoggedOut(err, result) { - var self = this; - test.equal(null, err); - - db.collection("stuff", function(err, collection) { - collection.findOne(self); - }); - }, - - function sameShouldApplyToRandomSecondaryServer(err, result) { - var self = this; - test.ok(err != null); - - slaveDb = new Db('foo', new Server(db.serverConfig.secondaries[0].host - , db.serverConfig.secondaries[0].port, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null), slave_ok:true}); - slaveDb.open(function(err, slaveDb) { - slaveDb.collection('stuff', function(err, collection) { - collection.findOne(self) - }) - }); - }, - - function shouldCorrectlyAuthenticateAgainstSecondary(err, result) { - test.ok(err != null) - slaveDb.admin().authenticate('me', 'secret2', this); - }, - - function shouldCorrectlyInsertItem(err, result) { - var self = this; - test.equal(null, err); - test.ok(result); - - slaveDb.collection('stuff', function(err, collection) { - collection.findOne(self) - }) - }, - - function finishUp(err, item) { - test.ok(err == null); - test.equal(3, item.a); - - test.done(); - p_db.close(); - slaveDb.close(); - } - ) - }); -} - -exports.shouldCorrectlyAuthenticate = function(test) { - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Connect to the replicaset - var slaveDb = null; - var db = new Db('foo', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - Step( - function addUser() { - db.admin().addUser("me", "secret", this); - }, - - function ensureFailingInsert(err, result) { - var self = this; - test.equal(null, err); - test.ok(result != null); - - db.collection("stuff", function(err, collection) { - collection.insert({a:2}, {safe: {w: 2, wtimeout: 10000}}, self); - }); - }, - - function authenticate(err, result) { - test.ok(err != null); - - db.admin().authenticate("me", "secret", this); - }, - - function insertShouldSuccedNow(err, result) { - var self = this; - test.equal(null, err); - test.ok(result); - - db.collection("stuff", function(err, collection) { - collection.insert({a:2}, {safe: {w: 2, wtimeout: 10000}}, self); - }); - }, - - function queryShouldExecuteCorrectly(err, result) { - var self = this; - test.equal(null, err); - - db.collection("stuff", function(err, collection) { - collection.findOne(self); - }); - }, - - function finishUp(err, item) { - test.ok(err == null); - test.equal(2, item.a); - test.done(); - p_db.close(); - } - ) - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/auxilliary/single_server_kill_reconnect.js b/node_modules/reg/node_modules/mongodb/test/auxilliary/single_server_kill_reconnect.js deleted file mode 100644 index bb41b9f..0000000 --- a/node_modules/reg/node_modules/mongodb/test/auxilliary/single_server_kill_reconnect.js +++ /dev/null @@ -1,159 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server, - ServerManager = require('../../test/tools/server_manager').ServerManager, - Step = require("../../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 1}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var serverManager = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports.shouldCorrectlyKeepInsertingDocumentsWhenServerDiesAndComesUp = function(test) { - var db1 = new Db('mongo-ruby-test-single-server', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // All inserted docs - var docs = []; - var errs = []; - var insertDocs = []; - // Start server - serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true}) - serverManager.start(true, function() { - db1.open(function(err, db) { - // Startup the insert of documents - var intervalId = setInterval(function() { - db.collection('inserts', function(err, collection) { - var doc = {timestamp:new Date().getTime()}; - insertDocs.push(doc); - // Insert document - collection.insert(doc, {safe:{fsync:true}}, function(err, result) { - // Save errors - if(err != null) errs.push(err); - if(err == null) { - docs.push(result[0]); - } - }) - }); - }, 500); - - // Wait for a second and then kill the server - setTimeout(function() { - // Kill server instance - serverManager.stop(9, function(err, result) { - // Server down for 1 second - setTimeout(function() { - // Restart server - serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true}); - serverManager.start(true, function() { - // Wait for it - setTimeout(function() { - // Drop db - db.dropDatabase(function(err, result) { - clearInterval(intervalId); - // Close db - db.close(); - // Check that we got at least one error - test.ok(docs.length > 0); - test.ok(insertDocs.length > 0); - // Finish up - test.done(); - }); - }, 5000) - }) - }, 1000); - }); - }, 3000); - }) - }); -} - -exports.shouldCorrectlyInsertKillServerFailThenRestartServerAndSucceed = function(test) { - var db = new Db('test-single-server-recovery', new Server("127.0.0.1", 27017, {auto_reconnect: true}), {numberOfRetries:3, retryMiliSeconds:500, native_parser: (process.env['TEST_NATIVE'] != null)}); - // All inserted docs - var docs = []; - var errs = []; - var insertDocs = []; - - // Start server - serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true}) - serverManager.start(true, function() { - db.open(function(err, db) { - // Add an error handler - db.on("error", function(err) { - console.log("----------------------------------------------- received error") - console.dir(err) - errs.push(err); - }); - - db.collection('inserts', function(err, collection) { - var doc = {timestamp:new Date().getTime(), a:1}; - collection.insert(doc, {safe:true}, function(err, result) { - test.equal(null, err); - - // Kill server instance - serverManager.stop(9, function(err, result) { - // Attemp insert (should timeout) - var doc = {timestamp:new Date().getTime(), b:1}; - collection.insert(doc, {safe:true}, function(err, result) { - test.ok(err != null); - test.equal(null, result); - - // Restart server - serverManager = new ServerManager({auth:false, purgedirectories:false, journal:true}); - serverManager.start(true, function() { - // Attemp insert again - collection.insert(doc, {safe:true}, function(err, result) { - // Fetch the documents - collection.find({b:1}).toArray(function(err, items) { - test.equal(null, err); - test.equal(1, items[0].b); - db.close(); - test.done(); - }); - }); - }); - }); - }); - }) - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/auxilliary/ssl_test.js b/node_modules/reg/node_modules/mongodb/test/auxilliary/ssl_test.js deleted file mode 100644 index c95620b..0000000 --- a/node_modules/reg/node_modules/mongodb/test/auxilliary/ssl_test.js +++ /dev/null @@ -1,78 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server, - ServerManager = require('../../test/tools/server_manager').ServerManager, - Step = require("../../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var serverManager = null; -var ssl = true; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports.shouldCorrectlyCommunicateUsingSSLSocket = function(test) { - var db1 = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize:4, ssl:ssl}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // All inserted docs - var docs = []; - var errs = []; - var insertDocs = []; - - // Start server - serverManager = new ServerManager({auth:false, purgedirectories:true, journal:true, ssl:ssl}) - serverManager.start(true, function() { - db1.open(function(err, db) { - // Create a collection - db.createCollection('shouldCorrectlyCommunicateUsingSSLSocket', function(err, collection) { - collection.insert([{a:1}, {b:2}, {c:'hello world'}]); - collection.insert([{a:1}, {b:2}, {c:'hello world'}]); - collection.insert([{a:1}, {b:2}, {c:'hello world'}]); - collection.insert([{a:1}, {b:2}, {c:'hello world'}]); - collection.insert([{a:1}, {b:2}, {c:'hello world'}], {safe:true}, function(err, result) { - collection.find({}).toArray(function(err, items) { - // test.equal(3, items.length); - db.close(); - test.done(); - }) - }); - }); - }) - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/bson/bson_test.js b/node_modules/reg/node_modules/mongodb/test/bson/bson_test.js deleted file mode 100644 index b28aea4..0000000 --- a/node_modules/reg/node_modules/mongodb/test/bson/bson_test.js +++ /dev/null @@ -1,1606 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - mongoO = require('../../lib/mongodb').pure(), - debug = require('util').debug, - inspect = require('util').inspect, - Buffer = require('buffer').Buffer, - gleak = require('../../dev/tools/gleak'), - fs = require('fs'), - BSON = mongoO.BSON, - Code = mongoO.Code, - Binary = mongoO.Binary, - Timestamp = mongoO.Timestamp, - Long = mongoO.Long, - MongoReply = mongoO.MongoReply, - ObjectID = mongoO.ObjectID, - Symbol = mongoO.Symbol, - DBRef = mongoO.DBRef, - Double = mongoO.Double, - MinKey = mongoO.MinKey, - MaxKey = mongoO.MaxKey, - BinaryParser = mongoO.BinaryParser; - -var BSONSE = mongodb, - BSONDE = mongodb; - -// for tests -BSONDE.BSON_BINARY_SUBTYPE_DEFAULT = 0; -BSONDE.BSON_BINARY_SUBTYPE_FUNCTION = 1; -BSONDE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -BSONDE.BSON_BINARY_SUBTYPE_UUID = 3; -BSONDE.BSON_BINARY_SUBTYPE_MD5 = 4; -BSONDE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -BSONSE.BSON_BINARY_SUBTYPE_DEFAULT = 0; -BSONSE.BSON_BINARY_SUBTYPE_FUNCTION = 1; -BSONSE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -BSONSE.BSON_BINARY_SUBTYPE_UUID = 3; -BSONSE.BSON_BINARY_SUBTYPE_MD5 = 4; -BSONSE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -var hexStringToBinary = function(string) { - var numberofValues = string.length / 2; - var array = ""; - - for(var i = 0; i < numberofValues; i++) { - array += String.fromCharCode(parseInt(string[i*2] + string[i*2 + 1], 16)); - } - return array; -} - -var assertBuffersEqual = function(test, buffer1, buffer2) { - if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2); - - for(var i = 0; i < buffer1.length; i++) { - test.equal(buffer1[i], buffer2[i]); - } -} - -/** - * Module for parsing an ISO 8601 formatted string into a Date object. - */ -var ISODate = function (string) { - var match; - - if (typeof string.getTime === "function") - return string; - else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) { - var date = new Date(); - date.setUTCFullYear(Number(match[1])); - date.setUTCMonth(Number(match[3]) - 1 || 0); - date.setUTCDate(Number(match[5]) || 0); - date.setUTCHours(Number(match[7]) || 0); - date.setUTCMinutes(Number(match[8]) || 0); - date.setUTCSeconds(Number(match[10]) || 0); - date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0); - - if (match[13] && match[13] !== "Z") { - var h = Number(match[16]) || 0, - m = Number(match[17]) || 0; - - h *= 3600000; - m *= 60000; - - var offset = h + m; - if (match[15] == "+") - offset = -offset; - - date = new Date(date.valueOf() + offset); - } - - return date; - } else - throw new Error("Invalid ISO 8601 date given.", __filename); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -/** - * @ignore - */ -exports['Should Correctly get BSON types from require'] = function(test) { - var _mongodb = require('../../lib/mongodb'); - test.ok(_mongodb.ObjectID === ObjectID); - test.ok(_mongodb.Binary === Binary); - test.ok(_mongodb.Long === Long); - test.ok(_mongodb.Timestamp === Timestamp); - test.ok(_mongodb.Code === Code); - test.ok(_mongodb.DBRef === DBRef); - test.ok(_mongodb.Symbol === Symbol); - test.ok(_mongodb.MinKey === MinKey); - test.ok(_mongodb.MaxKey === MaxKey); - test.ok(_mongodb.Double === Double); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Deserialize object'] = function(test) { - var bytes = [95,0,0,0,2,110,115,0,42,0,0,0,105,110,116,101,103,114,97,116,105,111,110,95,116,101,115,116,115,95,46,116,101,115,116,95,105,110,100,101,120,95,105,110,102,111,114,109,97,116,105,111,110,0,8,117,110,105,113,117,101,0,0,3,107,101,121,0,12,0,0,0,16,97,0,1,0,0,0,0,2,110,97,109,101,0,4,0,0,0,97,95,49,0,0]; - var serialized_data = ''; - // Convert to chars - for(var i = 0; i < bytes.length; i++) { - serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]); - } - - var object = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(new Buffer(serialized_data, 'binary')); - test.equal("a_1", object.name); - test.equal(false, object.unique); - test.equal(1, object.key.a); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Deserialize object with all types'] = function(test) { - var bytes = [26,1,0,0,7,95,105,100,0,161,190,98,75,118,169,3,0,0,3,0,0,4,97,114,114,97,121,0,26,0,0,0,16,48,0,1,0,0,0,16,49,0,2,0,0,0,16,50,0,3,0,0,0,0,2,115,116,114,105,110,103,0,6,0,0,0,104,101,108,108,111,0,3,104,97,115,104,0,19,0,0,0,16,97,0,1,0,0,0,16,98,0,2,0,0,0,0,9,100,97,116,101,0,161,190,98,75,0,0,0,0,7,111,105,100,0,161,190,98,75,90,217,18,0,0,1,0,0,5,98,105,110,97,114,121,0,7,0,0,0,2,3,0,0,0,49,50,51,16,105,110,116,0,42,0,0,0,1,102,108,111,97,116,0,223,224,11,147,169,170,64,64,11,114,101,103,101,120,112,0,102,111,111,98,97,114,0,105,0,8,98,111,111,108,101,97,110,0,1,15,119,104,101,114,101,0,25,0,0,0,12,0,0,0,116,104,105,115,46,120,32,61,61,32,51,0,5,0,0,0,0,3,100,98,114,101,102,0,37,0,0,0,2,36,114,101,102,0,5,0,0,0,116,101,115,116,0,7,36,105,100,0,161,190,98,75,2,180,1,0,0,2,0,0,0,10,110,117,108,108,0,0]; - var serialized_data = ''; - // Convert to chars - for(var i = 0; i < bytes.length; i++) { - serialized_data = serialized_data + BinaryParser.fromByte(bytes[i]); - } - - var object = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(new Buffer(serialized_data, 'binary'));//, false, true); - // Perform tests - test.equal("hello", object.string); - test.deepEqual([1,2,3], object.array); - test.equal(1, object.hash.a); - test.equal(2, object.hash.b); - test.ok(object.date != null); - test.ok(object.oid != null); - test.ok(object.binary != null); - test.equal(42, object.int); - test.equal(33.3333, object.float); - test.ok(object.regexp != null); - test.equal(true, object.boolean); - test.ok(object.where != null); - test.ok(object.dbref != null); - test.ok(object[null] == null); - test.done(); -} - -/** - * @ignore - */ -exports['Should Serialize and Deserialize String'] = function(test) { - var test_string = {hello: 'world'}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_string, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_string)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_string, false, serialized_data2, 0); - - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_string, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Serialize and Deserialize Empty String'] = function(test) { - var test_string = {hello: ''}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_string, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_string)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_string, false, serialized_data2, 0); - - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_string, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Integer'] = function(test) { - var test_number = {doc: 5}; - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_number, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_number)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_number, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_number, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.deepEqual(test_number, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data2)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize null value'] = function(test) { - var test_null = {doc:null}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_null, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_null)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_null, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var object = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal(null, object.doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Number'] = function(test) { - var test_number = {doc: 5.5}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_number, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_number)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_number, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.deepEqual(test_number, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Integer'] = function(test) { - var test_int = {doc: 42}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); - - test_int = {doc: -5600}; - serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); - - test_int = {doc: 2147483647}; - serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); - - test_int = {doc: -2147483648}; - serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - test.deepEqual(test_int.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Object'] = function(test) { - var doc = {doc: {age: 42, name: 'Spongebob', shoe_size: 9.5}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.deepEqual(doc.doc.age, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.age); - test.deepEqual(doc.doc.name, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.name); - test.deepEqual(doc.doc.shoe_size, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.shoe_size); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Array'] = function(test) { - var doc = {doc: [1, 2, 'a', 'b']}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal(doc.doc[0], deserialized.doc[0]) - test.equal(doc.doc[1], deserialized.doc[1]) - test.equal(doc.doc[2], deserialized.doc[2]) - test.equal(doc.doc[3], deserialized.doc[3]) - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Array with added on functions'] = function(test) { - Array.prototype.toXml = function() {}; - var doc = {doc: [1, 2, 'a', 'b']}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal(doc.doc[0], deserialized.doc[0]) - test.equal(doc.doc[1], deserialized.doc[1]) - test.equal(doc.doc[2], deserialized.doc[2]) - test.equal(doc.doc[3], deserialized.doc[3]) - test.done(); -} - -/** - * @ignore - */ -exports['Should correctly deserialize a nested object'] = function(test) { - var doc = {doc: {doc:1}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.deepEqual(doc.doc.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize A Boolean'] = function(test) { - var doc = {doc: true}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.equal(doc.doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize a Date'] = function(test) { - var date = new Date(); - //(2009, 11, 12, 12, 00, 30) - date.setUTCDate(12); - date.setUTCFullYear(2009); - date.setUTCMonth(11 - 1); - date.setUTCHours(12); - date.setUTCMinutes(0); - date.setUTCSeconds(30); - var doc = {doc: date}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.equal(doc.date, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc.date); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize nested doc'] = function(test) { - var doc = { - string: "Strings are great", - decimal: 3.14159265, - bool: true, - integer: 5, - - subObject: { - moreText: "Bacon ipsum dolor.", - longKeylongKeylongKeylongKeylongKeylongKey: "Pork belly." - }, - - subArray: [1,2,3,4,5,6,7,8,9,10], - anotherString: "another string" - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Oid'] = function(test) { - var doc = {doc: new ObjectID()}; - var doc2 = {doc: ObjectID.createFromHexString(doc.doc.toHexString())}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - delete doc.doc.__id; - test.deepEqual(doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly encode Empty Hash'] = function(test) { - var doc = {}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - test.deepEqual(doc, new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Ordered Hash'] = function(test) { - var doc = {doc: {b:1, a:2, c:3, d:4}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var decoded_hash = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data).doc; - var keys = []; - - for(var name in decoded_hash) keys.push(name); - test.deepEqual(['b', 'a', 'c', 'd'], keys); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Regular Expression'] = function(test) { - // Serialize the regular expression - var doc = {doc: /foobar/mi}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc.doc.toString(), doc2.doc.toString()); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize a Binary object'] = function(test) { - var bin = new Binary(); - var string = 'binstring'; - for(var index = 0; index < string.length; index++) { - bin.put(string.charAt(index)); - } - - var doc = {doc: bin}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc.doc.value(), deserialized_data.doc.value()); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize a big Binary object'] = function(test) { - var data = fs.readFileSync("test/gridstore/test_gs_weird_bug.png", 'binary'); - var bin = new Binary(); - bin.write(data); - var doc = {doc: bin}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc.value(), deserialized_data.doc.value()); - test.done(); -} - -/** - * @ignore - */ -exports["Should Correctly Serialize and Deserialize DBRef"] = function(test) { - var oid = new ObjectID(); - var doc = {dbref: new DBRef('namespace', oid, null)}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal("namespace", doc2.dbref.namespace); - test.deepEqual(doc2.dbref.oid.toHexString(), oid.toHexString()); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize partial DBRef'] = function(test) { - var id = new ObjectID(); - var doc = {'name':'something', 'user':{'$ref':'username', '$id': id}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal('something', doc2.name); - test.equal('username', doc2.user.namespace); - test.equal(id.toString(), doc2.user.oid.toString()); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize simple Int'] = function(test) { - var doc = {doc:2147483648}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc, doc2.doc) - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Long Integer'] = function(test) { - var doc = {doc: Long.fromNumber(9223372036854775807)}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc, deserialized_data.doc); - - doc = {doc: Long.fromNumber(-9223372036854775)}; - serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc, deserialized_data.doc); - - doc = {doc: Long.fromNumber(-9223372036854775809)}; - serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc, deserialized_data.doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Deserialize Large Integers as Number not Long'] = function(test) { - function roundTrip(val) { - var doc = {doc: val}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc, deserialized_data.doc); - }; - - roundTrip(Math.pow(2,52)); - roundTrip(Math.pow(2,53) - 1); - roundTrip(Math.pow(2,53)); - roundTrip(-Math.pow(2,52)); - roundTrip(-Math.pow(2,53) + 1); - roundTrip(-Math.pow(2,53)); - roundTrip(Math.pow(2,65)); // Too big for Long. - roundTrip(-Math.pow(2,65)); - roundTrip(9223372036854775807); - roundTrip(1234567890123456800); // Bigger than 2^53, stays a double. - roundTrip(-1234567890123456800); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Long Integer and Timestamp as different types'] = function(test) { - var long = Long.fromNumber(9223372036854775807); - var timestamp = Timestamp.fromNumber(9223372036854775807); - test.ok(long instanceof Long); - test.ok(!(long instanceof Timestamp)); - test.ok(timestamp instanceof Timestamp); - test.ok(!(timestamp instanceof Long)); - - var test_int = {doc: long, doc2: timestamp}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(test_int, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(test_int)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(test_int, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(test_int.doc, deserialized_data.doc); - test.done(); -} - -/** - * @ignore - */ -exports['Should Always put the id as the first item in a hash'] = function(test) { - var hash = {doc: {not_id:1, '_id':2}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(hash, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(hash)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(hash, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - var keys = []; - - for(var name in deserialized_data.doc) { - keys.push(name); - } - - test.deepEqual(['not_id', '_id'], keys); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize a User defined Binary object'] = function(test) { - var bin = new Binary(); - bin.sub_type = BSON.BSON_BINARY_SUBTYPE_USER_DEFINED; - var string = 'binstring'; - for(var index = 0; index < string.length; index++) { - bin.put(string.charAt(index)); - } - - var doc = {doc: bin}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(deserialized_data.doc.sub_type, BSON.BSON_BINARY_SUBTYPE_USER_DEFINED); - test.deepEqual(doc.doc.value(), deserialized_data.doc.value()); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correclty Serialize and Deserialize a Code object'] = function(test) { - var doc = {'doc': {'doc2': new Code('this.a > i', {i:1})}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.doc.doc2.code, deserialized_data.doc.doc2.code); - test.deepEqual(doc.doc.doc2.scope.i, deserialized_data.doc.doc2.scope.i); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly serialize and deserialize and embedded array'] = function(test) { - var doc = {'a':0, - 'b':['tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9', 'tmp10', 'tmp11', 'tmp12', 'tmp13', 'tmp14', 'tmp15', 'tmp16'] - }; - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.a, deserialized_data.a); - test.deepEqual(doc.b, deserialized_data.b); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize UTF8'] = function(test) { - // Serialize utf8 - var doc = { "name" : "本荘由利地域に洪水警報", "name1" : "öüóőúéáűíÖÜÓŐÚÉÁŰÍ", "name2" : "abcdedede"}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc, deserialized_data); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize query object'] = function(test) { - var doc = { count: 'remove_with_no_callback_bug_test', query: {}, fields: null}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc, deserialized_data); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize empty query object'] = function(test) { - var doc = {}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc, deserialized_data); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize array based doc'] = function(test) { - var doc = { b: [ 1, 2, 3 ], _id: new ObjectID() }; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.b, deserialized_data.b) - test.deepEqual(doc, deserialized_data); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize and Deserialize Symbol'] = function(test) { - if(Symbol != null) { - var doc = { b: [ new Symbol('test') ]}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc.b, deserialized_data.b) - test.deepEqual(doc, deserialized_data); - test.ok(deserialized_data.b[0] instanceof Symbol); - } - - test.done(); -} - -/** - * @ignore - */ -exports['Should handle Deeply nested document'] = function(test) { - var doc = {a:{b:{c:{d:2}}}}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var deserialized_data = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc, deserialized_data); - test.done(); -} - -/** - * @ignore - */ -exports['Should handle complicated all typed object'] = function(test) { - // First doc - var date = new Date(); - var oid = new ObjectID(); - var string = 'binstring' - var bin = new Binary() - for(var index = 0; index < string.length; index++) { - bin.put(string.charAt(index)) - } - - var doc = { - 'string': 'hello', - 'array': [1,2,3], - 'hash': {'a':1, 'b':2}, - 'date': date, - 'oid': oid, - 'binary': bin, - 'int': 42, - 'float': 33.3333, - 'regexp': /regexp/, - 'boolean': true, - 'long': date.getTime(), - 'where': new Code('this.a > i', {i:1}), - 'dbref': new DBRef('namespace', oid, 'integration_tests_') - } - - // Second doc - var oid = new ObjectID.createFromHexString(oid.toHexString()); - var string = 'binstring' - var bin = new Binary() - for(var index = 0; index < string.length; index++) { - bin.put(string.charAt(index)) - } - - var doc2 = { - 'string': 'hello', - 'array': [1,2,3], - 'hash': {'a':1, 'b':2}, - 'date': date, - 'oid': oid, - 'binary': bin, - 'int': 42, - 'float': 33.3333, - 'regexp': /regexp/, - 'boolean': true, - 'long': date.getTime(), - 'where': new Code('this.a > i', {i:1}), - 'dbref': new DBRef('namespace', oid, 'integration_tests_') - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); - - for(var i = 0; i < serialized_data2.length; i++) { - require('assert').equal(serialized_data2[i], serialized_data[i]) - } - - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize Complex Nested Object'] = function(test) { - var doc = { email: 'email@email.com', - encrypted_password: 'password', - friends: [ '4db96b973d01205364000006', - '4dc77b24c5ba38be14000002' ], - location: [ 72.4930088, 23.0431957 ], - name: 'Amit Kumar', - password_salt: 'salty', - profile_fields: [], - username: 'amit', - _id: new ObjectID() } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = doc; - doc2._id = ObjectID.createFromHexString(doc2._id.toHexString()); - var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); - - for(var i = 0; i < serialized_data2.length; i++) { - require('assert').equal(serialized_data2[i], serialized_data[i]) - } - - test.done(); -} - -/** - * @ignore - */ -exports['Should correctly massive doc'] = function(test) { - var oid1 = new ObjectID(); - var oid2 = new ObjectID(); - - // JS doc - var doc = { dbref2: new DBRef('namespace', oid1, 'integration_tests_'), - _id: oid2 }; - - var doc2 = { dbref2: new DBRef('namespace', ObjectID.createFromHexString(oid1.toHexString()), 'integration_tests_'), - _id: new ObjectID.createFromHexString(oid2.toHexString()) }; - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize/Deserialize regexp object'] = function(test) { - var doc = {'b':/foobaré/}; - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var serialized_data2 = new BSONDE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - for(var i = 0; i < serialized_data2.length; i++) { - require('assert').equal(serialized_data2[i], serialized_data[i]) - } - - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize/Deserialize complicated object'] = function(test) { - var doc = {a:{b:{c:[new ObjectID(), new ObjectID()]}}, d:{f:1332.3323}}; - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc, doc2) - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize/Deserialize nested object'] = function(test) { - var doc = { "_id" : { "date" : new Date(), "gid" : "6f35f74d2bea814e21000000" }, - "value" : { - "b" : { "countries" : { "--" : 386 }, "total" : 1599 }, - "bc" : { "countries" : { "--" : 3 }, "total" : 10 }, - "gp" : { "countries" : { "--" : 2 }, "total" : 13 }, - "mgc" : { "countries" : { "--" : 2 }, "total" : 14 } - } - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc, doc2) - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize/Deserialize nested object with even more nesting'] = function(test) { - var doc = { "_id" : { "date" : {a:1, b:2, c:new Date()}, "gid" : "6f35f74d2bea814e21000000" }, - "value" : { - "b" : { "countries" : { "--" : 386 }, "total" : 1599 }, - "bc" : { "countries" : { "--" : 3 }, "total" : 10 }, - "gp" : { "countries" : { "--" : 2 }, "total" : 13 }, - "mgc" : { "countries" : { "--" : 2 }, "total" : 14 } - } - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual(doc, doc2) - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly Serialize empty name object'] = function(test) { - var doc = {'':'test', - 'bbbb':1}; - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.equal(doc2[''], 'test'); - test.equal(doc2['bbbb'], 1); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly handle Forced Doubles to ensure we allocate enough space for cap collections'] = function(test) { - if(Double != null) { - var doubleValue = new Double(100); - var doc = {value:doubleValue}; - - // Serialize - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - test.deepEqual({value:100}, doc2); - } - - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly deserialize a message'] = function(test) { - var data = "24000000be00de4428000000010000000800000000000000000000000000000000000000"; - var parent = {bson_deserializer:{"Long":Long, "BSON":BSONSE.BSON}} - var binaryData = new Buffer(hexStringToBinary(data)); - - var doc2 = new MongoReply(parent, binaryData); - test.deepEqual([], doc2.documents); - test.done(); -} - -/** - * @ignore - */ -exports['Should deserialize correctly'] = function(test) { - var doc = { - "_id" : new ObjectID("4e886e687ff7ef5e00000162"), - "str" : "foreign", - "type" : 2, - "timestamp" : ISODate("2011-10-02T14:00:08.383Z"), - "links" : [ - "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" - ] - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc, doc2) - test.done(); -} - -/** - * @ignore - */ -exports['Should correctly serialize and deserialize MinKey and MaxKey values'] = function(test) { - var doc = { - _id : new ObjectID("4e886e687ff7ef5e00000162"), - minKey : new MinKey(), - maxKey : new MaxKey() - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.deepEqual(doc, doc2) - test.ok(doc2.minKey instanceof MinKey); - test.ok(doc2.maxKey instanceof MaxKey); - test.done(); -} - -/** - * @ignore - */ -exports['Should correctly serialize Double value'] = function(test) { - var doc = { - value : new Double(34343.2222) - } - - var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); - var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); - new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); - assertBuffersEqual(test, serialized_data, serialized_data2, 0); - var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data); - - test.ok(doc.value.valueOf(), doc2.value); - test.ok(doc.value.value, doc2.value); - test.done(); -} - -/** - * @ignore - */ -exports['ObjectID should correctly create objects'] = function(test) { - try { - var object1 = ObjectID.createFromHexString('000000000000000000000001') - var object2 = ObjectID.createFromHexString('00000000000000000000001') - test.ok(false); - } catch(err) { - test.ok(err != null); - } - - test.done(); -} - -/** - * @ignore - */ -exports['ObjectID should correctly retrieve timestamp'] = function(test) { - var testDate = new Date(); - var object1 = new ObjectID(); - test.equal(Math.floor(testDate.getTime()/1000), Math.floor(object1.getTimestamp().getTime()/1000)); - test.done(); -} - -/** - * @ignore - */ -exports['Should Correctly throw error on bsonparser errors'] = function(test) { - var data = new Buffer(3); - var parser = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]); - - // Catch to small buffer error - try { - parser.deserialize(data); - test.ok(false); - } catch(err) {} - - data = new Buffer(5); - data[0] = 0xff; - data[1] = 0xff; - // Catch illegal size - try { - parser.deserialize(data); - test.ok(false); - } catch(err) {} - - // Finish up - test.done(); -} - -/** - * A simple example showing the usage of BSON.calculateObjectSize function returning the number of BSON bytes a javascript object needs. - * - * @_class bson - * @_function BSON.calculateObjectSize - * @ignore - */ -exports['Should correctly calculate the size of a given javascript object'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Calculate the size of the object without serializing the function - var size = BSON.calculateObjectSize(doc, false); - test.equal(12, size); - // Calculate the size of the object serializing the function - size = BSON.calculateObjectSize(doc, true); - // Validate the correctness - test.equal(36, size); - test.done(); -} - -/** - * A simple example showing the usage of BSON.calculateObjectSize function returning the number of BSON bytes a javascript object needs. - * - * @_class bson - * @_function calculateObjectSize - * @ignore - */ -exports['Should correctly calculate the size of a given javascript object using instance method'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Create a BSON parser instance - var bson = new BSON(); - // Calculate the size of the object without serializing the function - var size = bson.calculateObjectSize(doc, false); - test.equal(12, size); - // Calculate the size of the object serializing the function - size = bson.calculateObjectSize(doc, true); - // Validate the correctness - test.equal(36, size); - test.done(); -} - -/** - * A simple example showing the usage of BSON.serializeWithBufferAndIndex function. - * - * @_class bson - * @_function BSON.serializeWithBufferAndIndex - * @ignore - */ -exports['Should correctly serializeWithBufferAndIndex a given javascript object'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Calculate the size of the document, no function serialization - var size = BSON.calculateObjectSize(doc, false); - // Allocate a buffer - var buffer = new Buffer(size); - // Serialize the object to the buffer, checking keys and not serializing functions - var index = BSON.serializeWithBufferAndIndex(doc, true, buffer, 0, false); - // Validate the correctness - test.equal(12, size); - test.equal(11, index); - - // Serialize with functions - // Calculate the size of the document, no function serialization - var size = BSON.calculateObjectSize(doc, true); - // Allocate a buffer - var buffer = new Buffer(size); - // Serialize the object to the buffer, checking keys and not serializing functions - var index = BSON.serializeWithBufferAndIndex(doc, true, buffer, 0, true); - // Validate the correctness - test.equal(36, size); - test.equal(35, index); - test.done(); -} - -/** - * A simple example showing the usage of BSON.serializeWithBufferAndIndex function. - * - * @_class bson - * @_function serializeWithBufferAndIndex - * @ignore - */ -exports['Should correctly serializeWithBufferAndIndex a given javascript object using a BSON instance'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Create a BSON parser instance - var bson = new BSON(); - // Calculate the size of the document, no function serialization - var size = bson.calculateObjectSize(doc, false); - // Allocate a buffer - var buffer = new Buffer(size); - // Serialize the object to the buffer, checking keys and not serializing functions - var index = bson.serializeWithBufferAndIndex(doc, true, buffer, 0, false); - // Validate the correctness - test.equal(12, size); - test.equal(11, index); - - // Serialize with functions - // Calculate the size of the document, no function serialization - var size = bson.calculateObjectSize(doc, true); - // Allocate a buffer - var buffer = new Buffer(size); - // Serialize the object to the buffer, checking keys and not serializing functions - var index = bson.serializeWithBufferAndIndex(doc, true, buffer, 0, true); - // Validate the correctness - test.equal(36, size); - test.equal(35, index); - test.done(); -} - -/** - * A simple example showing the usage of BSON.serialize function returning serialized BSON Buffer object. - * - * @_class bson - * @_function BSON.serialize - * @ignore - */ -exports['Should correctly serialize a given javascript object'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Serialize the object to a buffer, checking keys and not serializing functions - var buffer = BSON.serialize(doc, true, true, false); - // Validate the correctness - test.equal(12, buffer.length); - - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = BSON.serialize(doc, true, true, true); - // Validate the correctness - test.equal(36, buffer.length); - test.done(); -} - -/** - * A simple example showing the usage of BSON.serialize function returning serialized BSON Buffer object. - * - * @_class bson - * @_function serialize - * @ignore - */ -exports['Should correctly serialize a given javascript object using a bson instance'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){}} - // Create a BSON parser instance - var bson = new BSON(); - // Serialize the object to a buffer, checking keys and not serializing functions - var buffer = bson.serialize(doc, true, true, false); - // Validate the correctness - test.equal(12, buffer.length); - - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = bson.serialize(doc, true, true, true); - // Validate the correctness - test.equal(36, buffer.length); - test.done(); -} - -/** - * A simple example showing the usage of BSON.deserialize function returning a deserialized Javascript function. - * - * @_class bson - * @_function BSON.deserialize - * @ignore - */ - exports['Should correctly deserialize a buffer using the BSON class level parser'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){ console.log('hello world'); }} - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = BSON.serialize(doc, true, true, true); - // Validate the correctness - test.equal(65, buffer.length); - - // Deserialize the object with no eval for the functions - var deserializedDoc = BSON.deserialize(buffer); - // Validate the correctness - test.equal('object', typeof deserializedDoc.func); - test.equal(1, deserializedDoc.a); - - // Deserialize the object with eval for the functions caching the functions - deserializedDoc = BSON.deserialize(buffer, {evalFunctions:true, cacheFunctions:true}); - // Validate the correctness - test.equal('function', typeof deserializedDoc.func); - test.equal(1, deserializedDoc.a); - test.done(); -} - -/** - * A simple example showing the usage of BSON instance deserialize function returning a deserialized Javascript function. - * - * @_class bson - * @_function deserialize - * @ignore - */ -exports['Should correctly deserialize a buffer using the BSON instance parser'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){ console.log('hello world'); }} - // Create a BSON parser instance - var bson = new BSON(); - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = bson.serialize(doc, true, true, true); - // Validate the correctness - test.equal(65, buffer.length); - - // Deserialize the object with no eval for the functions - var deserializedDoc = bson.deserialize(buffer); - // Validate the correctness - test.equal('object', typeof deserializedDoc.func); - test.equal(1, deserializedDoc.a); - - // Deserialize the object with eval for the functions caching the functions - deserializedDoc = bson.deserialize(buffer, {evalFunctions:true, cacheFunctions:true}); - // Validate the correctness - test.equal('function', typeof deserializedDoc.func); - test.equal(1, deserializedDoc.a); - test.done(); -} - -/** - * A simple example showing the usage of BSON.deserializeStream function returning deserialized Javascript objects. - * - * @_class bson - * @_function BSON.deserializeStream - * @ignore - */ -exports['Should correctly deserializeStream a buffer object'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){ console.log('hello world'); }} - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = BSON.serialize(doc, true, true, true); - // Validate the correctness - test.equal(65, buffer.length); - - // The array holding the number of retuned documents - var documents = new Array(1); - // Deserialize the object with no eval for the functions - var index = BSON.deserializeStream(buffer, 0, 1, documents, 0); - // Validate the correctness - test.equal(65, index); - test.equal(1, documents.length); - test.equal(1, documents[0].a); - test.equal('object', typeof documents[0].func); - - // Deserialize the object with eval for the functions caching the functions - // The array holding the number of retuned documents - var documents = new Array(1); - // Deserialize the object with no eval for the functions - var index = BSON.deserializeStream(buffer, 0, 1, documents, 0, {evalFunctions:true, cacheFunctions:true}); - // Validate the correctness - test.equal(65, index); - test.equal(1, documents.length); - test.equal(1, documents[0].a); - test.equal('function', typeof documents[0].func); - test.done(); -} - -/** - * A simple example showing the usage of BSON instance deserializeStream function returning deserialized Javascript objects. - * - * @_class bson - * @_function deserializeStream - * @ignore - */ -exports['Should correctly deserializeStream a buffer object'] = function(test) { - // Create a simple object - var doc = {a: 1, func:function(){ console.log('hello world'); }} - // Create a BSON parser instance - var bson = new BSON(); - // Serialize the object to a buffer, checking keys and serializing functions - var buffer = bson.serialize(doc, true, true, true); - // Validate the correctness - test.equal(65, buffer.length); - - // The array holding the number of retuned documents - var documents = new Array(1); - // Deserialize the object with no eval for the functions - var index = bson.deserializeStream(buffer, 0, 1, documents, 0); - // Validate the correctness - test.equal(65, index); - test.equal(1, documents.length); - test.equal(1, documents[0].a); - test.equal('object', typeof documents[0].func); - - // Deserialize the object with eval for the functions caching the functions - // The array holding the number of retuned documents - var documents = new Array(1); - // Deserialize the object with no eval for the functions - var index = bson.deserializeStream(buffer, 0, 1, documents, 0, {evalFunctions:true, cacheFunctions:true}); - // Validate the correctness - test.equal(65, index); - test.equal(1, documents.length); - test.equal(1, documents[0].a); - test.equal('function', typeof documents[0].func); - test.done(); -} - -/** - * @ignore - */ -// 'Should Correctly Function' = function(test) { -// var doc = {b:1, func:function() { -// this.b = 2; -// }}; -// -// var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc, false, true); -// -// debug("----------------------------------------------------------------------") -// debug(inspect(serialized_data)) -// -// // var serialized_data2 = new Buffer(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).calculateObjectSize(doc)); -// // new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serializeWithBufferAndIndex(doc, false, serialized_data2, 0); -// // assertBuffersEqual(test, serialized_data, serialized_data2, 0); -// var COUNT = 100000; -// -// // var b = null; -// // eval("b = function(x) { return x+x; }"); -// // var b = new Function("x", "return x+x;"); -// -// console.log(COUNT + "x (objectBSON = BSON.serialize(object))") -// start = new Date -// -// for (i=COUNT; --i>=0; ) { -// var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data, {evalFunctions: true, cacheFunctions:true}); -// } -// -// end = new Date -// console.log("time = ", end - start, "ms -", COUNT * 1000 / (end - start), " ops/sec") -// -// // debug(inspect(new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).functionCache)) -// // -// // var doc2 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data, {evalFunctions: true, cacheFunctions:true}); -// // // test.deepEqual(doc, doc2) -// // // -// // debug(inspect(doc2)) -// // doc2.func() -// // debug(inspect(doc2)) -// // -// // var serialized_data = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).serialize(doc2, false, true); -// // var doc3 = new BSONSE.BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey]).deserialize(serialized_data, {evalFunctions: true, cacheFunctions:true}); -// // -// // debug("-----------------------------------------------") -// // debug(inspect(doc3)) -// -// // var key = "0" -// // for(var i = 1; i < 10000; i++) { -// // key = key + " " + i -// // } -// -// test.done(); -// -// -// // var car = { -// // model : "Volvo", -// // country : "Sweden", -// // -// // isSwedish : function() { -// // return this.country == "Sweden"; -// // } -// // } -// -// }, - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/bson/commands_test.js b/node_modules/reg/node_modules/mongodb/test/bson/commands_test.js deleted file mode 100644 index 13a9a06..0000000 --- a/node_modules/reg/node_modules/mongodb/test/bson/commands_test.js +++ /dev/null @@ -1,129 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - mongoO = require('../../lib/mongodb').pure(), - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - fs = require('fs'), - BSON = mongodb.BSON, - Code = mongoO.Code, - Binary = mongoO.Binary, - Symbol = mongoO.Symbol, - DBRef = mongoO.DBRef, - Double = mongoO.Double, - MinKey = mongoO.MinKey, - MaxKey = mongoO.MaxKey, - Timestamp = mongoO.Timestamp, - Long = mongoO.Long, - ObjectID = mongoO.ObjectID, - DBRef = mongoO.DBRef, - BaseCommand = mongoO.BaseCommand, - InsertCommand = mongoO.InsertCommand, - UpdateCommand = mongoO.UpdateCommand, - DeleteCommand = mongoO.DeleteCommand, - GetMoreCommand = mongoO.GetMoreCommand, - KillCursorCommand = mongoO.KillCursorCommand, - QueryCommand = mongoO.QueryCommand, - MongoReply = mongoO.MongoReply, - BinaryParser = mongoO.BinaryParser; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports['Should Correctly Generate an Insert Command'] = function(test) { - var full_collection_name = "db.users"; - var insert_command = new InsertCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name); - insert_command.add({name: 'peter pan'}); - insert_command.add({name: 'monkey king'}); - // assert the length of the binary - test.equal(81, insert_command.toBinary().length); - test.done(); -} - -exports['Should Correctly Generate an Update Command'] = function(test) { - var full_collection_name = "db.users"; - var flags = UpdateCommand.DB_UPSERT; - var selector = {name: 'peter pan'}; - var document = {name: 'peter pan junior'}; - // Create the command - var update_command = new UpdateCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name, selector, document, flags); - // assert the length of the binary - test.equal(90, update_command.toBinary().length); - test.done(); -} - -exports['Should Correctly Generate a Delete Command'] = function(test) { - var full_collection_name = "db.users"; - var selector = {name: 'peter pan'}; - // Create the command - var delete_command = new DeleteCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name, selector); - // assert the length of the binary - test.equal(58, delete_command.toBinary().length); - test.done(); -} - -exports['Should Correctly Generate a Get More Command'] = function(test) { - var full_collection_name = "db.users"; - var numberToReturn = 100; - var cursorId = Long.fromNumber(10000222); - // Create the command - var get_more_command = new GetMoreCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name, numberToReturn, cursorId); - // assert the length of the binary - test.equal(41, get_more_command.toBinary().length); - test.done(); -} - -exports['Should Correctly Generate a Kill Cursors Command'] = function(test) { - Array.prototype.toXml = function() {} - var cursorIds = [Long.fromNumber(1), Long.fromNumber(10000222)]; - // Create the command - var kill_cursor_command = new KillCursorCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, cursorIds); - // assert the length of the binary - test.equal(40, kill_cursor_command.toBinary().length); - test.done(); -} - -exports['Should Correctly Generate a Query Command'] = function(test) { - var full_collection_name = "db.users"; - var options = QueryCommand.OPTS_SLAVE; - var numberToSkip = 100; - var numberToReturn = 200; - var query = {name:'peter pan'}; - var query_command = new QueryCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name, options, numberToSkip, numberToReturn, query, null); - // assert the length of the binary - test.equal(62, query_command.toBinary().length); - // Generate command with return field filter - query_command = new QueryCommand({bson: new BSON([Long, ObjectID, Binary, Code, DBRef, Symbol, Double, Timestamp, MaxKey, MinKey])}, full_collection_name, options, numberToSkip, numberToReturn, query, { a : 1, b : 1, c : 1}); - test.equal(88, query_command.toBinary().length); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/bson_types_test.js b/node_modules/reg/node_modules/mongodb/test/bson_types_test.js deleted file mode 100644 index ed21cf3..0000000 --- a/node_modules/reg/node_modules/mongodb/test/bson_types_test.js +++ /dev/null @@ -1,215 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); - -var testCase = require('../deps/nodeunit').testCase, - Buffer = require('buffer').Buffer, - gleak = require('../dev/tools/gleak'), - fs = require('fs'), - BSON = mongodb.BSON, - Code = mongodb.Code, - Binary = mongodb.Binary, - Timestamp = mongodb.Timestamp, - Long = mongodb.Long, - MongoReply = mongodb.MongoReply, - ObjectID = mongodb.ObjectID, - Symbol = mongodb.Symbol, - DBRef = mongodb.DBRef, - Double = mongodb.Double, - MinKey = mongodb.MinKey, - MaxKey = mongodb.MaxKey, - BinaryParser = mongodb.BinaryParser; - -var BSONSE = mongodb, - BSONDE = mongodb; - -// for tests -BSONDE.BSON_BINARY_SUBTYPE_DEFAULT = 0; -BSONDE.BSON_BINARY_SUBTYPE_FUNCTION = 1; -BSONDE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -BSONDE.BSON_BINARY_SUBTYPE_UUID = 3; -BSONDE.BSON_BINARY_SUBTYPE_MD5 = 4; -BSONDE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -BSONSE.BSON_BINARY_SUBTYPE_DEFAULT = 0; -BSONSE.BSON_BINARY_SUBTYPE_FUNCTION = 1; -BSONSE.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2; -BSONSE.BSON_BINARY_SUBTYPE_UUID = 3; -BSONSE.BSON_BINARY_SUBTYPE_MD5 = 4; -BSONSE.BSON_BINARY_SUBTYPE_USER_DEFINED = 128; - -var hexStringToBinary = function(string) { - var numberofValues = string.length / 2; - var array = ""; - - for(var i = 0; i < numberofValues; i++) { - array += String.fromCharCode(parseInt(string[i*2] + string[i*2 + 1], 16)); - } - return array; -} - -var assertBuffersEqual = function(test, buffer1, buffer2) { - if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2); - - for(var i = 0; i < buffer1.length; i++) { - test.equal(buffer1[i], buffer2[i]); - } -} - -/** - * Module for parsing an ISO 8601 formatted string into a Date object. - */ -var ISODate = function (string) { - var match; - - if (typeof string.getTime === "function") - return string; - else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) { - var date = new Date(); - date.setUTCFullYear(Number(match[1])); - date.setUTCMonth(Number(match[3]) - 1 || 0); - date.setUTCDate(Number(match[5]) || 0); - date.setUTCHours(Number(match[7]) || 0); - date.setUTCMinutes(Number(match[8]) || 0); - date.setUTCSeconds(Number(match[10]) || 0); - date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0); - - if (match[13] && match[13] !== "Z") { - var h = Number(match[16]) || 0, - m = Number(match[17]) || 0; - - h *= 3600000; - m *= 60000; - - var offset = h + m; - if (match[15] == "+") - offset = -offset; - - date = new Date(date.valueOf() + offset); - } - - return date; - } else - throw new Error("Invalid ISO 8601 date given.", __filename); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -/** - * A simple example showing the usage of the binary put method. - * - * @_class binary - * @_function put - * @ignore - */ -exports.shouldCorrectUsePutForBinaryType = function(test) { - // Create an empty Binary object - var binary = new Binary(new Buffer(''), BSON.BSON_BINARY_SUBTYPE_DEFAULT); - // Write some character to the Binary value - binary.put('h'); - binary.put('e'); - binary.put('l'); - binary.put('l'); - binary.put('o'); - // Validate the content of the binary - test.equal('hello', binary.toString('ascii')); - test.done(); -} - -/** - * A simple example showing the usage of the binary write method. - * - * @_class binary - * @_function write - * @ignore - */ -exports.shouldCorrectUseWriteForBinaryType = function(test) { - // Create an empty Binary object - var binary = new Binary(new Buffer(''), BSON.BSON_BINARY_SUBTYPE_DEFAULT); - // Write some data to the binary - binary.write('hello', 0); - // Validate the content of the binary - test.equal('hello', binary.toString('ascii')); - test.done(); -} - -/** - * A simple example showing the usage of the binary read method. - * - * @_class binary - * @_function read - * @ignore - */ -exports.shouldCorrectUseReadForBinaryType = function(test) { - // Create an empty Binary object - var binary = new Binary(new Buffer(''), BSON.BSON_BINARY_SUBTYPE_DEFAULT); - // Write some data to the binary - binary.write('hello', 0); - // Read a couple of characters from the binary - var data = binary.read(1, 2); - // Validate the content of the binary - test.equal('el', data.toString('ascii')); - test.done(); -} - -/** - * A simple example showing the usage of the binary value method. - * - * @_class binary - * @_function value - * @ignore - */ -exports.shouldCorrectUseValueForBinaryType = function(test) { - // Create an empty Binary object - var binary = new Binary(new Buffer(''), BSON.BSON_BINARY_SUBTYPE_DEFAULT); - // Write some data to the binary - binary.write('hello', 0); - // Validate the content of the binary - test.equal('hello', binary.value()); - test.done(); -} - -/** - * A simple example showing the usage of the binary length method. - * - * @_class binary - * @_function length - * @ignore - */ -exports.shouldCorrectUseLengthForBinaryType = function(test) { - // Create an empty Binary object - var binary = new Binary(new Buffer(''), BSON.BSON_BINARY_SUBTYPE_DEFAULT); - // Write some data to the binary - binary.write('hello'); - // Validate the content of the binary - test.equal(5, binary.length()); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/certificates/mycert.pem b/node_modules/reg/node_modules/mongodb/test/certificates/mycert.pem deleted file mode 100644 index 954627c..0000000 --- a/node_modules/reg/node_modules/mongodb/test/certificates/mycert.pem +++ /dev/null @@ -1,36 +0,0 @@ ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: DES-EDE3-CBC,5BC1D8935109F6C8 - -cbr7PTUV8ySzjBsvtCLng+0m7aez0D/Q76JnsW265oLxwqqID9mgS3rIZUgbu2SQ -+rfTTG+xcrONJs41Pbao1D1BNcUrmLF+8pl6055xFOPWrE1cxHQRShlhgG/pLVE3 -JqLFLV4Pd8Tf+o3FwbZ3zqgqwMPVZN/TLfzw94qcrXiidNvWuWf3oyU4w+CzD4Vt -f9HYNOeZWCUtaGGM5koUU/qu/RYQdKXZTRPz9wCHTjSsrznE4BpAJgtBbaOpr850 -c3WP48aveK9NZ9aoR1c+BW6MN+HPN2HhwA9rQUBSwfwlVVxxY1Ir2ArbP7fStlvK -TRtuE7Ro0ZEOUiHB5c9X7p6clKgshP7K19ZG6O0ns1P9d9z7l35f1WG/XQxA66tg -h8haN8nOtPJfrAyn5NcmOS2kTA0kL6Lk2TWwqoVErvpCRgdyhQ94GxjMiHLvkfxx -z5fVQqoXuYV8O6ozfdx+58qJnRTLC1cHf8iwWc9sDE/IP9OTpxwMUBKX4EYOL8MQ -4pjv0qnD/PQN4B5CbQ0RViBLykl22SScxqS3Zq14/sItEjM44ctjgAfmoPZSElTz -n9zhc8VQzgyjuNRt02xAi+tx2RD5I44ylm7QTYnXdWVgftnSgY+Ir4npTK5bnxIB -b9CLPljXbj8k5utoTyFkZa+bRES3a3+MEq5dNFRb0neQ3nJXqB83hMEDE35XWbU0 -gJwG7KsVS6Vr3SfBi47fsoIH1Ii92hZxWrtbTlzjy884zSps+mTWGA6TuU8jb6jn -b2JyNJDhVqDk19DPP+TtMv+GgXuoj7EXenQbwRXO/NVyaWpyBU7dHA== ------END RSA PRIVATE KEY----- ------BEGIN CERTIFICATE----- -MIIC4TCCAkqgAwIBAgIJAM0r5teNISyyMA0GCSqGSIb3DQEBBQUAMFUxCzAJBgNV -BAYTAkVTMRIwEAYDVQQIEwlCYXJjZWxvbmExEjAQBgNVBAcTCUJhcmNlbG9uYTEO -MAwGA1UEChMFMTBnZW4xDjAMBgNVBAMTBTEwZ2VuMB4XDTExMTIwMjEwMTcwM1oX -DTEyMTIwMTEwMTcwM1owVTELMAkGA1UEBhMCRVMxEjAQBgNVBAgTCUJhcmNlbG9u -YTESMBAGA1UEBxMJQmFyY2Vsb25hMQ4wDAYDVQQKEwUxMGdlbjEOMAwGA1UEAxMF -MTBnZW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPBY5u20gJQAXw/m3hiY -kC1zqDt4lahjUauPUDeshceAuBIgQLePZwckR3caPqS1a1uPsKMQIKN1E/z781MY -iAdgRPwpQfKt1MRZRZdUVzOsGQdDtF1XEnIbQgdiahbXVqVeULLLuypWnw1ceAys -ESu8kWqPAm1eu+utqJOENXWpAgMBAAGjgbgwgbUwHQYDVR0OBBYEFN1iayQf9puR -3OZxEy/FtFv6YSRoMIGFBgNVHSMEfjB8gBTdYmskH/abkdzmcRMvxbRb+mEkaKFZ -pFcwVTELMAkGA1UEBhMCRVMxEjAQBgNVBAgTCUJhcmNlbG9uYTESMBAGA1UEBxMJ -QmFyY2Vsb25hMQ4wDAYDVQQKEwUxMGdlbjEOMAwGA1UEAxMFMTBnZW6CCQDNK+bX -jSEssjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAOvATDKZ95epzVjV -qGnaHgu4u6NJuvZlGmBl2Mq/EA2ymw2LL+Pt38BqyQWvO/5TlxF1EFhH3kl6RENw -9U7C+w8tqhQL3hQsTASdX9gTczaYgHwHsKLc2JFcC7J2ffXM0aW5wUCKUwvvtf/h -7rUWJPi+evtVGTxRhCQGJcoI9lEK ------END CERTIFICATE----- diff --git a/node_modules/reg/node_modules/mongodb/test/collection_test.js b/node_modules/reg/node_modules/mongodb/test/collection_test.js deleted file mode 100644 index e5c15ca..0000000 --- a/node_modules/reg/node_modules/mongodb/test/collection_test.js +++ /dev/null @@ -1,1189 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Long = require('../lib/mongodb/bson/long').Long, - Step = require("../deps/step/lib/step"), - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * Example of a simple document save with safe set to false - * - * @_class collection - * @_function save - * @ignore - */ -exports.shouldCorrectlySaveASimpleDocument = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch the collection - db.collection("save_a_simple_document", function(err, collection) { - - // Save a document with no safe option - collection.save({hello:'world'}); - - // Wait for a second - setTimeout(function() { - - // Find the saved document - collection.findOne({hello:'world'}, function(err, item) { - test.equal(null, err); - test.equal('world', item.hello); - db.close(); - test.done(); - }); - }, 1000); - }); - }); -} - -/** - * Example of a simple document save and then resave with safe set to true - * - * @_class collection - * @_function save - * @ignore - */ -exports.shouldCorrectlySaveASimpleDocumentModifyItAndResaveIt = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch the collection - db.collection("save_a_simple_document_modify_it_and_resave_it", function(err, collection) { - - // Save a document with no safe option - collection.save({hello:'world'}, {safe:true}, function(err, result) { - - // Find the saved document - collection.findOne({hello:'world'}, function(err, item) { - test.equal(null, err); - test.equal('world', item.hello); - - // Update the document - item['hello2'] = 'world2'; - - // Save the item with the additional field - collection.save(item, {safe:true}, function(err, result) { - - // Find the changed document - collection.findOne({hello:'world'}, function(err, item) { - test.equal(null, err); - test.equal('world', item.hello); - test.equal('world2', item.hello2); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectExecuteBasicCollectionMethods = function(test) { - client.createCollection('test_collection_methods', function(err, collection) { - // Verify that all the result are correct coming back (should contain the value ok) - test.equal('test_collection_methods', collection.collectionName); - // Let's check that the collection was created correctly - client.collectionNames(function(err, documents) { - var found = false; - documents.forEach(function(document) { - if(document.name == "integration_tests_.test_collection_methods") found = true; - }); - test.ok(true, found); - // Rename the collection and check that it's gone - client.renameCollection("test_collection_methods", "test_collection_methods2", function(err, reply) { - test.equal(null, err); - // Drop the collection and check that it's gone - client.dropCollection("test_collection_methods2", function(err, result) { - test.equal(true, result); - test.done(); - }) - }); - }); - }) -} - -/** - * @ignore - */ -exports.shouldAccessToCollections = function(test) { - // Create two collections - client.createCollection('test.spiderman', function(r) { - client.createCollection('test.mario', function(r) { - // Insert test documents (creates collections) - client.collection('test.spiderman', function(err, spiderman_collection) { - spiderman_collection.insert({foo:5}, {safe:true}, function(err, r) { - - client.collection('test.mario', function(err, mario_collection) { - mario_collection.insert({bar:0}, {safe:true}, function(err, r) { - // Assert collections - client.collections(function(err, collections) { - var found_spiderman = false; - var found_mario = false; - var found_does_not_exist = false; - - collections.forEach(function(collection) { - if(collection.collectionName == "test.spiderman") found_spiderman = true; - if(collection.collectionName == "test.mario") found_mario = true; - if(collection.collectionName == "does_not_exist") found_does_not_exist = true; - }); - - test.ok(found_spiderman); - test.ok(found_mario); - test.ok(!found_does_not_exist); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyDropCollection = function(test) { - client.createCollection('test_drop_collection2', function(err, r) { - client.dropCollection('test_drop_collection', function(err, r) { - test.ok(err instanceof Error); - test.equal("ns not found", err.message); - var found = false; - // Ensure we don't have the collection in the set of names - client.collectionNames(function(err, replies) { - replies.forEach(function(err, document) { - if(document.name == "test_drop_collection") { - found = true; - return; - } - }); - // If we have an instance of the index throw and error - if(found) throw new Error("should not fail"); - // Let's close the db - test.done(); - }); - }); - }); -} - -/** - * Example of a simple document save and then resave with safe set to true - * - * @_class collection - * @_function drop - * @ignore - */ -exports.shouldCorrectlyDropCollectionWithDropFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('test_other_drop', function(err, collection) { - test.equal(null, err); - - // Drop the collection - collection.drop(function(err, reply) { - - // Ensure we don't have the collection in the set of names - db.collectionNames(function(err, replies) { - - var found = false; - // For each collection in the list of collection names in this db look for the - // dropped collection - replies.forEach(function(document) { - if(document.name == "test_other_drop") { - found = true; - return; - } - }); - - // Ensure the collection is not found - test.equal(false, found); - - // Let's close the db - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyRetriveCollectionNames = function(test) { - client.createCollection('test_collection_names', function(err, r) { - client.collectionNames(function(err, documents) { - var found = false; - var found2 = false; - documents.forEach(function(document) { - if(document.name == MONGODB + '.test_collection_names') found = true; - }); - test.ok(found); - // Insert a document in an non-existing collection should create the collection - client.collection('test_collection_names2', function(err, collection) { - collection.insert({a:1}, {safe:true}, function(err, r) { - client.collectionNames(function(err, documents) { - documents.forEach(function(document) { - if(document.name == MONGODB + '.test_collection_names2') found = true; - if(document.name == MONGODB + '.test_collection_names') found2 = true; - }); - - test.ok(found); - test.ok(found2); - // Let's close the db - test.done(); - }); - }) - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyRetrieveCollectionInfo = function(test) { - client.createCollection('test_collections_info', function(err, r) { - client.collectionsInfo(function(err, cursor) { - test.ok((cursor instanceof Cursor)); - // Fetch all the collection info - cursor.toArray(function(err, documents) { - test.ok(documents.length > 1); - - var found = false; - documents.forEach(function(document) { - if(document.name == MONGODB + '.test_collections_info') found = true; - }); - test.ok(found); - // Let's close the db - test.done(); - }); - }); - }); -} - -/** - * An example returning the options for a collection. - * - * @_class collection - * @_function options - */ -exports.shouldCorrectlyRetriveCollectionOptions = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection that we are getting the options back from - db.createCollection('test_collection_options', {'capped':true, 'size':1024}, function(err, collection) { - test.ok(collection instanceof Collection); - test.equal('test_collection_options', collection.collectionName); - - // Let's fetch the collection options - collection.options(function(err, options) { - test.equal(true, options.capped); - test.equal(1024, options.size); - test.equal("test_collection_options", options.create); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * An example showing how to establish if it's a capped collection - * - * @_class collection - * @_function isCapped - */ -exports.shouldCorrectlyExecuteIsCapped = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection that we are getting the options back from - db.createCollection('test_collection_is_capped', {'capped':true, 'size':1024}, function(err, collection) { - test.ok(collection instanceof Collection); - test.equal('test_collection_is_capped', collection.collectionName); - - // Let's fetch the collection options - collection.isCapped(function(err, capped) { - test.equal(true, capped); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * An example showing the use of the indexExists function for a single index name and a list of index names. - * - * @_class collection - * @_function indexExists - */ -exports.shouldCorrectlyExecuteIndexExists = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection that we are getting the options back from - db.createCollection('test_collection_index_exists', function(err, collection) { - test.equal(null, err); - - // Create an index on the collection - collection.createIndex('a', function(err, indexName) { - - // Let's test to check if a single index exists - collection.indexExists("a_1", function(err, result) { - test.equal(true, result); - - // Let's test to check if multiple indexes are available - collection.indexExists(["a_1", "_id_"], function(err, result) { - test.equal(true, result); - - // Check if a non existing index exists - collection.indexExists("c_1", function(err, result) { - test.equal(false, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldEnsureStrictAccessCollection = function(test) { - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - test.equal(true, error_client.strict); - - error_client.open(function(err, error_client) { - error_client.collection('does-not-exist', function(err, collection) { - test.ok(err instanceof Error); - test.equal("Collection does-not-exist does not exist. Currently in strict mode.", err.message); - }); - - error_client.createCollection('test_strict_access_collection', function(err, collection) { - error_client.collection('test_strict_access_collection', function(err, collection) { - test.ok(collection instanceof Collection); - // Let's close the db - error_client.close(); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldPerformStrictCreateCollection = function(test) { - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - test.equal(true, error_client.strict); - - error_client.open(function(err, error_client) { - error_client.createCollection('test_strict_create_collection', function(err, collection) { - test.ok(collection instanceof Collection); - - // Creating an existing collection should fail - error_client.createCollection('test_strict_create_collection', function(err, collection) { - test.ok(err instanceof Error); - test.equal("Collection test_strict_create_collection already exists. Currently in strict mode.", err.message); - - // Switch out of strict mode and try to re-create collection - error_client.strict = false; - error_client.createCollection('test_strict_create_collection', function(err, collection) { - test.ok(collection instanceof Collection); - - // Let's close the db - error_client.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldFailToInsertDueToIllegalKeys = function(test) { - client.createCollection('test_invalid_key_names', function(err, collection) { - // Legal inserts - collection.insert([{'hello':'world'}, {'hello':{'hello':'world'}}], {safe:true}, function(err, r) { - // Illegal insert for key - collection.insert({'$hello':'world'}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key $hello must not start with '$'", err.message); - - collection.insert({'hello':{'$hello':'world'}}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key $hello must not start with '$'", err.message); - - collection.insert({'he$llo':'world'}, {safe:true}, function(err, docs) { - test.ok(docs[0].constructor == Object); - - collection.insert({'hello':{'hell$o':'world'}}, {safe:true}, function(err, docs) { - test.ok(err == null); - - collection.insert({'.hello':'world'}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key .hello must not contain '.'", err.message); - - collection.insert({'hello':{'.hello':'world'}}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key .hello must not contain '.'", err.message); - - collection.insert({'hello.':'world'}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key hello. must not contain '.'", err.message); - - collection.insert({'hello':{'hello.':'world'}}, {safe:true}, function(err, doc) { - test.ok(err instanceof Error); - test.equal("key hello. must not contain '.'", err.message); - // Let's close the db - test.done(); - }); - }); - }); - }); - }) - }) - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldFailDueToIllegalCollectionNames = function(test) { - client.collection(5, function(err, collection) { - test.equal("collection name must be a String", err.message); - }); - - client.collection("", function(err, collection) { - test.equal("collection names cannot be empty", err.message); - }); - - client.collection("te$t", function(err, collection) { - test.equal("collection names must not contain '$'", err.message); - }); - - client.collection(".test", function(err, collection) { - test.equal("collection names must not start or end with '.'", err.message); - }); - - client.collection("test.", function(err, collection) { - test.equal("collection names must not start or end with '.'", err.message); - }); - - client.collection("test..t", function(err, collection) { - test.equal("collection names cannot be empty", err.message); - test.done(); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCountOnNonExistingCollection = function(test) { - client.collection('test_multiple_insert_2', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - // Let's close the db - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteSave = function(test) { - client.createCollection('test_save', function(err, collection) { - var doc = {'hello':'world'}; - collection.save(doc, {safe:true}, function(err, docs) { - test.ok(docs._id instanceof ObjectID || Object.prototype.toString.call(docs._id) === '[object ObjectID]'); - - collection.count(function(err, count) { - test.equal(1, count); - doc = docs; - - collection.save(doc, {safe:true}, function(err, doc2) { - - collection.count(function(err, count) { - test.equal(1, count); - - collection.findOne(function(err, doc3) { - test.equal('world', doc3.hello); - - doc3.hello = 'mike'; - - collection.save(doc3, {safe:true}, function(err, doc4) { - collection.count(function(err, count) { - test.equal(1, count); - - collection.findOne(function(err, doc5) { - test.equal('mike', doc5.hello); - - // Save another document - collection.save({hello:'world'}, {safe:true}, function(err, doc) { - collection.count(function(err, count) { - test.equal(2, count); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveDocumentWithLongValue = function(test) { - client.createCollection('test_save_long', function(err, collection) { - collection.insert({'x':Long.fromNumber(9223372036854775807)}, {safe:true}, function(err, r) { - collection.findOne(function(err, doc) { - test.ok(Long.fromNumber(9223372036854775807).equals(doc.x)); - // Let's close the db - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldSaveObjectThatHasIdButDoesNotExistInCollection = function(test) { - client.createCollection('test_save_with_object_that_has_id_but_does_not_actually_exist_in_collection', function(err, collection) { - var a = {'_id':'1', 'hello':'world'}; - collection.save(a, {safe:true}, function(err, docs) { - collection.count(function(err, count) { - test.equal(1, count); - - collection.findOne(function(err, doc) { - test.equal('world', doc.hello); - - doc.hello = 'mike'; - collection.save(doc, {safe:true}, function(err, doc) { - collection.count(function(err, count) { - test.equal(1, count); - }); - - collection.findOne(function(err, doc) { - test.equal('mike', doc.hello); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformUpsert = function(test) { - client.createCollection('test_should_correctly_do_upsert', function(err, collection) { - var id = new ObjectID(null) - var doc = {_id:id, a:1}; - - Step( - function test1() { - var self = this; - - collection.update({"_id":id}, doc, {upsert:true, safe:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - collection.findOne({"_id":id}, self); - }); - }, - - function test2(err, doc) { - var self = this; - test.equal(1, doc.a); - - id = new ObjectID(null) - doc = {_id:id, a:2}; - - collection.update({"_id":id}, doc, {safe:true, upsert:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - collection.findOne({"_id":id}, self); - }); - }, - - function test3(err, doc2) { - var self = this; - test.equal(2, doc2.a); - - collection.update({"_id":id}, doc2, {safe:true, upsert:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - collection.findOne({"_id":id}, function(err, doc) { - test.equal(2, doc.a); - test.done(); - }); - }); - } - ); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyUpdateWithNoDocs = function(test) { - client.createCollection('test_should_correctly_do_update_with_no_docs', function(err, collection) { - var id = new ObjectID(null) - var doc = {_id:id, a:1}; - collection.update({"_id":id}, doc, {safe:true}, function(err, numberofupdateddocs) { - test.equal(null, err); - test.equal(0, numberofupdateddocs); - - test.done(); - }); - }); -} - -/** - * Example of a simple document update with safe set to false on an existing document - * - * @_class collection - * @_function update - */ -exports.shouldCorrectlyUpdateASimpleDocument = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Get a collection - db.collection('update_a_simple_document', function(err, collection) { - - // Insert a document, then update it - collection.insert({a:1}, {safe:true}, function(err, doc) { - - // Update the document with an atomic operator - collection.update({a:1}, {$set:{b:2}}); - - // Wait for a second then fetch the document - setTimeout(function() { - - // Fetch the document that we modified - collection.findOne({a:1}, function(err, item) { - test.equal(null, err); - test.equal(1, item.a); - test.equal(2, item.b); - db.close(); - test.done(); - }); - }, 1000); - }) - }); - }); -} - -/** - * Example of a simple document update using upsert (the document will be inserted if it does not exist) - * - * @_class collection - * @_function update - * @ignore - */ -exports.shouldCorrectlyUpsertASimpleDocument = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Get a collection - db.collection('update_a_simple_document_upsert', function(err, collection) { - - // Update the document using an upsert operation, ensuring creation if it does not exist - collection.update({a:1}, {b:2, a:1}, {upsert:true, safe:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - // Fetch the document that we modified and check if it got inserted correctly - collection.findOne({a:1}, function(err, item) { - test.equal(null, err); - test.equal(1, item.a); - test.equal(2, item.b); - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * Example of an update across multiple documents using the multi option. - * - * @_class collection - * @_function update - * @ignore - */ -exports.shouldCorrectlyUpdateMultipleDocuments = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Get a collection - db.collection('update_a_simple_document_multi', function(err, collection) { - - // Insert a couple of documentations - collection.insert([{a:1, b:1}, {a:1, b:2}], {safe:true}, function(err, result) { - - // Update multiple documents using the multi option - collection.update({a:1}, {$set:{b:0}}, {safe:true, multi:true}, function(err, numberUpdated) { - test.equal(null, err); - test.equal(2, numberUpdated); - - // Fetch all the documents and verify that we have changed the b value - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(1, items[0].a); - test.equal(0, items[0].b); - test.equal(1, items[1].a); - test.equal(0, items[1].b); - - db.close(); - test.done(); - }); - }) - }); - }); - }); -} - -/** - * Example of running the distinct command against a collection - * - * @_class collection - * @_function distinct - * @ignore - */ -exports.shouldCorrectlyHandleDistinctIndexes = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Crete the collection for the distinct example - db.createCollection('simple_key_based_distinct', function(err, collection) { - - // Insert documents to perform distinct against - collection.insert([{a:0, b:{c:'a'}}, {a:1, b:{c:'b'}}, {a:1, b:{c:'c'}}, - {a:2, b:{c:'a'}}, {a:3}, {a:3}], {safe:true}, function(err, ids) { - - // Peform a distinct query against the a field - collection.distinct('a', function(err, docs) { - test.deepEqual([0, 1, 2, 3], docs.sort()); - - // Perform a distinct query against the sub-field b.c - collection.distinct('b.c', function(err, docs) { - test.deepEqual(['a', 'b', 'c'], docs.sort()); - - db.close(); - test.done(); - }); - }); - }) - }); - }); -} - -/** - * Example of running the distinct command against a collection with a filter query - * - * @_class collection - * @_function distinct - * @ignore - */ -exports.shouldCorrectlyHandleDistinctIndexesWithSubQueryFilter = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Crete the collection for the distinct example - db.createCollection('simple_key_based_distinct_sub_query_filter', function(err, collection) { - - // Insert documents to perform distinct against - collection.insert([{a:0, b:{c:'a'}}, {a:1, b:{c:'b'}}, {a:1, b:{c:'c'}}, - {a:2, b:{c:'a'}}, {a:3}, {a:3}, {a:5, c:1}], {safe:true}, function(err, ids) { - - // Peform a distinct query with a filter against the documents - collection.distinct('a', {c:1}, function(err, docs) { - test.deepEqual([5], docs.sort()); - - db.close(); - test.done(); - }); - }) - }); - }); -} - -/** - * Example of running simple count commands against a collection. - * - * @_class collection - * @_function count - * @ignore - */ -exports.shouldCorrectlyDoSimpleCountExamples = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Crete the collection for the distinct example - db.createCollection('simple_count_example', function(err, collection) { - - // Insert documents to perform distinct against - collection.insert([{a:1}, {a:2}, {a:3}, {a:4, b:1}], {safe:true}, function(err, ids) { - - // Perform a total count command - collection.count(function(err, count) { - test.equal(null, err); - test.equal(4, count); - - // Peform a partial account where b=1 - collection.count({b:1}, function(err, count) { - test.equal(null, err); - test.equal(1, count); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteInsertUpdateDeleteSafeMode = function(test) { - client.createCollection('test_should_execute_insert_update_delete_safe_mode', function(err, collection) { - test.ok(collection instanceof Collection); - test.equal('test_should_execute_insert_update_delete_safe_mode', collection.collectionName); - - collection.insert({i:1}, {safe:true}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]._id.toHexString().length == 24); - - // Update the record - collection.update({i:1}, {"$set":{i:2}}, {safe:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - // Remove safely - collection.remove({}, {safe:true}, function(err, result) { - test.equal(null, err); - - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldPerformMultipleSaves = function(test) { - client.createCollection("multiple_save_test", function(err, collection) { - var doc = { - name: 'amit', - text: 'some text' - }; - - //insert new user - collection.save(doc, {safe:true}, function(err, r) { - collection.find({}, {name: 1}).limit(1).toArray(function(err, users){ - var user = users[0] - - if(err) { - throw new Error(err) - } else if(user) { - user.pants = 'worn' - - collection.save(user, {safe:true}, function(err, result){ - test.equal(null, err); - test.equal(1, result); - - test.done(); - }) - } - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveDocumentWithNestedArray = function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, db) { - db.createCollection("save_error_on_save_test", function(err, collection) { - // Create unique index for username - collection.createIndex([['username', 1]], true, function(err, result) { - var doc = { - email: 'email@email.com', - encrypted_password: 'password', - friends: - [ '4db96b973d01205364000006', - '4db94a1948a683a176000001', - '4dc77b24c5ba38be14000002' ], - location: [ 72.4930088, 23.0431957 ], - name: 'Amit Kumar', - password_salt: 'salty', - profile_fields: [], - username: 'amit' }; - //insert new user - collection.save(doc, {safe:true}, function(err, doc) { - - collection.find({}).limit(1).toArray(function(err, users) { - test.equal(null, err); - var user = users[0] - user.friends.splice(1,1) - - collection.save(user, function(err, doc) { - test.equal(null, err); - - // Update again - collection.update({_id:new ObjectID(user._id.toString())}, {friends:user.friends}, {upsert:true, safe:true}, function(err, result) { - test.equal(null, err); - test.equal(1, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldPeformCollectionRemoveWithNoCallback = function(test) { - client.collection("remove_with_no_callback_bug_test", function(err, collection) { - collection.save({a:1}, {safe:true}, function(){ - collection.save({b:1}, {safe:true}, function(){ - collection.save({c:1}, {safe:true}, function(){ - collection.remove({a:1}, {safe:true}, function() { - // Let's perform a count - collection.count(function(err, count) { - test.equal(null, err); - test.equal(2, count); - test.done(); - }); - }) - }); - }); - }); - }); -}, - -/** - * Example of retrieving a collections indexes - * - * @_class collection - * @_function indexes - * @ignore - */ -exports.shouldCorrectlyRetriveACollectionsIndexes = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Crete the collection for the distinct example - db.createCollection('simple_key_based_distinct', function(err, collection) { - - // Create a geo 2d index - collection.ensureIndex({loc:"2d"}, function(err, result) { - test.equal(null, err); - - // Create a simple single field index - collection.ensureIndex({a:1}, function(err, result) { - test.equal(null, err); - - // List all of the indexes on the collection - collection.indexes(function(err, indexes) { - test.equal(3, indexes.length); - - db.close(); - test.done(); - }); - }) - }) - }); - }); -} - -/** - * Example of retrieving a collections stats - * - * @_class collection - * @_function stats - * @ignore - */ -exports.shouldCorrectlyReturnACollectionsStats = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Crete the collection for the distinct example - db.createCollection('collection_stats_test', function(err, collection) { - - // Insert some documents - collection.insert([{a:1}, {hello:'world'}], {safe:true}, function(err, result) { - - // Retrieve the statistics for the collection - collection.stats(function(err, stats) { - test.equal(2, stats.count); - - db.close(); - test.done(); - }); - }); - }); - }); -} - - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/connect_test.js b/node_modules/reg/node_modules/mongodb/test/connect_test.js deleted file mode 100644 index 9fd8252..0000000 --- a/node_modules/reg/node_modules/mongodb/test/connect_test.js +++ /dev/null @@ -1,148 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - connect = mongodb.connect, - gleak = require('../dev/tools/gleak'), - Script = require('vm'), - Collection = mongodb.Collection, - Server = mongodb.Server, - Step = require("../deps/step/lib/step"); - -var MONGODB = 'integration_tests'; -var clientUrl = 'mongo://localhost:27017/' + MONGODB + (useSSL == true ? '?ssl=true' : ''); - -/** - * @ignore - */ -function connectionTester(test, testName) { - return function(err, db) { - test.equal(err, null); - db.collection(testName, function(err, collection) { - test.equal(err, null); - var doc = {foo:123}; - collection.insert({foo:123}, {safe:true}, function(err, docs) { - test.equal(err, null); - db.dropDatabase(function(err, done) { - db.close(); - test.equal(err, null); - test.ok(done); - test.done(); - }); - }); - }); - }; -}; - -/** - * @ignore - */ -exports.testConnectNoOptions = function(test) { - connect(clientUrl, connectionTester(test, 'testConnectNoOptions')); -}; - -/** - * @ignore - */ -exports.testConnectDbOptions = function(test) { - connect(clientUrl, - { db: {native_parser: (process.env['TEST_NATIVE'] != null)} }, - connectionTester(test, 'testConnectDbOptions')); -}; - -/** - * @ignore - */ -exports.testConnectServerOptions = function(test) { - connect(clientUrl, - { server: {auto_reconnect: true, poolSize: 4} }, - connectionTester(test, 'testConnectServerOptions')); -}; - -/** - * @ignore - */ -exports.testConnectAllOptions = function(test) { - connect(clientUrl, - { server: {auto_reconnect: true, poolSize: 4}, - db: {native_parser: (process.env['TEST_NATIVE'] != null)} }, - connectionTester(test, 'testConnectAllOptions')); -}; - -/** - * @ignore - */ -exports.testConnectGoodAuth = function(test) { - var user = 'testConnectGoodAuth', password = 'password'; - // First add a user. - connect(clientUrl, function(err, db) { - test.equal(err, null); - db.addUser(user, password, function(err, result) { - test.equal(err, null); - db.close(); - restOfTest(); - }); - }); - - function restOfTest() { - var url = 'mongo://' + user + ':' + password + '@localhost:27017/' + MONGODB + (useSSL == true ? '?ssl=true' : ''); - connect(url, connectionTester(test, 'testConnectGoodAuth')); - } -}; - -/** - * @ignore - */ -exports.testConnectBadAuth = function(test) { - var url = 'mongo://slithy:toves@localhost:27017/' + MONGODB + (useSSL == true ? '?ssl=true' : ''); - connect(url, function(err, db) { - test.ok(err); - test.ok(db); - db.close(); - test.done(); - }); -}; - -/** - * @ignore - */ -exports.testConnectBadUrl = function(test) { - test.throws(function() { - connect('mango://localhost:27017/' + MONGODB, function(err, db) { - test.ok(false, 'Bad URL!'); - }); - }); - test.done(); -}; - -/** - * Example of a simple url connection string. - * - * @_class db - * @_function Db.connect - * @ignore - */ -exports.shouldCorrectlyDoSimpleCountExamples = function(test) { - // Connect to the server - Db.connect('mongodb://localhost:27017/integration_tests' + (useSSL == true ? '?ssl=true' : ''), function(err, db) { - test.equal(null, err); - - db.close(); - test.done(); - }); -} - - -/** - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} diff --git a/node_modules/reg/node_modules/mongodb/test/connection/connection_pool_test.js b/node_modules/reg/node_modules/mongodb/test/connection/connection_pool_test.js deleted file mode 100644 index fe34beb..0000000 --- a/node_modules/reg/node_modules/mongodb/test/connection/connection_pool_test.js +++ /dev/null @@ -1,102 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - Buffer = require('buffer').Buffer, - gleak = require('../../dev/tools/gleak'), - fs = require('fs'), - ConnectionPool = require('../../lib/mongodb/connection/connection_pool').ConnectionPool; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports['Should Correctly create a pool instance with the expected values'] = function(test) { - var connectionPool = new ConnectionPool('localhost', 2000, 1, null, {timeout:100, noDelay:true}); - test.equal(100, connectionPool.socketOptions.timeout); - test.equal(true, connectionPool.socketOptions.noDelay); - test.equal(null, connectionPool.socketOptions.encoding); - test.equal(0, connectionPool.socketOptions.bufferSize); - test.done(); -} - -exports['Should correctly fail due to no server'] = function(test) { - var connectionPool = new ConnectionPool('localhost', 2000, 4, null, {timeout:100, noDelay:true}); - - // // Add event handler that will fire once the pool is ready - connectionPool.on("poolReady", function(err, result) { - }) - - // Add event handler that will fire when it fails - connectionPool.on("error", function(err, connection) { - test.equal(0, connectionPool.connections.length) - test.equal(0, connectionPool.openConnections.length) - test.done(); - }); - - // Start the pool - connectionPool.start(); -} - -exports['Should Correctly create a pool of connections and receive an ok when all connections are active'] = function(test) { - var connectionPool = new ConnectionPool('localhost', 27017, 4, {timeout:100, noDelay:true}); - - // Add event handler that will fire once the pool is ready - connectionPool.on("poolReady", function() { - connectionPool.stop(); - test.done(); - }) - - // Start the pool - connectionPool.start(); -} - -exports['Should Correctly connect and then force a restart creating new connections'] = function(test) { - var connectionPool = new ConnectionPool('localhost', 27017, 4, {timeout:100, noDelay:true}); - var done = false; - - // Add event handler that will fire once the pool is ready - connectionPool.on("poolReady", function() { - // Restart - if(done) { - connectionPool.stop(); - test.done(); - } else { - // Trigger stop - connectionPool.restart(); - done = true; - } - }) - - // Start the pool - connectionPool.start(); -}, - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/connection/message_parser_test.js b/node_modules/reg/node_modules/mongodb/test/connection/message_parser_test.js deleted file mode 100644 index 06702d3..0000000 --- a/node_modules/reg/node_modules/mongodb/test/connection/message_parser_test.js +++ /dev/null @@ -1,436 +0,0 @@ -// var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - Buffer = require('buffer').Buffer, - gleak = require('../../dev/tools/gleak'), - Connection = require('../../lib/mongodb/connection/connection').Connection; - -var assertBuffersEqual = function(test, buffer1, buffer2) { - if(buffer1.length != buffer2.length) test.fail("Buffers do not have the same length", buffer1, buffer2); - - for(var i = 0; i < buffer1.length; i++) { - test.equal(buffer1[i], buffer2[i]); - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - callback(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - callback(); -} - -exports['Should correctly parse perfectly aligned message from socket'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(10); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer, data); - test.done(); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer); -}, - -exports['Should correctly parse perfectly aligned double message from socket'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(20); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - buffer[index+4] = 0xa; - - // var result index - var resultIndex = 0; - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(resultIndex, resultIndex + 10), data); - resultIndex = resultIndex + 10; - - if(resultIndex === buffer.length) { - test.done(); - } - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - // Execute parsing of message - dataHandler(buffer); -} - -exports['Should correctly parse message + in two packets from socket'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(10); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer, data); - test.done(); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6)); -}, - -exports['Should correctly parse message + in two packets from socket and partial third one'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(20); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - buffer[index + 4] = 0xff; - buffer[index + 5] = 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(0, 10), data); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 15)); - - // Check status of the parser - test.equal(5, self.bytesRead); - test.equal(10, self.sizeOfMessage); - assertBuffersEqual(test, buffer.slice(10, 15), self.buffer.slice(0, 5)); - test.equal(null, self.stubBuffer); - // Finish test - test.done(); -} - -exports['Should correctly parse message + in two packets from socket and smaller than 4 bytes additional one'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(20); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(0, 10), data); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 13)); - - // Check status of the parser - test.equal(0, self.bytesRead); - test.equal(0, self.sizeOfMessage); - test.equal(null, self.buffer); - assertBuffersEqual(test, buffer.slice(10, 13), self.stubBuffer); - test.done(); -} - -exports['Should correctly parse message + in two packets from socket and smaller than 4 bytes additional one then rest of the message'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(20); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - buffer[index + 4] = 0xff; - buffer[index + 5] = 0xff; - buffer[index + 6] = 0xff; - buffer[index + 7] = 0xff; - buffer[index + 8] = 0xfd; - buffer[index + 9] = 0xfe; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(0, 10), data); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 13)); - dataHandler(buffer.slice(13, 19)); - - // Check status of the parser - test.equal(9, self.bytesRead); - test.equal(10, self.sizeOfMessage); - test.equal(null, self.stubBuffer); - assertBuffersEqual(test, buffer.slice(10, 19), self.buffer.slice(0, 9)); - // Test done - test.done(); -} - -exports['Should correctly parse message + in two packets from socket and smaller than 4 bytes additional one then partial message'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(20); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - // Add data to check - buffer[index + 4] = 0xff; - buffer[index + 5] = 0xff; - buffer[index + 6] = 0xff; - buffer[index + 7] = 0xff; - buffer[index + 8] = 0xfd; - buffer[index + 9] = 0xfe; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(0, 10), data); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 13)); - dataHandler(buffer.slice(13, 15)); - - // Check status of the parser - test.equal(5, self.bytesRead); - test.equal(10, self.sizeOfMessage); - test.equal(null, self.stubBuffer); - assertBuffersEqual(test, buffer.slice(10, 15), self.buffer.slice(0, 5)); - // Test done - test.done(); -} - -exports['Should correctly parse message + in two packets from socket and smaller than 4 bytes additional one then partial message'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(40); - var value = 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - var value = 20; - // Adjust the index - index = index + 10; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - var value = 15; - // Adjust the index - index = index + 20; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - assertBuffersEqual(test, buffer.slice(0, 10), data); - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 15)); - dataHandler(buffer.slice(15, 27)); - - // Check status of the parser - test.equal(17, self.bytesRead); - test.equal(20, self.sizeOfMessage); - test.equal(null, self.stubBuffer); - assertBuffersEqual(test, buffer.slice(10, 27), self.buffer.slice(0, 17)); - // Test done - test.done(); -} - -exports['Corrupt the message baby'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(40); - var value = -40; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - test.equal('parseError', message) - // test.equal('socketHandler', data.err) - }}; - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 15)); - dataHandler(buffer.slice(15, 27)); - test.done(); -} - -exports['Corrupt the message baby but catch the log error'] = function(test) { - // Data object - var index = 0; - var buffer = new Buffer(40); - for(var i = 0; i < buffer.length; i++) buffer[i] = 0; - var value = -40; - // Encode length at start according to wire protocol - buffer[index + 3] = (value >> 24) & 0xff; - buffer[index + 2] = (value >> 16) & 0xff; - buffer[index + 1] = (value >> 8) & 0xff; - buffer[index] = value & 0xff; - - // Dummy object for receiving message - var self = {maxBsonSize: (4 * 1024 * 1024 * 4 * 3), emit:function(message, data) { - test.equal('parseError', message) - }}; - - // Count the number of errors - var totalCountOfErrors = 0; - - // Add a logger object - self.logger = { - doDebug:true, - doError:true, - doLog:true, - - error:function(message, object) { - totalCountOfErrors = totalCountOfErrors + 1; - if(totalCountOfErrors == 3) { - test.done(); - } - }, - - log:function(message, object) { - }, - - debug:function(message, object) { - } - } - - // Create a connection object - var dataHandler = Connection.createDataHandler(self); - - // Execute parsing of message - dataHandler(buffer.slice(0, 6)); - dataHandler(buffer.slice(6, 15)); - dataHandler(buffer.slice(15, 27)); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/connection_test.js b/node_modules/reg/node_modules/mongodb/test/connection_test.js deleted file mode 100644 index f9148d6..0000000 --- a/node_modules/reg/node_modules/mongodb/test/connection_test.js +++ /dev/null @@ -1,171 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - connect = mongodb.connect, - Script = require('vm'), - Collection = mongodb.Collection, - Server = mongodb.Server, - ServerManager = require('../test/tools/server_manager').ServerManager, - Step = require("../deps/step/lib/step"), - mongodb = require('../lib/mongodb'); - -// Test db -var MONGODB = 'integration_tests'; -var client = null; - -function connectionTester(test, testName, callback) { - return function(err, db) { - test.equal(err, null); - db.collection(testName, function(err, collection) { - test.equal(err, null); - var doc = {foo:123}; - collection.insert({foo:123}, {safe:true}, function(err, docs) { - test.equal(err, null); - db.dropDatabase(function(err, done) { - test.equal(err, null); - test.ok(done); - callback(); - }); - }); - }); - }; -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldThrowErrorDueToSharedConnectionUsage = function(test) { - var server = new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}); - - try { - var db = new Db(MONGODB, server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - var db1 = new Db(MONGODB, server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - } catch(err) { - test.done(); - } -} - -exports.testCloseNoCallback = function(test) { - var db = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(connectionTester(test, 'testCloseNoCallback', function() { - var dbCloseCount = 0, connectionCloseCount = 0, poolCloseCount = 0; - // Ensure no close events are fired as we are closing the connection specifically - db.on('close', function() { dbCloseCount++; }); - - var connectionPool = db.serverConfig.connectionPool; - var connections = connectionPool.getAllConnections(); - - // Force the connection close, should not trigger close command - db.serverConfig.connectionPool.stop(); - // Test done - test.equal(0, dbCloseCount); - test.done(); - })); -} - -exports.testCloseWithCallback = function(test) { - var db = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}),{native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(connectionTester(test, 'testCloseWithCallback', function() { - var dbCloseCount = 0, connectionCloseCount = 0, poolCloseCount = 0; - // Ensure no close events are fired as we are closing the connection specifically - db.on('close', function() { dbCloseCount++; }); - - var connectionPool = db.serverConfig.connectionPool; - var connections = connectionPool.getAllConnections(); - - // Ensure no close events are fired as we are closing the connection specifically - for(var i = 0; i < connections.length; i++) { - connections[i].on("close", function() { test.ok(false); }); - } - - db.close(function() { - // Test done - test.equal(0, dbCloseCount); - test.done(); - }); - })); -} - -exports.testShouldCorrectlyCloseOnUnopedConnection = function(test) { - var db = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}),{native_parser: (process.env['TEST_NATIVE'] != null)}); - db.close(); - test.done(); -} - -exports.testConnectUsingDefaultHostAndPort = function(test) { - var db = new Db(MONGODB, new Server("127.0.0.1", mongodb.Connection.DEFAULT_PORT, {auto_reconnect: true, poolSize: 4, ssl:useSSL}),{native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, db) { - test.equal(null, err); - test.done(); - db.close(); - }) -} - -exports.testConnectUsingSocketOptions = function(test) { - var db = new Db(MONGODB, new Server("127.0.0.1", mongodb.Connection.DEFAULT_PORT, {auto_reconnect: true, poolSize: 4, socketOptions:{keepAlive:100}, ssl:useSSL}),{native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, db) { - test.equal(null, err); - test.equal(100, db.serverConfig.checkoutWriter().socketOptions.keepAlive) - test.done(); - db.close(); - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/cursor_test.js b/node_modules/reg/node_modules/mongodb/test/cursor_test.js deleted file mode 100644 index 4ac4fc7..0000000 --- a/node_modules/reg/node_modules/mongodb/test/cursor_test.js +++ /dev/null @@ -1,1965 +0,0 @@ -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = require('../lib/mongodb').Db, - Cursor = require('../lib/mongodb').Cursor, - Step = require("../deps/step/lib/step"), - Collection = require('../lib/mongodb').Collection, - fs = require('fs'), - Server = require('../lib/mongodb').Server; - -var MONGODB = 'integration_tests'; -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * An example showing the information returned by indexInformation - * - * @_class cursor - * @_function toArray - */ -exports.shouldCorrectlyExecuteToArray = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection to hold our documents - db.createCollection('test_array', function(err, collection) { - - // Insert a test document - collection.insert({'b':[1, 2, 3]}, {safe:true}, function(err, ids) { - - // Retrieve all the documents in the collection - collection.find().toArray(function(err, documents) { - test.equal(1, documents.length); - test.deepEqual([1, 2, 3], documents[0].b); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteToArrayAndFailOnFurtherCursorAccess = function(test) { - client.createCollection('test_to_a', function(err, collection) { - test.ok(collection instanceof Collection); - collection.insert({'a':1}, {safe:true}, function(err, ids) { - collection.find({}, function(err, cursor) { - cursor.toArray(function(err, items) { - // Should fail if called again (cursor should be closed) - cursor.toArray(function(err, items) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - - // Should fail if called again (cursor should be closed) - cursor.each(function(err, item) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example iterating over a query using the each function of the cursor. - * - * @_class cursor - * @_function each - * @ignore - */ -exports.shouldCorrectlyFailToArrayDueToFinishedEachOperation = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('test_to_a_after_each', function(err, collection) { - test.equal(null, err); - test.ok(collection instanceof Collection); - - // Insert a document in the collection - collection.insert({'a':1}, {safe:true}, function(err, ids) { - - // Grab a cursor - collection.find(function(err, cursor) { - - // Execute the each command, triggers for each document - cursor.each(function(err, item) { - - // If the item is null then the cursor is exhausted/empty and closed - if(item == null) { - - // Show that the cursor is closed - cursor.toArray(function(err, items) { - test.ok(err != null); - - // Let's close the db - test.done(); - db.close(); - }); - }; - }); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteCursorExplain = function(test) { - client.createCollection('test_explain', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, r) { - collection.find({'a':1}, function(err, cursor) { - cursor.explain(function(err, explaination) { - test.ok(explaination.cursor != null); - test.ok(explaination.n.constructor == Number); - test.ok(explaination.millis.constructor == Number); - test.ok(explaination.nscanned.constructor == Number); - - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteCursorCount = function(test) { - client.createCollection('test_count', function(err, collection) { - collection.find(function(err, cursor) { - cursor.count(function(err, count) { - test.equal(0, count); - - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 10; i++) { - collection.insert({'x':i}, {safe:true}, group()); - } - }, - - function finished() { - collection.find().count(function(err, count) { - test.equal(10, count); - test.ok(count.constructor == Number); - }); - - collection.find({}, {'limit':5}).count(function(err, count) { - test.equal(10, count); - }); - - collection.find({}, {'skip':5}).count(function(err, count) { - test.equal(10, count); - }); - - collection.find(function(err, cursor) { - cursor.count(function(err, count) { - test.equal(10, count); - - cursor.each(function(err, item) { - if(item == null) { - cursor.count(function(err, count2) { - test.equal(10, count2); - test.equal(count, count2); - // Let's close the db - test.done(); - }); - } - }); - }); - }); - - client.collection('acollectionthatdoesn', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - }); - }) - } - ) - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteSortOnCursor = function(test) { - client.createCollection('test_sort', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 5; i++) { - collection.insert({'a':i}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - cursor.sort(['a', 1], function(err, cursor) { - test.ok(cursor instanceof Cursor); - test.deepEqual(['a', 1], cursor.sortValue); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', 1, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.equal(0, doc.a); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', -1, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.equal(4, doc.a); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', "asc", function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.equal(0, doc.a); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort([['a', -1], ['b', 1]], function(err, cursor) { - test.ok(cursor instanceof Cursor); - test.deepEqual([['a', -1], ['b', 1]], cursor.sortValue); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', 1, function(err, cursor) { - cursor.sort('a', -1, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.equal(4, doc.a); - }); - }) - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', -1, function(err, cursor) { - cursor.sort('a', 1, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.equal(0, doc.a); - }); - }) - }); - }); - - collection.find(function(err, cursor) { - cursor.nextObject(function(err, doc) { - cursor.sort(['a'], function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort('a', 25, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.ok(err instanceof Error); - test.equal("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]", err.message); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.sort(25, function(err, cursor) { - cursor.nextObject(function(err, doc) { - test.ok(err instanceof Error); - test.equal("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]", err.message); - // Let's close the db - test.done(); - }); - }); - }); - } - ); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyThrowErrorOnToArrayWhenMissingCallback = function(test) { - client.createCollection('test_to_array', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 2; i++) { - collection.save({'x':1}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - test.throws(function () { - cursor.toArray(); - }); - test.done(); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldThrowErrorOnEachWhenMissingCallback = function(test) { - client.createCollection('test_each', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 2; i++) { - collection.save({'x':1}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - test.throws(function () { - cursor.each(); - }); - test.done(); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyHandleLimitOnCursor = function(test) { - client.createCollection('test_cursor_limit', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 10; i++) { - collection.save({'x':1}, {safe:true}, group()); - } - }, - - function finished() { - collection.find().count(function(err, count) { - test.equal(10, count); - }); - - collection.find(function(err, cursor) { - cursor.limit(5, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(5, items.length); - // Let's close the db - test.done(); - }); - }); - }); - } - ); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyReturnErrorsOnIllegalLimitValues = function(test) { - client.createCollection('test_limit_exceptions', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, docs) {}); - collection.find(function(err, cursor) { - cursor.limit('not-an-integer', function(err, cursor) { - test.ok(err instanceof Error); - test.equal("limit requires an integer", err.message); - }); - }); - - collection.find(function(err, cursor) { - cursor.nextObject(function(err, doc) { - cursor.limit(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.close(function(err, cursor) { - cursor.limit(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlySkipRecordsOnCursor = function(test) { - client.createCollection('test_skip', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 10; i++) { - collection.insert({'x':i}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - cursor.count(function(err, count) { - test.equal(10, count); - }); - }); - - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(10, items.length); - - collection.find(function(err, cursor) { - cursor.skip(2, function(err, cursor) { - cursor.toArray(function(err, items2) { - test.equal(8, items2.length); - - // Check that we have the same elements - var numberEqual = 0; - var sliced = items.slice(2, 10); - - for(var i = 0; i < sliced.length; i++) { - if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1; - } - test.equal(8, numberEqual); - - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyReturnErrorsOnIllegalSkipValues = function(test) { - client.createCollection('test_skip_exceptions', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, docs) {}); - collection.find(function(err, cursor) { - cursor.skip('not-an-integer', function(err, cursor) { - test.ok(err instanceof Error); - test.equal("skip requires an integer", err.message); - }); - }); - - collection.find(function(err, cursor) { - cursor.nextObject(function(err, doc) { - cursor.skip(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.close(function(err, cursor) { - cursor.skip(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldReturnErrorsOnIllegalBatchSizes = function(test) { - client.createCollection('test_batchSize_exceptions', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, docs) {}); - collection.find(function(err, cursor) { - cursor.batchSize('not-an-integer', function(err, cursor) { - test.ok(err instanceof Error); - test.equal("batchSize requires an integer", err.message); - }); - }); - - collection.find(function(err, cursor) { - cursor.nextObject(function(err, doc) { - cursor.nextObject(function(err, doc) { - cursor.batchSize(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - }); - }); - }); - }); - - collection.find(function(err, cursor) { - cursor.close(function(err, cursor) { - cursor.batchSize(1, function(err, cursor) { - test.ok(err instanceof Error); - test.equal("Cursor is closed", err.message); - - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyHandleChangesInBatchSizes = function(test) { - client.createCollection('test_not_multiple_batch_size', function(err, collection) { - var records = 6; - var batchSize = 2; - var docs = []; - for(var i = 0; i < records; i++) { - docs.push({'a':i}); - } - - collection.insert(docs, {safe:true}, function() { - collection.find({}, {batchSize : batchSize}, function(err, cursor) { - //1st - cursor.nextObject(function(err, items) { - //cursor.items should contain 1 since nextObject already popped one - test.equal(1, cursor.items.length); - test.ok(items != null); - - //2nd - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - test.ok(items != null); - - //test batch size modification on the fly - batchSize = 3; - cursor.batchSize(batchSize); - - //3rd - cursor.nextObject(function(err, items) { - test.equal(2, cursor.items.length); - test.ok(items != null); - - //4th - cursor.nextObject(function(err, items) { - test.equal(1, cursor.items.length); - test.ok(items != null); - - //5th - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - test.ok(items != null); - - //6th - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - test.ok(items != null); - - //No more - cursor.nextObject(function(err, items) { - test.ok(items == null); - test.ok(cursor.isClosed()); - - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyHandleBatchSize = function(test) { - client.createCollection('test_multiple_batch_size', function(err, collection) { - //test with the last batch that is a multiple of batchSize - var records = 4; - var batchSize = 2; - var docs = []; - for(var i = 0; i < records; i++) { - docs.push({'a':i}); - } - - collection.insert(docs, {safe:true}, function() { - collection.find({}, {batchSize : batchSize}, function(err, cursor) { - //1st - cursor.nextObject(function(err, items) { - test.equal(1, cursor.items.length); - test.ok(items != null); - - //2nd - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - test.ok(items != null); - - //3rd - cursor.nextObject(function(err, items) { - test.equal(1, cursor.items.length); - test.ok(items != null); - - //4th - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - test.ok(items != null); - - //No more - cursor.nextObject(function(err, items) { - test.ok(items == null); - test.ok(cursor.isClosed()); - - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldHandleWhenLimitBiggerThanBatchSize = function(test) { - client.createCollection('test_limit_greater_than_batch_size', function(err, collection) { - var limit = 4; - var records = 10; - var batchSize = 3; - var docs = []; - for(var i = 0; i < records; i++) { - docs.push({'a':i}); - } - - collection.insert(docs, {safe:true}, function() { - collection.find({}, {batchSize : batchSize, limit : limit}, function(err, cursor) { - //1st - cursor.nextObject(function(err, items) { - test.equal(2, cursor.items.length); - - //2nd - cursor.nextObject(function(err, items) { - test.equal(1, cursor.items.length); - - //3rd - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - - //4th - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - - //No more - cursor.nextObject(function(err, items) { - test.ok(items == null); - test.ok(cursor.isClosed()); - - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldHandleLimitLessThanBatchSize = function(test) { - client.createCollection('test_limit_less_than_batch_size', function(err, collection) { - var limit = 2; - var records = 10; - var batchSize = 4; - var docs = []; - for(var i = 0; i < records; i++) { - docs.push({'a':i}); - } - - collection.insert(docs, {safe:true}, function() { - collection.find({}, {batchSize : batchSize, limit : limit}, function(err, cursor) { - //1st - cursor.nextObject(function(err, items) { - test.equal(1, cursor.items.length); - - //2nd - cursor.nextObject(function(err, items) { - test.equal(0, cursor.items.length); - - //No more - cursor.nextObject(function(err, items) { - test.ok(items == null); - test.ok(cursor.isClosed()); - - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldHandleSkipLimitChaining = function(test) { - client.createCollection('test_limit_skip_chaining', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 10; i++) { - collection.insert({'x':1}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(10, items.length); - - collection.find(function(err, cursor) { - cursor.limit(5, function(err, cursor) { - cursor.skip(3, function(err, cursor) { - cursor.toArray(function(err, items2) { - test.equal(5, items2.length); - - // Check that we have the same elements - var numberEqual = 0; - var sliced = items.slice(3, 8); - - for(var i = 0; i < sliced.length; i++) { - if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1; - } - test.equal(5, numberEqual); - - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyHandleLimitSkipChainingInline = function(test) { - client.createCollection('test_limit_skip_chaining_inline', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 10; i++) { - collection.insert({'x':1}, {safe:true}, group()); - } - }, - - function finished() { - collection.find(function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(10, items.length); - - collection.find(function(err, cursor) { - cursor.limit(5).skip(3).toArray(function(err, items2) { - test.equal(5, items2.length); - - // Check that we have the same elements - var numberEqual = 0; - var sliced = items.slice(3, 8); - - for(var i = 0; i < sliced.length; i++) { - if(sliced[i].x == items2[i].x) numberEqual = numberEqual + 1; - } - test.equal(5, numberEqual); - - // Let's close the db - test.done(); - }); - }); - }); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCloseCursorNoQuerySent = function(test) { - client.createCollection('test_close_no_query_sent', function(err, collection) { - collection.find(function(err, cursor) { - cursor.close(function(err, cursor) { - test.equal(true, cursor.isClosed()); - // Let's close the db - test.done(); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyRefillViaGetMoreCommand = function(test) { - var COUNT = 1000; - - client.createCollection('test_refill_via_get_more', function(err, collection) { - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < COUNT; i++) { - collection.save({'a': i}, {safe:true}, group()); - } - }, - - function finished() { - collection.count(function(err, count) { - test.equal(COUNT, count); - }); - - var total = 0; - var i = 0; - collection.find({}, {}, function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - total = total + item.a; - } else { - test.equal(499500, total); - - collection.count(function(err, count) { - test.equal(COUNT, count); - }); - - collection.count(function(err, count) { - test.equal(COUNT, count); - - var total2 = 0; - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - total2 = total2 + item.a; - } else { - test.equal(499500, total2); - collection.count(function(err, count) { - test.equal(COUNT, count); - test.equal(total, total2); - // Let's close the db - test.done(); - }); - } - }); - }); - }); - } - }); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyRefillViaGetMoreAlternativeCollection = function(test) { - client.createCollection('test_refill_via_get_more_alt_coll', function(err, collection) { - - Step( - function insert() { - var group = this.group(); - - for(var i = 0; i < 1000; i++) { - collection.save({'a': i}, {safe:true}, group()); - } - }, - - function finished() { - collection.count(function(err, count) { - test.equal(1000, count); - }); - - var total = 0; - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - total = total + item.a; - } else { - test.equal(499500, total); - - collection.count(function(err, count) { - test.equal(1000, count); - }); - - collection.count(function(err, count) { - test.equal(1000, count); - - var total2 = 0; - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - total2 = total2 + item.a; - } else { - test.equal(499500, total2); - collection.count(function(err, count) { - test.equal(1000, count); - test.equal(total, total2); - // Let's close the db - test.done(); - }); - } - }); - }); - }); - } - }); - }); - } - ) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCloseCursorAfterQueryHasBeenSent = function(test) { - client.createCollection('test_close_after_query_sent', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, r) { - collection.find({'a':1}, function(err, cursor) { - cursor.nextObject(function(err, item) { - cursor.close(function(err, cursor) { - test.equal(true, cursor.isClosed()); - // Let's close the db - test.done(); - }) - }); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteCursorCountWithFields = function(test) { - client.createCollection('test_count_with_fields', function(err, collection) { - collection.save({'x':1, 'a':2}, {safe:true}, function(err, doc) { - collection.find({}, {'fields':['a']}).toArray(function(err, items) { - test.equal(1, items.length); - test.equal(2, items[0].a); - test.equal(null, items[0].x); - }); - - collection.findOne({}, {'fields':['a']}, function(err, item) { - test.equal(2, item.a); - test.equal(null, item.x); - test.done(); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyCountWithFieldsUsingExclude = function(test) { - client.createCollection('test_count_with_fields_using_exclude', function(err, collection) { - collection.save({'x':1, 'a':2}, {safe:true}, function(err, doc) { - collection.find({}, {'fields':{'x':0}}).toArray(function(err, items) { - test.equal(1, items.length); - test.equal(2, items[0].a); - test.equal(null, items[0].x); - test.done(); - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyExecuteEnsureIndexWithNoCallback = function(test) { - var docs = []; - - for(var i = 0; i < 1; i++) { - var d = new Date().getTime() + i*1000; - docs[i] = {createdAt:new Date(d)}; - } - - // Create collection - client.createCollection('shouldCorrectlyExecuteEnsureIndexWithNoCallback', function(err, collection) { - // ensure index of createdAt index - collection.ensureIndex({createdAt:1}) - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - // Find with sort - collection.find().sort(['createdAt', 'asc']).toArray(function(err, items) { - if (err) logger.error("error in collection_info.find: " + err); - test.equal(1, items.length); - test.done(); - }) - }) - }); -} - -/** - * @ignore - * @api private - */ -exports.shouldCorrectlyInsert5000RecordsWithDateAndSortCorrectlyWithIndex = function(test) { - var docs = []; - - for(var i = 0; i < 5000; i++) { - var d = new Date().getTime() + i*1000; - docs[i] = {createdAt:new Date(d)}; - } - - // Create collection - client.createCollection('shouldCorrectlyInsert5000RecordsWithDateAndSortCorrectlyWithIndex', function(err, collection) { - // ensure index of createdAt index - collection.ensureIndex({createdAt:1}, function(err, indexName) { - test.equal(null, err); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - // Find with sort - collection.find().sort(['createdAt', 'asc']).toArray(function(err, items) { - if (err) logger.error("error in collection_info.find: " + err); - test.equal(5000, items.length); - test.done(); - }) - }) - }); - }); -} - -/** - * An example showing the information returned by indexInformation - * - * @_class cursor - * @_function rewind - */ -exports['Should correctly rewind and restart cursor'] = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - var docs = []; - - // Insert 100 documents with some data - for(var i = 0; i < 100; i++) { - var d = new Date().getTime() + i*1000; - docs[i] = {'a':i, createdAt:new Date(d)}; - } - - // Create collection - db.createCollection('Should_correctly_rewind_and_restart_cursor', function(err, collection) { - test.equal(null, err); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - // Grab a cursor using the find - var cursor = collection.find({}); - // Fetch the first object off the cursor - cursor.nextObject(function(err, item) { - test.equal(0, item.a) - // Rewind the cursor, resetting it to point to the start of the query - cursor.rewind(); - - // Grab the first object again - cursor.nextObject(function(err, item) { - test.equal(0, item.a) - - db.close(); - test.done(); - }) - }) - }) - }); - }); -} - -/** - * @ignore - * @api private - */ -exports['Should correctly execute count on cursor'] = function(test) { - var docs = []; - - for(var i = 0; i < 1000; i++) { - var d = new Date().getTime() + i*1000; - docs[i] = {'a':i, createdAt:new Date(d)}; - } - - // Create collection - client.createCollection('Should_correctly_execute_count_on_cursor', function(err, collection) { - test.equal(null, err); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - var total = 0; - // Create a cursor for the content - var cursor = collection.find({}); - cursor.count(function(err, c) { - // Ensure each returns all documents - cursor.each(function(err, item) { - if(item != null) { - total++; - } else { - cursor.count(function(err, c) { - test.equal(1000, c); - test.equal(1000, total); - test.done(); - }) - } - }); - }) - }) - }); -} - -/** - * @ignore - * @api private - */ -exports['should be able to stream documents'] = function(test) { - var docs = []; - - for (var i = 0; i < 1000; i++) { - docs[i] = { a: i+1 }; - } - - // Create collection - client.createCollection('Should_be_able_to_stream_documents', function(err, collection) { - test.equal(null, err); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - var paused = 0 - , closed = 0 - , resumed = 0 - , i = 0 - , err - - var stream = collection.find().stream(); - - stream.on('data', function (doc) { - test.equal(true, !! doc); - test.equal(true, !! doc.a); - - if (paused > 0 && 0 === resumed) { - err = new Error('data emitted during pause'); - return done(); - } - - if (++i === 3) { - test.equal(false, stream.paused); - stream.pause(); - test.equal(true, stream.paused); - paused++; - - setTimeout(function () { - test.equal(true, stream.paused); - stream.resume(); - test.equal(false, stream.paused); - resumed++; - }, 20); - } - }); - - stream.on('error', function (er) { - err = er; - done(); - }); - - stream.on('close', function () { - closed++; - done(); - }); - - function done () { - test.equal(undefined, err); - test.equal(i, docs.length); - test.equal(1, closed); - test.equal(1, paused); - test.equal(1, resumed); - test.strictEqual(stream._cursor.isClosed(), true); - test.done(); - } - }) - }) -} - -/** - * @ignore - * @api private - */ -exports['immediately destroying a stream prevents the query from executing'] = function(test) { - var i = 0 - , docs = [{ b: 2 }, { b: 3 }] - , doneCalled = 0 - - client.createCollection('immediately_destroying_a_stream_prevents_the_query_from_executing', function(err, collection) { - test.equal(null, err); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - var stream = collection.find().stream(); - - stream.on('data', function () { - i++; - }) - stream.on('close', done); - stream.on('error', done); - - stream.destroy(); - - function done (err) { - test.equal(++doneCalled, 1); - test.equal(undefined, err); - test.strictEqual(0, i); - test.strictEqual(true, stream._destroyed); - test.done(); - } - }); - }); -} - -/** - * @ignore - * @api private - */ -exports['destroying a stream stops it'] = function(test) { - client.createCollection('destroying_a_stream_stops_it', function(err, collection) { - test.equal(null, err); - - var docs = []; - for (var ii = 0; ii < 10; ++ii) docs.push({ b: ii+1 }); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - var finished = 0 - , i = 0 - - var stream = collection.find().stream(); - - test.strictEqual(null, stream._destroyed); - test.strictEqual(true, stream.readable); - - stream.on('data', function (doc) { - if (++i === 5) { - stream.destroy(); - test.strictEqual(false, stream.readable); - } - }); - - stream.on('close', done); - stream.on('error', done); - - function done (err) { - ++finished; - setTimeout(function () { - test.strictEqual(undefined, err); - test.strictEqual(5, i); - test.strictEqual(1, finished); - test.strictEqual(true, stream._destroyed); - test.strictEqual(false, stream.readable); - test.strictEqual(true, stream._cursor.isClosed()); - test.done(); - }, 150) - } - }); - }); -} - -/** - * @ignore - * @api private - */ -exports['cursor stream errors']= function(test) { - var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - test.equal(null, err); - - client.createCollection('cursor_stream_errors', function(err, collection) { - test.equal(null, err); - - var docs = []; - for (var ii = 0; ii < 10; ++ii) docs.push({ b: ii+1 }); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - var finished = 0 - , closed = 0 - , i = 0 - - var stream = collection.find({}, { batchSize: 5 }).stream(); - - stream.on('data', function (doc) { - if (++i === 5) { - client.close(); - } - }); - - stream.on('close', function () { - closed++; - }); - - stream.on('error', done); - - function done (err) { - ++finished; - setTimeout(function () { - test.equal('no open connections', err.message); - test.equal(5, i); - test.equal(1, closed); - test.equal(1, finished); - test.equal(true, stream._destroyed); - test.equal(false, stream.readable); - test.equal(true, stream._cursor.isClosed()); - test.done(); - }, 150) - } - }); - }); - }); -} - -/** - * @ignore - * @api private - */ -exports['cursor stream pipe']= function(test) { - client.createCollection('cursor_stream_pipe', function(err, collection) { - test.equal(null, err); - - var docs = []; - ;('Aaden Aaron Adrian Aditya Bob Joe').split(' ').forEach(function (name) { - docs.push({ name: name }); - }); - - // insert all docs - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - var filename = '/tmp/_nodemongodbnative_stream_out.txt' - , out = fs.createWriteStream(filename) - - // hack so we don't need to create a stream filter just to - // stringify the objects (otherwise the created file would - // just contain a bunch of [object Object]) - var toString = Object.prototype.toString; - Object.prototype.toString = function () { - return JSON.stringify(this); - } - - var stream = collection.find().stream(); - stream.pipe(out); - - stream.on('error', done); - stream.on('close', done); - - function done (err) { - Object.prototype.toString = toString; - test.strictEqual(undefined, err); - var contents = fs.readFileSync(filename, 'utf8'); - test.ok(/Aaden/.test(contents)); - test.ok(/Aaron/.test(contents)); - test.ok(/Adrian/.test(contents)); - test.ok(/Aditya/.test(contents)); - test.ok(/Bob/.test(contents)); - test.ok(/Joe/.test(contents)); - fs.unlink(filename); - test.done(); - } - }); - }); -} - -/** - * A simple example showing the count function of the cursor. - * - * @_class cursor - * @_function count - * @ignore - */ -exports.shouldCorrectlyUseCursorCountFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Creat collection - db.createCollection('cursor_count_collection', function(err, collection) { - test.equal(null, err); - - // Insert some docs - collection.insert([{a:1}, {a:2}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Do a find and get the cursor count - collection.find().count(function(err, count) { - test.equal(null, err); - test.equal(2, count); - - db.close(); - test.done(); - }) - }); - }); - }); -} - -/** - * A simple example showing the use of sort on the cursor. - * - * @_class cursor - * @_function sort - * @ignore - */ -exports.shouldCorrectlyPeformSimpleSorts = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_sort_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Do normal ascending sort - collection.find().sort([['a', 1]]).nextObject(function(err, item) { - test.equal(null, err); - test.equal(1, item.a); - - // Do normal descending sort - collection.find().sort([['a', -1]]).nextObject(function(err, item) { - test.equal(null, err); - test.equal(3, item.a); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of limit on the cursor - * - * @_class cursor - * @_function limit - * @ignore - */ -exports.shouldCorrectlyPeformLimitOnCursor = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_limit_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Limit to only one document returned - collection.find().limit(1).toArray(function(err, items) { - test.equal(null, err); - test.equal(1, items.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of skip on the cursor - * - * @_class cursor - * @_function skip - * @ignore - */ -exports.shouldCorrectlyPeformSkipOnCursor = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_skip_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Skip one document - collection.find().skip(1).nextObject(function(err, item) { - test.equal(null, err); - test.equal(2, item.a); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of batchSize on the cursor, batchSize only regulates how many - * documents are returned for each batch using the getMoreCommand against the MongoDB server - * - * @_class cursor - * @_function batchSize - * @ignore - */ -exports.shouldCorrectlyPeformBatchSizeOnCursor = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_batch_size_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Do normal ascending sort - collection.find().batchSize(1).nextObject(function(err, item) { - test.equal(null, err); - test.equal(1, item.a); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of nextObject. - * - * @_class cursor - * @_function nextObject - * @ignore - */ -exports.shouldCorrectlyPeformNextObjectOnCursor = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_next_object_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Do normal ascending sort - collection.find().nextObject(function(err, item) { - test.equal(null, err); - test.equal(1, item.a); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursor explain function. - * - * @_class cursor - * @_function explain - * @ignore - */ -exports.shouldCorrectlyPeformSimpleExplainCursor = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('simple_explain_collection', function(err, collection) { - test.equal(null, err); - - // Insert some documents we can sort on - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, docs) { - test.equal(null, err); - - // Do normal ascending sort - collection.find().explain(function(err, explaination) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursor streamRecords function. - * - * @_class cursor - * @_function streamRecords - * @ignore - */ -exports.shouldStreamDocumentsUsingTheStreamRecords = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 100; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_streamingRecords_function', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var stream = collection.find().streamRecords({fetchSize:1000}); - - // Execute find on all the documents - stream.on('end', function() { - db.close(); - test.done(); - }); - - stream.on('data', function(data) { - test.ok(data != null); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursor stream function. - * - * @_class cursor - * @_function stream - * @ignore - */ -exports.shouldStreamDocumentsUsingTheStreamFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 100; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_stream_function', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var stream = collection.find().stream(); - - // Execute find on all the documents - stream.on('close', function() { - db.close(); - test.done(); - }); - - stream.on('data', function(data) { - test.ok(data != null); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursor close function. - * - * @_class cursor - * @_function close - * @ignore - */ -exports.shouldStreamDocumentsUsingTheCloseFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 100; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_close_function_on_cursor', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var cursor = collection.find(); - - // Fetch the first object - cursor.nextObject(function(err, object) { - test.equal(null, err); - - // Close the cursor, this is the same as reseting the query - cursor.close(function(err, result) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursor close function. - * - * @_class cursor - * @_function isClosed - * @ignore - */ -exports.shouldStreamDocumentsUsingTheIsCloseFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 100; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_is_close_function_on_cursor', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var cursor = collection.find(); - - // Fetch the first object - cursor.nextObject(function(err, object) { - test.equal(null, err); - - // Close the cursor, this is the same as reseting the query - cursor.close(function(err, result) { - test.equal(null, err); - test.equal(true, cursor.isClosed()); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/cursorstream_test.js b/node_modules/reg/node_modules/mongodb/test/cursorstream_test.js deleted file mode 100644 index 270324e..0000000 --- a/node_modules/reg/node_modules/mongodb/test/cursorstream_test.js +++ /dev/null @@ -1,231 +0,0 @@ -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = require('../lib/mongodb').Db, - Cursor = require('../lib/mongodb').Cursor, - Step = require("../deps/step/lib/step"), - Collection = require('../lib/mongodb').Collection, - fs = require('fs'), - Server = require('../lib/mongodb').Server; - -var MONGODB = 'integration_tests'; -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple example showing the use of the cursorstream pause function. - * - * @_class cursorstream - * @_function pause - * @ignore - */ -exports.shouldStreamDocumentsUsingTheCursorStreamPauseFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 1; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_cursorstream_pause', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var stream = collection.find().stream(); - - // For each data item - stream.on("data", function(item) { - // Check if cursor is paused - test.equal(false, stream.paused); - // Pause stream - stream.pause(); - // Check if cursor is paused - test.equal(true, stream.paused); - - // Restart the stream after 1 miliscecond - setTimeout(function() { - stream.resume(); - // Check if cursor is paused - test.equal(false, stream.paused); - }, 1); - }); - - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursorstream resume function. - * - * @_class cursorstream - * @_function resume - * @ignore - */ -exports.shouldStreamDocumentsUsingTheCursorStreamResumeFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 1; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_cursorstream_resume', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var stream = collection.find().stream(); - - // For each data item - stream.on("data", function(item) { - // Check if cursor is paused - test.equal(false, stream.paused); - // Pause stream - stream.pause(); - // Check if cursor is paused - test.equal(true, stream.paused); - - // Restart the stream after 1 miliscecond - setTimeout(function() { - - // Resume the stream - stream.resume(); - - // Check if cursor is paused - test.equal(false, stream.paused); - }, 1); - }); - - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the cursorstream resume function. - * - * @_class cursorstream - * @_function destroy - * @ignore - */ -exports.shouldStreamDocumentsUsingTheCursorStreamDestroyFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a lot of documents to insert - var docs = [] - for(var i = 0; i < 1; i++) { - docs.push({'a':i}) - } - - // Create a collection - db.createCollection('test_cursorstream_destroy', function(err, collection) { - test.equal(null, err); - - // Insert documents into collection - collection.insert(docs, {safe:true}, function(err, ids) { - // Peform a find to get a cursor - var stream = collection.find().stream(); - - // For each data item - stream.on("data", function(item) { - // Destroy stream - stream.destroy(); - }); - - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/custom_pk_test.js b/node_modules/reg/node_modules/mongodb/test/custom_pk_test.js deleted file mode 100644 index c1b6c74..0000000 --- a/node_modules/reg/node_modules/mongodb/test/custom_pk_test.js +++ /dev/null @@ -1,107 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCreateRecordsWithCustomPKFactory = function(test) { - // Custom factory (need to provide a 12 byte array); - var CustomPKFactory = function() {} - CustomPKFactory.prototype = new Object(); - CustomPKFactory.createPk = function() { - return new ObjectID("aaaaaaaaaaaa"); - } - - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {ssl:useSSL}), {'pk':CustomPKFactory, native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - p_client.dropDatabase(function(err, done) { - p_client.createCollection('test_custom_key', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, doc) { - collection.find({'_id':new ObjectID("aaaaaaaaaaaa")}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(1, items.length); - - p_client.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -exports.testConnectBadUrl = function(test) { - test.throws(function() { - connect('mango://localhost:27017/' + MONGODB, function(err, db) { - test.ok(false, 'Bad URL!'); - }); - }); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/db_test.js b/node_modules/reg/node_modules/mongodb/test/db_test.js deleted file mode 100644 index 68f3266..0000000 --- a/node_modules/reg/node_modules/mongodb/test/db_test.js +++ /dev/null @@ -1,1441 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - DBRef = require('../lib/mongodb/bson/db_ref').DBRef, - Code = require('../lib/mongodb/bson/code').Code, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleIllegalDbNames = function(test) { - // Assert rename - try { - new Db(5); - } catch(err) { - test.ok(err instanceof Error); - test.equal("database name must be a string", err.message); - } - - try { - new Db(""); - } catch(err) { - test.ok(err instanceof Error); - test.equal("database name cannot be the empty string", err.message); - } - - try { - new Db("te$t", function(err, collection) {}); - } catch(err) { - test.equal("database names cannot contain the character '$'", err.message); - } - - try { - new Db(".test", function(err, collection) {}); - } catch(err) { - test.equal("database names cannot contain the character '.'", err.message); - } - - try { - new Db("\\test", function(err, collection) {}); - } catch(err) { - test.equal("database names cannot contain the character '\\'", err.message); - } - - try { - new Db("\\test", function(err, collection) {}); - } catch(err) { - test.equal("database names cannot contain the character '\\'", err.message); - } - - try { - new Db("test test", function(err, collection) {}); - } catch(err) { - test.equal("database names cannot contain the character ' '", err.message); - } - - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformAutomaticConnect = function(test) { - var automatic_connect_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null), retryMiliSeconds:50}); - automatic_connect_client.open(function(err, automatic_connect_client) { - // Listener for closing event - var closeListener = function(has_error) { - // Let's insert a document - automatic_connect_client.collection('test_object_id_generation.data2', function(err, collection) { - // Insert another test document and collect using ObjectId - collection.insert({"name":"Patty", "age":34}, {safe:true}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]._id.toHexString().length == 24); - - collection.findOne({"name":"Patty"}, function(err, document) { - test.equal(ids[0]._id.toHexString(), document._id.toHexString()); - // Let's close the db - automatic_connect_client.close(); - test.done(); - }); - }); - }); - }; - - // Add listener to close event - automatic_connect_client.on("close", closeListener); - automatic_connect_client.close(); - }); -} - -/** - * An example that shows how to force close a db connection so it cannot be reused. - * - * @_class db - * @_function close - * @ignore - */ -exports.shouldCorrectlyFailOnRetryDueToAppCloseOfDb = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection - db.collection('shouldCorrectlyFailOnRetryDueToAppCloseOfDb', function(err, collection) { - - // Insert a document - collection.insert({a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - // Force close the connection - db.close(true, function(err, result) { - - // Attemp to insert should fail now with correct message 'db closed by application' - collection.insert({a:2}, {safe:true}, function(err, result) { - test.equal('db closed by application', err.message); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A whole bunch of examples on how to use eval on the server. - * - * @_class db - * @_function eval - * @ignore - */ -exports.shouldCorrectlyExecuteEvalFunctions = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Evaluate a function on the server with the parameter 3 passed in - db.eval('function (x) {return x;}', [3], function(err, result) { - test.equal(3, result); - }); - - // Evaluate a function on the server with the parameter 3 passed in no lock aquired for eval - // on server - db.eval('function (x) {return x;}', [3], {nolock:true}, function(err, result) { - test.equal(3, result); - }); - - // Evaluate a function on the server that writes to a server collection - db.eval('function (x) {db.test_eval.save({y:x});}', [5], function(err, result) { - // Locate the entry - client.collection('test_eval', function(err, collection) { - collection.findOne(function(err, item) { - test.equal(5, item.y); - }); - }); - }); - - // Evaluate a function with 2 parameters passed in - db.eval('function (x, y) {return x + y;}', [2, 3], function(err, result) { - test.equal(5, result); - }); - - // Evaluate a function with no parameters passed in - db.eval('function () {return 5;}', function(err, result) { - test.equal(5, result); - }); - - // Evaluate a statement - db.eval('2 + 3;', function(err, result) { - test.equal(5, result); - }); - - // Evaluate a statement using the code object - db.eval(new Code("2 + 3;"), function(err, result) { - test.equal(5, result); - }); - - // Evaluate a statement using the code object including a scope - db.eval(new Code("return i;", {'i':2}), function(err, result) { - test.equal(2, result); - }); - - // Evaluate a statement using the code object including a scope - db.eval(new Code("i + 3;", {'i':2}), function(err, result) { - test.equal(5, result); - test.done(); - }); - - // Evaluate an illegal statement - db.eval("5 ++ 5;", function(err, result) { - test.ok(err instanceof Error); - test.ok(err.message != null); - // Let's close the db - test.done(); - }); - - db.close(); - test.done(); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyDereferenceDbRef = function(test) { - client.createCollection('test_deref', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, ids) { - collection.remove({}, {safe:true}, function(err, result) { - collection.count(function(err, count) { - test.equal(0, count); - - // Execute deref a db reference - client.dereference(new DBRef("test_deref", new ObjectID()), function(err, result) { - collection.insert({'x':'hello'}, {safe:true}, function(err, ids) { - collection.findOne(function(err, document) { - test.equal('hello', document.x); - - client.dereference(new DBRef("test_deref", document._id), function(err, result) { - test.equal('hello', document.x); - - client.dereference(new DBRef("test_deref", 4), function(err, result) { - var obj = {'_id':4}; - - collection.insert(obj, {safe:true}, function(err, ids) { - client.dereference(new DBRef("test_deref", 4), function(err, document) { - - test.equal(obj['_id'], document._id); - collection.remove({}, {safe:true}, function(err, result) { - collection.insert({'x':'hello'}, {safe:true}, function(err, ids) { - client.dereference(new DBRef("test_deref", null), function(err, result) { - test.equal(null, result); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }) - }) - }) - }); -} - -/** - * An example of illegal and legal renaming of a collection - * - * @_class collection - * @_function rename - * @ignore - */ -exports.shouldCorrectlyRenameCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Open a couple of collections - db.createCollection('test_rename_collection', function(err, collection1) { - db.createCollection('test_rename_collection2', function(err, collection2) { - - // Attemp to rename a collection to a number - try { - collection1.rename(5, function(err, collection) {}); - } catch(err) { - test.ok(err instanceof Error); - test.equal("collection name must be a String", err.message); - } - - // Attemp to rename a collection to an empty string - try { - collection1.rename("", function(err, collection) {}); - } catch(err) { - test.ok(err instanceof Error); - test.equal("collection names cannot be empty", err.message); - } - - // Attemp to rename a collection to an illegal name including the character $ - try { - collection1.rename("te$t", function(err, collection) {}); - } catch(err) { - test.ok(err instanceof Error); - test.equal("collection names must not contain '$'", err.message); - } - - // Attemp to rename a collection to an illegal name starting with the character . - try { - collection1.rename(".test", function(err, collection) {}); - } catch(err) { - test.ok(err instanceof Error); - test.equal("collection names must not start or end with '.'", err.message); - } - - // Attemp to rename a collection to an illegal name ending with the character . - try { - collection1.rename("test.", function(err, collection) {}); - } catch(err) { - test.ok(err instanceof Error); - test.equal("collection names must not start or end with '.'", err.message); - } - - // Attemp to rename a collection to an illegal name with an empty middle name - try { - collection1.rename("tes..t", function(err, collection) {}); - } catch(err) { - test.equal("collection names cannot be empty", err.message); - } - - // Insert a couple of documents - collection1.insert([{'x':1}, {'x':2}], {safe:true}, function(err, docs) { - - // Attemp to rename the first collection to the second one, this will fail - collection1.rename('test_rename_collection2', function(err, collection) { - test.ok(err instanceof Error); - test.ok(err.message.length > 0); - - // Attemp to rename the first collection to a name that does not exist - // this will be succesful - collection1.rename('test_rename_collection3', function(err, collection) { - test.equal("test_rename_collection3", collection.collectionName); - - // Ensure that the collection is pointing to the new one - collection1.count(function(err, count) { - test.equal(2, count); - db.close(); - test.done(); - }); - }); - }); - }) - }); - }); - }); -} - -/** - * An example of a simple single server db connection - * - * @_class db - * @_function open - * @ignore - */ -exports.shouldCorrectlyOpenASimpleDbSingleServerConnection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - db.close(); - test.done(); - }); -} - -/** - * An example of a simple single server db connection and close function - * - * @_class db - * @_function close - * @ignore - */ -exports.shouldCorrectlyOpenASimpleDbSingleServerConnection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Close the connection with a callback that is optional - db.close(function(err, result) { - test.equal(null, err); - - test.done(); - }); - }); -} - -/** - * An example of retrieveing the information of all the collections. - * - * @_class db - * @_function collectionsInfo - * @ignore - */ -exports.shouldCorrectlyRetrieveCollectionInfo = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection('test_collections_info', function(err, r) { - test.equal(null, err); - - // Return the information of a single collection name - db.collectionsInfo("test_collections_info").toArray(function(err, items) { - test.equal(1, items.length); - - // Return the information of a all collections, using the callback format - db.collectionsInfo(function(err, cursor) { - - // Turn the cursor into an array of results - cursor.toArray(function(err, items) { - test.ok(items.length > 0); - - db.close(); - test.done(); - }); - }) - }); - }); - }); -} - -/** - * An example of retrieveing the collection names for a database. - * - * @_class db - * @_function collectionNames - * @ignore - */ -exports.shouldCorrectlyRetrieveCollectionInfo = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection('test_collections_info', function(err, r) { - test.equal(null, err); - - // Return the information of a single collection name - db.collectionNames("test_collections_info", function(err, items) { - test.equal(1, items.length); - - // Return the information of a all collections, using the callback format - db.collectionNames(function(err, items) { - test.ok(items.length > 0); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * An example of retrieving a collection from a db using the collection function. - * - * @_class db - * @_function collection - * @ignore - */ -exports.shouldCorrectlyAccessACollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Grab a collection without a callback no safe mode - var col1 = db.collection('test_correctly_access_collections'); - - // Grab a collection with a callback but no safe operation - db.collection('test_correctly_access_collections', function(err, col2) { - test.equal(null, err); - - // Grab a collection with a callback in safe mode, ensuring it exists (should fail as it's not created) - db.collection('test_correctly_access_collections', {safe:true}, function(err, col3) { - test.ok(err != null); - - // Create the collection - db.createCollection('test_correctly_access_collections', function(err, result) { - - // Retry to get the collection, should work as it's now created - db.collection('test_correctly_access_collections', {safe:true}, function(err, col3) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * An example of retrieving all collections for a db as Collection objects - * - * @_class db - * @_function collections - * @ignore - */ -exports.shouldCorrectlyRetrieveAllCollections = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create the collection - db.createCollection('test_correctly_access_collections', function(err, result) { - - // Retry to get the collection, should work as it's now created - db.collections(function(err, collections) { - test.equal(null, err); - test.ok(collections.length > 0); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleFailedConnection = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 25117, {auto_reconnect: false, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - test.ok(err != null) - test.done(); - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyResaveDBRef = function(test) { - client.dropCollection('test_resave_dbref', function() { - client.createCollection('test_resave_dbref', function(err, collection) { - test.ifError(err); - - collection.insert({'name': 'parent'}, {safe : true}, function(err, objs) { - test.ok(objs && objs.length == 1 && objs[0]._id != null); - var parent = objs[0]; - var child = {'name' : 'child', 'parent' : new DBRef("test_resave_dbref", parent._id)}; - - collection.insert(child, {safe : true}, function(err, objs) { - test.ifError(err); - - collection.findOne({'name' : 'child'}, function(err, child) { //Child deserialized - test.ifError(err); - test.ok(child != null); - - collection.save(child, {save : true}, function(err) { - test.ifError(err); //Child node with dbref resaved! - - collection.findOne({'parent' : new DBRef("test_resave_dbref", parent._id)}, - function(err, child) { - test.ifError(err); - test.ok(child != null);//!!!! Main test point! - test.done(); - }) - }); - }); - }); - }); - }); - }); -}, - -/** - * An example of dereferencing values. - * - * @_class db - * @_function dereference - * @ignore - */ -exports.shouldCorrectlyDereferenceDbRefExamples = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Get a second db - var secondDb = db.db('integration_tests_2'); - - // Create a dereference example - secondDb.createCollection('test_deref_examples', function(err, collection) { - - // Insert a document in the collection - collection.insert({'a':1}, {safe:true}, function(err, ids) { - - // Let's build a db reference and resolve it - var dbRef = new DBRef('test_deref_examples', ids[0]._id, 'integration_tests_2'); - - // Resolve it including a db resolve - db.dereference(dbRef, function(err, item) { - test.equal(1, item.a); - - // Let's build a db reference and resolve it - var dbRef = new DBRef('test_deref_examples', ids[0]._id); - - // Simple local resolve - secondDb.dereference(dbRef, function(err, item) { - test.equal(1, item.a); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * An example of using the logout command for the database. - * - * @_class db - * @_function logout - * @ignore - */ -exports.shouldCorrectlyLogoutFromTheDatabase = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Add a user to the database - db.addUser('user', 'name', function(err, result) { - test.equal(null, err); - - // Authenticate - db.authenticate('user', 'name', function(err, result) { - test.equal(true, result); - - // Logout the db - db.logout(function(err, result) { - test.equal(true, result); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * An example of using the authenticate command. - * - * @_class db - * @_function authenticate - * @ignore - */ -exports.shouldCorrectlyAuthenticateAgainstTheDatabase = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Add a user to the database - db.addUser('user', 'name', function(err, result) { - test.equal(null, err); - - // Authenticate - db.authenticate('user', 'name', function(err, result) { - test.equal(true, result); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * An example of adding a user to the database. - * - * @_class db - * @_function addUser - * @ignore - */ -exports.shouldCorrectlyAuthenticateAgainstTheDatabase = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Add a user to the database - db.addUser('user', 'name', function(err, result) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); -} - -/** - * An example of dereferencing values. - * - * @_class db - * @_function removeUser - * @ignore - */ -exports.shouldCorrectlyAddAndRemoveUser = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Add a user to the database - db.addUser('user', 'name', function(err, result) { - test.equal(null, err); - - // Authenticate - db.authenticate('user', 'name', function(err, result) { - test.equal(true, result); - - // Logout the db - db.logout(function(err, result) { - test.equal(true, result); - - // Remove the user from the db - db.removeUser('user', function(err, result) { - - // Authenticate - db.authenticate('user', 'name', function(err, result) { - test.equal(false, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the creation of a collection. - * - * @_class db - * @_function createCollection - * @ignore - */ -exports.shouldCorrectlyCreateACollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a capped collection with a maximum of 1000 documents - db.createCollection("a_simple_collection", {capped:true, size:10000, max:1000, safe:true}, function(err, collection) { - test.equal(null, err); - - // Insert a document in the capped collection - collection.insert({a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * A simple example executing a command against the server. - * - * @_class db - * @_function dropCollection - * @ignore - */ -exports.shouldCorrectlyExecuteACommandAgainstTheServer = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Execute ping against the server - db.command({ping:1}, function(err, result) { - test.equal(null, err); - - // Create a capped collection with a maximum of 1000 documents - db.createCollection("a_simple_create_drop_collection", {capped:true, size:10000, max:1000, safe:true}, function(err, collection) { - test.equal(null, err); - - // Insert a document in the capped collection - collection.insert({a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - // Drop the collection from this world - db.dropCollection("a_simple_create_drop_collection", function(err, result) { - test.equal(null, err); - - // Verify that the collection is gone - db.collectionNames("a_simple_create_drop_collection", function(err, names) { - test.equal(0, names.length); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example creating, dropping a collection and then verifying that the collection is gone. - * - * @_class db - * @_function command - * @ignore - */ -exports.shouldCorrectlyCreateDropAndVerifyThatCollectionIsGone = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Execute ping against the server - db.command({ping:1}, function(err, result) { - test.equal(null, err); - - db.close(); - test.done(); - }); - }); -} - -/** - * A simple example creating, dropping a collection and then verifying that the collection is gone. - * - * @_class db - * @_function renameCollection - * @ignore - */ -exports.shouldCorrectlyRenameACollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection("simple_rename_collection", {safe:true}, function(err, collection) { - test.equal(null, err); - - // Insert a document in the collection - collection.insert({a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - // Rename the collection - db.renameCollection("simple_rename_collection", "simple_rename_collection_2", function(err, collection2) { - test.equal(null, err); - - // Retrieve the number of documents from the collection - collection2.count(function(err, count) { - test.equal(1, count); - - // Verify that the collection is gone - db.collectionNames("simple_rename_collection", function(err, names) { - test.equal(0, names.length); - - // Verify that the new collection exists - db.collectionNames("simple_rename_collection_2", function(err, names) { - test.equal(1, names.length); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example using lastError on a single connection with a pool of 1. - * - * @_class db - * @_function lastError - * @ignore - */ -exports.shouldCorrectlyUseLastError = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection("simple_rename_collection", {safe:true}, function(err, collection) { - test.equal(null, err); - - // Insert a document in the collection - collection.insert({a:1}, function(err, result) { - test.equal(null, err); - - // Execute lastError - db.lastError(function(err, result) { - test.equal(null, err); - test.equal(null, result[0].err); - - // Pick a specific connection and execute lastError against it - var connection = db.serverConfig.checkoutWriter(); - // Execute lastError - db.lastError({}, {connection:connection}, function(err, result) { - test.equal(null, err); - test.equal(null, result[0].err); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example using previousError to return the list of all errors, might be deprecated in the future. - * - * @_class db - * @_function previousErrors - * @ignore - */ -exports.shouldCorrectlyUsePreviousError = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection("simple_previous_error_coll", {safe:true}, function(err, collection) { - test.equal(null, err); - - // Force a unique index - collection.ensureIndex({a:1}, {unique:true}, function(err, result) { - test.equal(null, err); - - // Force some errors - collection.insert([{a:1}, {a:1}, {a:1}, {a:2}], function(err, result) { - - // Pick a specific connection and execute lastError against it - var connection = db.serverConfig.checkoutWriter(); - - // Execute previousErrors - db.previousErrors({connection:connection}, function(err, result) { - test.equal(null, err); - test.equal(1, result.length); - test.ok(result[0].err != null); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example using resetErrorHistory to clean up the history of errors. - * - * @_class db - * @_function resetErrorHistory - * @ignore - */ -exports.shouldCorrectlyUseResetErrorHistory = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Create a collection - db.createCollection("simple_reset_error_history_coll", {safe:true}, function(err, collection) { - test.equal(null, err); - - // Force a unique index - collection.ensureIndex({a:1}, {unique:true}, function(err, result) { - test.equal(null, err); - - // Force some errors - collection.insert([{a:1}, {a:1}, {a:1}, {a:2}], function(err, result) { - // Pick a specific connection and execute lastError against it - var connection = db.serverConfig.checkoutWriter(); - - // Reset the error history - db.resetErrorHistory({connection:connection}, function(err, result) { - - // Execute previousErrors and validate that there are no errors left - db.previousErrors({connection:connection}, function(err, result) { - test.equal(null, err); - test.equal(1, result.length); - test.equal(null, result[0].err); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A more complex createIndex using a compound unique index in the background and dropping duplicated documents - * - * @_class db - * @_function createIndex - */ -exports.shouldCreateComplexIndexOnTwoFields = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_complex_index_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - db.createIndex('more_complex_index_test', {a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Show that duplicate records got dropped - collection.find({}).toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - - // Peform a query, with explain to show we hit the query - collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { - test.equal(null, err); - test.ok(explanation[0].indexBounds.a != null); - test.ok(explanation[0].indexBounds.b != null); - - db.close(); - test.done(); - }); - }) - }); - }); - }); - }); -} - -/** - * A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents. - * - * @_class db - * @_function ensureIndex - */ -exports.shouldCreateComplexEnsureIndex = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_complex_ensure_index_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - db.ensureIndex('more_complex_ensure_index_test', {a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Show that duplicate records got dropped - collection.find({}).toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - - // Peform a query, with explain to show we hit the query - collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { - test.equal(null, err); - test.ok(explanation[0].indexBounds.a != null); - test.ok(explanation[0].indexBounds.b != null); - - db.close(); - test.done(); - }); - }) - }); - }); - }); - }); -} - -/** - * A Simple example of returning current cursor information in MongoDB - * - * @_class db - * @_function cursorInfo - */ -exports.shouldCorrectlyReturnCursorInformation = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('cursor_information_collection', function(err, collection) { - test.equal(null, err); - - // Create a bunch of documents so we can force the creation of a cursor - var docs = []; - for(var i = 0; i < 1000; i++) { - docs.push({a:'hello world hello world hello world hello world hello world hello world hello world hello world'}); - } - - // Insert a bunch of documents for the index - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - // Let's set a cursor - var cursor = collection.find({}, {batchSize:10}); - cursor.nextObject(function(err, item) { - test.equal(null, err); - - // Let's grab the information about the cursors on the database - db.cursorInfo(function(err, cursorInformation) { - test.ok(cursorInformation.totalOpen > 0); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * An examples showing the creation and dropping of an index - * - * @_class db - * @_function dropIndex - */ -exports.shouldCorrectlyCreateAndDropIndex = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('create_and_drop_an_index', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Drop the index - db.dropIndex("create_and_drop_an_index", "a_1_b_1", function(err, result) { - test.equal(null, err); - - // Verify that the index is gone - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.equal(null, indexInformation.a_1_b_1); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An example showing how to force a reindex of a collection. - * - * @_class db - * @_function reIndex - */ -exports.shouldCorrectlyForceReindexOnCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('create_and_drop_all_indexes', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Force a reindex of the collection - db.reIndex('create_and_drop_all_indexes', function(err, result) { - test.equal(null, err); - test.equal(true, result); - - // Verify that the index is gone - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An example showing the information returned by indexInformation - * - * @_class db - * @_function indexInformation - */ -exports.shouldCorrectlyShowTheResultsFromIndexInformation = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_index_information_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Fetch basic indexInformation for collection - db.indexInformation('more_index_information_test', function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); - - // Fetch full index information - collection.indexInformation({full:true}, function(err, indexInformation) { - test.deepEqual({ _id: 1 }, indexInformation[0].key); - test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An examples showing the dropping of a database - * - * @_class db - * @_function dropDatabase - */ -exports.shouldCorrectlyShowTheResultsFromIndexInformation = function(test) { - var db = new Db('integration_tests_to_drop', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection - db.createCollection('more_index_information_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Let's drop the database - db.dropDatabase(function(err, result) { - test.equal(null, err); - - // Get the admin database - db.admin().listDatabases(function(err, dbs) { - // Grab the databases - dbs = dbs.databases; - // Did we find the db - var found = false; - - // Check if we have the db in the list - for(var i = 0; i < dbs.length; i++) { - if(dbs[i].name == 'integration_tests_to_drop') found = true; - } - - // We should not find the databases - test.equal(false, found); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/error_test.js b/node_modules/reg/node_modules/mongodb/test/error_test.js deleted file mode 100644 index 4e7c399..0000000 --- a/node_modules/reg/node_modules/mongodb/test/error_test.js +++ /dev/null @@ -1,311 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -// Test the error reporting functionality -exports.shouldCorrectlyRetrieveErrorMessagesFromServer = function(test) { - // Just run with one connection in the pool - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize:1, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Open the db - error_client.open(function(err, error_client) { - error_client.resetErrorHistory(function() { - error_client.error(function(err, documents) { - test.equal(true, documents[0].ok); - test.equal(0, documents[0].n); - - // Force error on server - error_client.executeDbCommand({forceerror: 1}, function(err, r) { - test.equal(0, r.documents[0].ok); - test.ok(r.documents[0].errmsg.length > 0); - // Check for previous errors - error_client.previousErrors(function(err, documents) { - test.equal(true, documents[0].ok); - test.equal(1, documents[0].nPrev); - test.equal("forced error", documents[0].err); - - // Check for the last error - error_client.error(function(err, documents) { - test.equal("forced error", documents[0].err); - // Force another error - error_client.collection('test_error_collection', function(err, collection) { - collection.findOne({name:"Fred"}, function(err, document) { - // Check that we have two previous errors - error_client.previousErrors(function(err, documents) { - test.equal(true, documents[0].ok); - test.equal(2, documents[0].nPrev); - test.equal("forced error", documents[0].err); - - error_client.resetErrorHistory(function() { - error_client.previousErrors(function(err, documents) { - test.equal(true, documents[0].ok); - test.equal(-1, documents[0].nPrev); - - error_client.error(function(err, documents) { - test.equal(true, documents[0].ok); - test.equal(0, documents[0].n); - - // Let's close the db - error_client.close(); - - error_client.error(function(err, documents) { - test.ok(err instanceof Error); - test.equal('no open connections', err.message); - test.done(); - }); - }); - }) - }); - }); - }); - }); - }) - }); - }); - }); - }); - }); -} - -// Test the last status functionality of the driver -exports.shouldCorrectlyExecuteLastStatus = function(test) { - // Just run with one connection in the pool - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, poolSize:1, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Open the db - error_client.open(function(err, client) { - client.createCollection('test_last_status', function(err, collection) { - test.ok(collection instanceof Collection); - test.equal('test_last_status', collection.collectionName); - - // Get the collection - client.collection('test_last_status', function(err, collection) { - // Remove all the elements of the collection - collection.remove(function(err, result) { - // Check update of a document - collection.insert({i:1}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]._id.toHexString().length == 24); - - // Update the record - collection.update({i:1}, {"$set":{i:2}}, function(err, result) { - // Check for the last message from the server - client.lastStatus(function(err, status) { - test.equal(true, status[0].ok); - test.equal(true, status[0].updatedExisting); - // Check for failed update of document - collection.update({i:1}, {"$set":{i:500}}, function(err, result) { - client.lastStatus(function(err, status) { - test.equal(true, status[0].ok); - test.equal(false, status[0].updatedExisting); - - // Check safe update of a document - collection.insert({x:1}, function(err, ids) { - collection.update({x:1}, {"$set":{x:2}}, {'safe':true}, function(err, document) { - }); - - collection.update({x:1}, {"$set":{x:2}}, {'safe':true}); - - collection.update({y:1}, {"$set":{y:2}}, {'safe':true}, function(err, result) { - test.equal(0, result); - - // Let's close the db - error_client.close(); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports.shouldFailInsertDueToUniqueIndex = function(test) { - client.createCollection('test_failing_insert_due_to_unique_index', function(err, r) { - client.collection('test_failing_insert_due_to_unique_index', function(err, collection) { - collection.ensureIndex([['a', 1 ]], true, function(err, indexName) { - collection.insert({a:2}, {safe: true}, function(err, r) { - test.ok(err == null); - collection.insert({a:2}, {safe: true}, function(err, r) { - test.ok(err != null); - test.done(); - }) - }) - }) - }) - }) -} - -// Test the error reporting functionality -exports.shouldFailInsertDueToUniqueIndexStrict = function(test) { - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - error_client.open(function(err, error_client) { - error_client.dropCollection('test_failing_insert_due_to_unique_index_strict', function(err, r) { - error_client.createCollection('test_failing_insert_due_to_unique_index_strict', function(err, r) { - error_client.collection('test_failing_insert_due_to_unique_index_strict', function(err, collection) { - collection.ensureIndex([['a', 1 ]], true, function(err, indexName) { - collection.insert({a:2}, {safe:true}, function(err, r) { - test.ok(err == null); - collection.insert({a:2}, {safe:true}, function(err, r) { - test.ok(err != null); - error_client.close(); - test.done(); - }) - }) - }) - }) - }) - }); - }); -} - -exports['safe mode should pass the disconnected error to the callback'] = function (test) { - var error_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - var name = 'test_safe_mode_when_disconnected'; - error_client.open(function(err, error_client) { - test.ok(err == null); - error_client.resetErrorHistory(function() { - error_client.dropCollection(name, function() { - error_client.createCollection(name, function(err, collection) { - test.ok(err == null); - collection.insert({ inserted: true }, { safe: true }, function (err) { - test.ok(err == null); - error_client.close(); - - collection.insert({ works: true }, { safe: true }, function (err) { - test.ok(err instanceof Error); - test.equal('no open connections', err.message); - - collection.update({ inserted: true }, { inserted: true, x: 1 }, { safe: true }, function (err) { - test.ok(err instanceof Error); - test.equal('no open connections', err.message); - - collection.remove({ inserted: true }, { safe: true }, function (err) { - test.ok(err instanceof Error); - test.equal('no open connections', err.message); - - collection.findOne({ works: true }, function (err) { - test.ok(err instanceof Error); - test.equal('no open connections', err.message); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports.shouldHandleAssertionError = function(test) { - client.createCollection('test_handle_assertion_error', function(err, r) { - client.collection('test_handle_assertion_error', function(err, collection) { - collection.insert({a:{lat:50, lng:10}}, {safe: true}, function(err, docs) { - test.ok(err == null); - - var query = {a:{$within:{$box:[[1,-10],[80,120]]}}}; - - // We don't have a geospatial index at this point - collection.findOne(query, function(err, docs) { - test.ok(err instanceof Error); - - collection.ensureIndex([['a', '2d' ]], true, function(err, indexName) { - test.ok(err == null); - - collection.findOne(query, function(err, doc) { - test.ok(err == null); - - var invalidQuery = {a:{$within:{$box:[[-10,-180],[10,180]]}}}; - - client.admin().serverInfo(function(err, result){ - collection.findOne(invalidQuery, function(err, doc) { - if(parseInt((result.version.replace(/\./g, ''))) < 200) { - test.ok(err instanceof Error); - } else { - test.equal(null, err); - test.equal(null, doc); - } - - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/exception_handling_test.js b/node_modules/reg/node_modules/mongodb/test/exception_handling_test.js deleted file mode 100644 index b7424cc..0000000 --- a/node_modules/reg/node_modules/mongodb/test/exception_handling_test.js +++ /dev/null @@ -1,101 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlyHandleThrownError = function(test) { - client.createCollection('shouldCorrectlyHandleThrownError', function(err, r) { - try { - client.collection('shouldCorrectlyHandleThrownError', function(err, collection) { - debug(someUndefinedVariable); - }); - } catch (err) { - test.ok(err != null); - test.done(); - } - }); -} - -exports.shouldCorrectlyHandleThrownErrorInRename = function(test) { - // Catch unhandled exception - process.on("uncaughtException", function(err) { - // Remove listener - process.removeAllListeners("uncaughtException"); - test.done() - }) - - // Execute code - client.createCollection('shouldCorrectlyHandleThrownErrorInRename', function(err, r) { - client.collection('shouldCorrectlyHandleThrownError', function(err, collection) { - collection.rename("shouldCorrectlyHandleThrownErrorInRename2", function(err, result) { - debug(someUndefinedVariable); - }) - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/find_test.js b/node_modules/reg/node_modules/mongodb/test/find_test.js deleted file mode 100644 index b828c2e..0000000 --- a/node_modules/reg/node_modules/mongodb/test/find_test.js +++ /dev/null @@ -1,1647 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Step = require('../deps/step/lib/step'), - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Code = require('../lib/mongodb/bson/code').Code, - Long = require('../lib/mongodb/bson/long').Long, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var POOL_SIZE = 4; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * Test a simple find - * @ignore - */ -exports.shouldCorrectlyPerformSimpleFind = function(test) { - client.createCollection('test_find_simple', function(err, r) { - var collection = client.collection('test_find_simple', function(err, collection) { - var doc1 = null; - var doc2 = null; - - // Insert some test documents - collection.insert([{a:2}, {b:3}], {safe:true}, function(err, docs) { - doc1 = docs[0]; - doc2 = docs[1] - - // Ensure correct insertion testing via the cursor and the count function - collection.find(function(err, cursor) { - cursor.toArray(function(err, documents) { - test.equal(2, documents.length); - - collection.count(function(err, count) { - test.equal(2, count); - - // Fetch values by selection - collection.find({'a': doc1.a}, function(err, cursor) { - cursor.toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal(doc1.a, documents[0].a); - // Let's close the db - test.done(); - }); - }); - }); - }) - }); - }); - }); - }); -} - -/** - * Test a simple find chained - * @ignore - */ -exports.shouldCorrectlyPeformSimpleChainedFind = function(test) { - client.createCollection('test_find_simple_chained', function(err, r) { - var collection = client.collection('test_find_simple_chained', function(err, collection) { - var doc1 = null; - var doc2 = null; - - // Insert some test documents - collection.insert([{a:2}, {b:3}], {safe:true}, function(err, docs) { - doc1 = docs[0]; - doc2 = docs[1] - - // Ensure correct insertion testing via the cursor and the count function - collection.find().toArray(function(err, documents) { - test.equal(2, documents.length); - - collection.count(function(err, count) { - test.equal(2, count); - - // Fetch values by selection - collection.find({'a': doc1.a}).toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal(doc1.a, documents[0].a); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * Test advanced find - * @ignore - */ -exports.shouldCorrectlyPeformAdvancedFinds = function(test) { - client.createCollection('test_find_advanced', function(err, r) { - var collection = client.collection('test_find_advanced', function(err, collection) { - var doc1 = null, doc2 = null, doc3 = null; - - // Insert some test documents - collection.insert([{a:1}, {a:2}, {b:3}], {safe:true}, function(err, docs) { - var doc1 = docs[0], doc2 = docs[1], doc3 = docs[2]; - - // Locate by less than - collection.find({'a':{'$lt':10}}).toArray(function(err, documents) { - test.equal(2, documents.length); - // Check that the correct documents are returned - var results = []; - // Check that we have all the results we want - documents.forEach(function(doc) { - if(doc.a == 1 || doc.a == 2) results.push(1); - }); - test.equal(2, results.length); - }); - - // Locate by greater than - collection.find({'a':{'$gt':1}}).toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal(2, documents[0].a); - }); - - // Locate by less than or equal to - collection.find({'a':{'$lte':1}}).toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal(1, documents[0].a); - }); - - // Locate by greater than or equal to - collection.find({'a':{'$gte':1}}).toArray(function(err, documents) { - test.equal(2, documents.length); - // Check that the correct documents are returned - var results = []; - // Check that we have all the results we want - documents.forEach(function(doc) { - if(doc.a == 1 || doc.a == 2) results.push(1); - }); - test.equal(2, results.length); - }); - - // Locate by between - collection.find({'a':{'$gt':1, '$lt':3}}).toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal(2, documents[0].a); - }); - - // Locate in clause - collection.find({'a':{'$in':[1,2]}}).toArray(function(err, documents) { - test.equal(2, documents.length); - // Check that the correct documents are returned - var results = []; - // Check that we have all the results we want - documents.forEach(function(doc) { - if(doc.a == 1 || doc.a == 2) results.push(1); - }); - test.equal(2, results.length); - }); - - // Locate in _id clause - collection.find({'_id':{'$in':[doc1['_id'], doc2['_id']]}}).toArray(function(err, documents) { - test.equal(2, documents.length); - // Check that the correct documents are returned - var results = []; - // Check that we have all the results we want - documents.forEach(function(doc) { - if(doc.a == 1 || doc.a == 2) results.push(1); - }); - test.equal(2, results.length); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * Test sorting of results - * @ignore - */ -exports.shouldCorrectlyPerformFindWithSort = function(test) { - client.createCollection('test_find_sorting', function(err, r) { - client.collection('test_find_sorting', function(err, collection) { - var doc1 = null, doc2 = null, doc3 = null, doc4 = null; - // Insert some test documents - collection.insert([{a:1, b:2}, - {a:2, b:1}, - {a:3, b:2}, - {a:4, b:1} - ], {safe:true}, function(err, docs) { - doc1 = docs[0]; - doc2 = docs[1]; - doc3 = docs[2]; - doc4 = docs[3] - - // Test sorting (ascending) - collection.find({'a': {'$lt':10}}, {'sort': [['a', 1]]}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(1, documents[0].a); - test.equal(2, documents[1].a); - test.equal(3, documents[2].a); - test.equal(4, documents[3].a); - - // Test sorting (descending) - collection.find({'a': {'$lt':10}}, {'sort': [['a', -1]]}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(4, documents[0].a); - test.equal(3, documents[1].a); - test.equal(2, documents[2].a); - test.equal(1, documents[3].a); - - // Test sorting (descending), sort is hash - collection.find({'a': {'$lt':10}}, {sort: {a: -1}}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(4, documents[0].a); - test.equal(3, documents[1].a); - test.equal(2, documents[2].a); - test.equal(1, documents[3].a); - - // Sorting using array of names, assumes ascending order - collection.find({'a': {'$lt':10}}, {'sort': ['a']}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(1, documents[0].a); - test.equal(2, documents[1].a); - test.equal(3, documents[2].a); - test.equal(4, documents[3].a); - - // Sorting using single name, assumes ascending order - collection.find({'a': {'$lt':10}}, {'sort': 'a'}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(1, documents[0].a); - test.equal(2, documents[1].a); - test.equal(3, documents[2].a); - test.equal(4, documents[3].a); - - // Sorting using single name, assumes ascending order, sort is hash - collection.find({'a': {'$lt':10}}, {sort: {'a':1}}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(1, documents[0].a); - test.equal(2, documents[1].a); - test.equal(3, documents[2].a); - test.equal(4, documents[3].a); - - collection.find({'a': {'$lt':10}}, {'sort': ['b', 'a']}).toArray(function(err, documents) { - test.equal(4, documents.length); - test.equal(2, documents[0].a); - test.equal(4, documents[1].a); - test.equal(1, documents[2].a); - test.equal(3, documents[3].a); - - // Sorting using empty array, no order guarantee should not blow up - collection.find({'a': {'$lt':10}}, {'sort': []}).toArray(function(err, documents) { - test.equal(4, documents.length); - - /* NONACTUAL */ - // Sorting using ordered hash - collection.find({'a': {'$lt':10}}, {'sort': {a:-1}}).toArray(function(err, documents) { - // Fail test if not an error - test.equal(4, documents.length); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Test the limit function of the db - * @ignore - */ -exports.shouldCorrectlyPerformFindWithLimit = function(test) { - client.createCollection('test_find_limits', function(err, r) { - client.collection('test_find_limits', function(err, collection) { - var doc1 = null, doc2 = null, doc3 = null, doc4 = null; - - // Insert some test documents - collection.insert([{a:1}, - {b:2}, - {c:3}, - {d:4} - ], {safe:true}, function(err, docs) { - doc1 = docs[0]; - doc2 = docs[1]; - doc3 = docs[2]; - doc4 = docs[3] - - // Test limits - collection.find({}, {'limit': 1}).toArray(function(err, documents) { - test.equal(1, documents.length); - }); - - collection.find({}, {'limit': 2}).toArray(function(err, documents) { - test.equal(2, documents.length); - }); - - collection.find({}, {'limit': 3}).toArray(function(err, documents) { - test.equal(3, documents.length); - }); - - collection.find({}, {'limit': 4}).toArray(function(err, documents) { - test.equal(4, documents.length); - }); - - collection.find({}, {}).toArray(function(err, documents) { - test.equal(4, documents.length); - }); - - collection.find({}, {'limit':99}).toArray(function(err, documents) { - test.equal(4, documents.length); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * Test find by non-quoted values (issue #128) - * @ignore - */ -exports.shouldCorrectlyFindWithNonQuotedValues = function(test) { - client.createCollection('test_find_non_quoted_values', function(err, r) { - client.collection('test_find_non_quoted_values', function(err, collection) { - // insert test document - collection.insert([{ a: 19, b: 'teststring', c: 59920303 }, - { a: "19", b: 'teststring', c: 3984929 }], {safe:true} , function(err, r) { - - collection.find({ a: 19 }).toArray(function(err, documents) { - test.equal(1, documents.length); - test.done(); - }); - }); - }); - }); -} - -/** - * Test for querying embedded document using dot-notation (issue #126) - * @ignore - */ -exports.shouldCorrectlyFindEmbeddedDocument = function(test) { - client.createCollection('test_find_embedded_document', function(err, r) { - client.collection('test_find_embedded_document', function(err, collection) { - // insert test document - collection.insert([{ a: { id: 10, value: 'foo' }, b: 'bar', c: { id: 20, value: 'foobar' }}, - { a: { id: 11, value: 'foo' }, b: 'bar2', c: { id: 20, value: 'foobar' }}], {safe:true}, function(err, r) { - - // test using integer value - collection.find({ 'a.id': 10 }).toArray(function(err, documents) { - test.equal(1, documents.length); - test.equal('bar', documents[0].b); - }); - - // test using string value - collection.find({ 'a.value': 'foo' }).toArray(function(err, documents) { - // should yield 2 documents - test.equal(2, documents.length); - test.equal('bar', documents[0].b); - test.equal('bar2', documents[1].b); - test.done(); - }); - }); - }); - }); -} - -/** - * Find no records - * @ignore - */ -exports.shouldCorrectlyFindNoRecords = function(test) { - client.createCollection('test_find_one_no_records', function(err, r) { - client.collection('test_find_one_no_records', function(err, collection) { - collection.find({'a':1}, {}).toArray(function(err, documents) { - test.equal(0, documents.length); - // Let's close the db - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformFindByWhere = function(test) { - client.createCollection('test_where', function(err, collection) { - test.ok(collection instanceof Collection); - collection.insert([{'a':1}, {'a':2}, {'a':3}], {safe:true}, function(err, ids) { - collection.count(function(err, count) { - test.equal(3, count); - - // Let's test usage of the $where statement - collection.find({'$where':new Code('this.a > 2')}).count(function(err, count) { - test.equal(1, count); - }); - - collection.find({'$where':new Code('this.a > i', {i:1})}).count(function(err, count) { - test.equal(2, count); - - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformFindsWithHintTurnedOn = function(test) { - client.createCollection('test_hint', function(err, collection) { - collection.insert({'a':1}, {safe:true}, function(err, ids) { - client.createIndex(collection.collectionName, "a", function(err, indexName) { - collection.find({'a':1}, {'hint':'a'}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - collection.find({'a':1}, {'hint':['a']}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - collection.find({'a':1}, {'hint':{'a':1}}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - // Modify hints - collection.hint = 'a'; - test.equal(1, collection.hint['a']); - collection.find({'a':1}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - collection.hint = ['a']; - test.equal(1, collection.hint['a']); - collection.find({'a':1}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - collection.hint = {'a':1}; - test.equal(1, collection.hint['a']); - collection.find({'a':1}).toArray(function(err, items) { - test.equal(1, items.length); - }); - - collection.hint = null; - test.ok(collection.hint == null); - collection.find({'a':1}).toArray(function(err, items) { - test.equal(1, items.length); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformFindByObjectID = function(test) { - client.createCollection('test_find_by_oid', function(err, collection) { - collection.save({'hello':'mike'}, {safe:true}, function(err, docs) { - test.ok(docs._id instanceof ObjectID || Object.prototype.toString.call(docs._id) === '[object ObjectID]'); - - collection.findOne({'_id':docs._id}, function(err, doc) { - test.equal('mike', doc.hello); - - var id = doc._id.toString(); - collection.findOne({'_id':new ObjectID(id)}, function(err, doc) { - test.equal('mike', doc.hello); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReturnDocumentWithOriginalStructure= function(test) { - client.createCollection('test_find_by_oid_with_subdocs', function(err, collection) { - var c1 = { _id: new ObjectID, comments: [], title: 'number 1' }; - var c2 = { _id: new ObjectID, comments: [], title: 'number 2' }; - var doc = { - numbers: [] - , owners: [] - , comments: [c1, c2] - , _id: new ObjectID - }; - - collection.insert(doc, {safe:true}, function(err, docs) { - collection.findOne({'_id':doc._id}, {safe:true,fields: undefined}, function(err, doc) { - if (err) console.error('error', err); - test.equal(2, doc.comments.length); - test.equal('number 1', doc.comments[0].title); - test.equal('number 2', doc.comments[1].title); - - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyRetrieveSingleRecord = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - client.createCollection('test_should_correctly_retrieve_one_record', function(err, collection) { - collection.insert({'a':0}, {safe:true}, function(err, r) { - p_client.collection('test_should_correctly_retrieve_one_record', function(err, usercollection) { - usercollection.findOne({'a': 0}, function(err, result) { - p_client.close(); - - test.done(); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleError = function(test) { - client.createCollection('test_find_one_error_handling', function(err, collection) { - // Try to fetch an object using a totally invalid and wrong hex string... what we're interested in here - // is the error handling of the findOne Method - try { - collection.findOne({"_id":ObjectID.createFromHexString('5e9bd59248305adf18ebc15703a1')}, function(err, result) {}); - } catch (err) { - test.done(); - } - }); -} - -/** - * Test field select with options - * @ignore - */ -exports.shouldCorrectlyPerformFindWithOptions = function(test) { - client.createCollection('test_field_select_with_options', function(err, r) { - var collection = client.collection('test_field_select_with_options', function(err, collection) { - var docCount = 25, docs = []; - - // Insert some test documents - while(docCount--) docs.push({a:docCount, b:docCount}); - collection.insert(docs, {safe:true}, function(err,retDocs) { - docs = retDocs; - - collection.find({},{ 'a' : 1},{ limit : 3, sort : [['a',-1]] }).toArray(function(err,documents){ - test.equal(3,documents.length); - documents.forEach(function(doc,idx){ - test.equal(undefined,doc.b); // making sure field select works - test.equal((24-idx),doc.a); // checking limit sort object with field select - }); - }); - - collection.find({},{},10,3).toArray(function(err,documents){ - test.equal(3,documents.length); - documents.forEach(function(doc,idx){ - test.equal(doc.a,doc.b); // making sure empty field select returns properly - test.equal((14-idx),doc.a); // checking skip and limit in args - }); - - test.done(); - }); - }); - }); - }); -} - -/** - * Test findAndModify a document - * @ignore - */ -exports.shouldCorrectlyFindAndModifyDocument = function(test) { - client.createCollection('test_find_and_modify_a_document', function(err, collection) { - // Test return new document on change - collection.insert({'a':1, 'b':2}, {safe:true}, function(err, doc) { - // Let's modify the document in place - collection.findAndModify({'a':1}, [['a', 1]], {'$set':{'b':3}}, {'new':true}, function(err, updated_doc) { - test.equal(1, updated_doc.a); - test.equal(3, updated_doc.b); - - // Test return old document on change - collection.insert({'a':2, 'b':2}, {safe:true}, function(err, doc) { - // Let's modify the document in place - collection.findAndModify({'a':2}, [['a', 1]], {'$set':{'b':3}}, {safe:true}, function(err, result) { - test.equal(2, result.a); - test.equal(2, result.b); - - // Test remove object on change - collection.insert({'a':3, 'b':2}, {safe:true}, function(err, doc) { - // Let's modify the document in place - collection.findAndModify({'a':3}, [], {'$set':{'b':3}}, {'new': true, remove: true}, function(err, updated_doc) { - test.equal(3, updated_doc.a); - test.equal(2, updated_doc.b); - - // Let's upsert! - collection.findAndModify({'a':4}, [], {'$set':{'b':3}}, {'new': true, upsert: true}, function(err, updated_doc) { - test.equal(4, updated_doc.a); - test.equal(3, updated_doc.b); - - // Test selecting a subset of fields - collection.insert({a: 100, b: 101}, {safe:true}, function (err, ids) { - collection.findAndModify({'a': 100}, [], {'$set': {'b': 5}}, {'new': true, fields: {b: 1}}, function (err, updated_doc) { - test.equal(2, Object.keys(updated_doc).length); - test.equal(ids[0]['_id'].toHexString(), updated_doc._id.toHexString()); - test.equal(5, updated_doc.b); - test.equal("undefined", typeof updated_doc.a); - test.done(); - }); - }); - }); - }) - }); - }) - }); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteFindOneWithAnInSearchTag = function(test) { - client.createCollection('shouldCorrectlyExecuteFindOneWithAnInSearchTag', function(err, collection) { - // Test return new document on change - collection.insert({'tags':[]}, {safe:true}, function(err, docs) { - // Fetch the id - var id = docs[0]._id - - Step( - function findFirst() { - var self = this; - - collection.findOne({_id:id}, function(err, doc) { - test.equal(null, err) - test.ok(doc != null); - - // Perform atomic push operation - collection.update({_id:id}, {'$push':{comments:{title:'1'}}}, {safe:true}, self); - }) - }, - - function findSecond(err, result) { - var self = this; - test.equal(1, result); - test.equal(null, err); - - collection.findOne({_id:id}, function(err, doc) { - test.equal(null, err) - test.ok(doc != null); - test.deepEqual(1, doc.comments.length); - - // Perform atomic push operation - collection.update({_id:id}, {'$push':{comments:{title:'2'}}}, {safe:true}, self); - }) - }, - - function findThird(err, result) { - var self = this; - test.equal(1, result); - test.equal(null, err); - - collection.findOne({_id:id}, function(err, doc) { - test.equal(null, err) - test.ok(doc != null); - test.deepEqual(2, doc.comments.length); - - // Perform atomic push operation - collection.update({_id:id}, {'$push':{comments:{title:'3'}}}, {safe:true}, self); - }) - }, - - function findFourth(err, result) { - var self = this; - test.equal(1, result); - test.equal(null, err); - - collection.findOne({_id:id}, function(err, doc) { - test.equal(null, err) - test.ok(doc != null); - test.deepEqual(3, doc.comments.length); - // Perform atomic push operation - collection.update({_id:id}, {'$pushAll':{comments:[{title:'4'}, {title:'5'}]}}, {safe:true}, self); - }) - }, - - function findFourth(err, result) { - var self = this; - test.equal(1, result); - test.equal(null, err); - - collection.findOne({_id:id}, function(err, doc) { - test.equal(null, err) - test.ok(doc != null); - test.deepEqual(5, doc.comments.length); - test.done(); - }) - } - ) - }) - }); -} - -/** - * @ignore - */ -exports['ShouldCorrectlyLocatePostAndIncValues'] = function(test) { - client.createCollection('shouldCorrectlyExecuteFindOneWithAnInSearchTag', function(err, collection) { - // Test return new document on change - collection.insert({title:'Tobi', - author:'Brian', - newTitle:'Woot', meta:{visitors:0}}, {safe:true}, function(err, docs) { - // Fetch the id - var id = docs[0]._id - - collection.update({_id:id}, {$inc:{ 'meta.visitors': 1 }}, {safe:true}, function(err, result) { - test.equal(1, result); - test.equal(null, err); - - collection.findOne({_id:id}, function(err, item) { - test.equal(1, item.meta.visitors); - test.done() - }) - }); - }); - }); -} - -/** - * Test findAndModify a document - * @ignore - */ -exports['Should Correctly Handle FindAndModify Duplicate Key Error'] = function(test) { - client.createCollection('FindAndModifyDuplicateKeyError', function(err, collection) { - collection.ensureIndex(['name', 1], {unique:true}, function(err, index) { - // Test return new document on change - collection.insert([{name:'test1'}, {name:'test2'}], {safe:true}, function(err, doc) { - // Let's modify the document in place - collection.findAndModify({name: 'test1'}, [], {$set: {name: 'test2'}}, {}, function(err, updated_doc) { - test.equal(null, updated_doc); - test.ok(err != null); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly return null when attempting to modify a non-existing document'] = function(test) { - client.createCollection('AttemptToFindAndModifyNonExistingDocument', function(err, collection) { - // Let's modify the document in place - collection.findAndModify({name: 'test1'}, [], {$set: {name: 'test2'}}, {}, function(err, updated_doc) { - test.equal(null, updated_doc); - test.ok(err == null || err.errmsg.match("No matching object found")) - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly handle chained skip and limit on find with toArray'] = function(test) { - client.createCollection('skipAndLimitOnFindWithToArray', function(err, collection) { - collection.insert([{a:1}, {b:2}, {c:3}], {safe:true}, function(err, result) { - - collection.find().skip(1).limit(1).toArray(function(err, items) { - test.equal(null, err); - test.equal(1, items.length); - test.equal(2, items[0].b) - test.done(); - }) - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly pass timeout options to cursor'] = function(test) { - client.createCollection('timeoutFalse', function(err, collection) { - collection.find({},{timeout:false},function(err, cursor) { - test.equal(false, cursor.timeout); - }); - collection.find({},{timeout:true},function(err, cursor) { - test.equal(true, cursor.timeout); - }); - collection.find({},{},function(err, cursor) { - test.equal(true, cursor.timeout); - }); - - test.done(); - }); -} - -/** - * Test findAndModify a document with strict mode enabled - * @ignore - */ -exports.shouldCorrectlyFindAndModifyDocumentWithDBStrict = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - p_client.createCollection('shouldCorrectlyFindAndModifyDocumentWithDBStrict', function(err, collection) { - // Test return old document on change - collection.insert({'a':2, 'b':2}, {safe:true}, function(err, doc) { - // Let's modify the document in place - collection.findAndModify({'a':2}, [['a', 1]], {'$set':{'b':3}}, {new:true}, function(err, result) { - test.equal(2, result.a) - test.equal(3, result.b) - p_client.close(); - test.done(); - }) - }); - }); - }); -} - -/** - * Test findAndModify a document that fails in first step before safe - * @ignore - */ -exports.shouldCorrectlyFindAndModifyDocumentThatFailsInFirstStep = function(test) { - client.createCollection('shouldCorrectlyFindAndModifyDocumentThatFailsInFirstStep', function(err, collection) { - // Set up an index to force duplicate index erro - collection.ensureIndex([['failIndex', 1]], {unique:true}, function(err, index) { - // Setup a new document - collection.insert({'a':2, 'b':2, 'failIndex':1}, function(err, doc) { - - // Let's attempt to upsert with a duplicate key error - collection.findAndModify({'c':2}, [['a', 1]], {'a':10, 'b':10, 'failIndex':1}, {safe:true, upsert:true}, function(err, result) { - test.equal(null, result); - test.ok(err.errmsg.match("duplicate key error index")); - test.done(); - }) - }); - }); - }); -} - -/** - * Test findAndModify a document that fails in first step before safe - * @ignore - */ -exports.shouldCorrectlyFindAndModifyDocumentThatFailsInSecondStepWithNoMatchingDocuments = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - p_client.createCollection('shouldCorrectlyFindAndModifyDocumentThatFailsInSecondStepWithNoMatchingDocuments', function(err, collection) { - // Test return old document on change - collection.insert({'a':2, 'b':2}, function(err, doc) { - - // Let's modify the document in place - collection.findAndModify({'a':2}, [['a', 1]], {'$set':{'b':3}}, {safe:{w:200, wtimeout:1000}}, function(err, result) { - test.equal(null, result); - test.ok(err != null); - p_client.close(); - test.done(); - }) - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly return new modified document'] = function(test) { - client.createCollection('Should_correctly_return_new_modified_document', function(err, collection) { - var id = new ObjectID(); - var doc = {_id:id, a:1, b:1, c:{a:1, b:1}}; - - collection.insert(doc, {safe:true}, function(err, result) { - test.ok(err == null); - - // Find and modify returning the new object - collection.findAndModify({_id:id}, [], {$set : {'c.c': 100}}, {new:true}, function(err, item) { - test.equal(doc._id.toString(), item._id.toString()); - test.equal(doc.a, item.a); - test.equal(doc.b, item.b); - test.equal(doc.c.a, item.c.a); - test.equal(doc.c.b, item.c.b); - test.equal(100, item.c.c); - test.done(); - }) - }); - }); -} - -/** - * Should correctly execute findAndModify that is breaking in prod - * @ignore - */ -exports.shouldCorrectlyExecuteFindAndModify = function(test) { - client.createCollection('shouldCorrectlyExecuteFindAndModify', function(err, collection) { - var self = {_id : new ObjectID()} - var _uuid = 'sddffdss' - - collection.findAndModify( - {_id: self._id, 'plays.uuid': _uuid}, - [], - {$set : {'plays.$.active': true}}, - {new: true, fields: {plays: 0, results: 0}, safe: true}, - function(err, contest) { - test.done(); - }) - }); -} - -/** - * @ignore - */ -exports['Should correctly return record with 64-bit id'] = function(test) { - client.createCollection('should_correctly_return_record_with_64bit_id', function(err, collection) { - var _lowerId = new ObjectID(); - var _higherId = new ObjectID(); - var lowerId = new Long.fromString('133118461172916224', 10); - var higherId = new Long.fromString('133118461172916225', 10); - - var lowerDoc = {_id:_lowerId, id: lowerId}; - var higherDoc = {_id:_higherId, id: higherId}; - - collection.insert([lowerDoc, higherDoc], {safe:true}, function(err, result) { - test.ok(err == null); - - // Select record with id of 133118461172916225 using $gt directive - collection.find({id: {$gt: lowerId}}, {}, function(err, cur) { - test.ok(err == null); - - cur.toArray(function(err, arr) { - test.ok(err == null); - test.equal(arr.length, 1, 'Selecting record via $gt directive on 64-bit integer should return a record with higher Id') - test.equal(arr[0].id.toString(), '133118461172916225', 'Returned Id should be equal to 133118461172916225') - test.done() - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly find a Document using findOne excluding _id field'] = function(test) { - client.createCollection('Should_Correctly_find_a_Document_using_findOne_excluding__id_field', function(err, collection) { - var doc = {_id : new ObjectID(), a:1, c:2} - // insert doc - collection.insert(doc, {safe:true}, function(err, result) { - // Get one document, excluding the _id field - collection.findOne({a:1}, {fields:{'_id': 0}}, function(err, item) { - test.equal(null, item._id); - test.equal(1, item.a); - test.equal(2, item.c); - - collection.find({a:1}, {fields:{'_id':0}}).toArray(function(err, items) { - var item = items[0] - test.equal(null, item._id); - test.equal(1, item.a); - test.equal(2, item.c); - test.done(); - }) - }) - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly execute find and findOne queries in the same way'] = function(test) { - client.createCollection('Should_correctly_execute_find_and_findOne_queries_in_the_same_way', function(err, collection) { - var doc = {_id : new ObjectID(), a:1, c:2, comments:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}; - // insert doc - collection.insert(doc, {safe:true}, function(err, result) { - - collection.find({_id: doc._id}, {comments: {$slice: -5}}).toArray(function(err, docs) { - test.equal(5, docs[0].comments.length) - - collection.findOne({_id: doc._id}, {comments: {$slice: -5}}, function(err, item) { - test.equal(5, item.comments.length) - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly execute find and findOne queries with selector set to null'] = function(test) { - client.createCollection('Should_correctly_execute_find_and_findOne_queries_in_the_same_way', function(err, collection) { - var doc = {_id : new ObjectID(), a:1, c:2, comments:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}; - // insert doc - collection.insert(doc, {safe:true}, function(err, result) { - - collection.find(null, {comments: {$slice: -5}}).toArray(function(err, docs) { - test.equal(5, docs[0].comments.length) - - collection.findOne(null, {comments: {$slice: -5}}, function(err, item) { - test.equal(5, item.comments.length) - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandlerErrorForFindAndModifyWhenNoRecordExists = function(test) { - client.createCollection('shouldCorrectlyHandlerErrorForFindAndModifyWhenNoRecordExists', function(err, collection) { - collection.findAndModify({'a':1}, [], {'$set':{'b':3}}, {'new': true}, function(err, updated_doc) { - test.equal(null, err); - test.equal(null, updated_doc); - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteFindAndModifyShouldGenerateCorrectBSON = function(test) { - var transaction = {}; - transaction.document = {}; - transaction.document.type = "documentType"; - transaction.document.id = new ObjectID(); - transaction.transactionId = new ObjectID(); - transaction.amount = 12.3333 - - var transactions = []; - transactions.push(transaction); - // Wrapping object - var wrapingObject = { - funds : { - remaining : 100.5 - }, - - transactions:transactions - } - - client.createCollection('shouldCorrectlyExecuteFindAndModify', function(err, collection) { - collection.insert(wrapingObject, {safe:true}, function(err, doc) { - test.equal(null, err); - - collection.findOne({_id:doc[0]._id, 'funds.remaining': {$gte: 3.0}, 'transactions.id': {$ne: transaction.transactionId}}, function(err, item) { - test.ok(item != null) - - collection.findAndModify({_id:doc[0]._id, 'funds.remaining': {$gte: 3.0}, 'transactions.id': {$ne: transaction.transactionId}}, [], {$push: {transactions: transaction}}, {new: true, safe: true}, function(err, result) { - test.done(); - }); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteMultipleFindsInParallel = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:10, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - p_client.createCollection('tasks', function(err, collection) { - var numberOfOperations = 0; - - // Test return old document on change - collection.insert({'a':2, 'b':2}, {safe:true}, function(err, doc) { - collection.find({"user_id":"4e9fc8d55883d90100000003","lc_status":{"$ne":"deleted"},"owner_rating":{"$exists":false}}, - {"skip":0,"limit":10,"sort":{"updated":-1}}, function(err, cursor) { - cursor.count(function(err, count) { - numberOfOperations = numberOfOperations + 1; - if(numberOfOperations == 2) { - test.done(); - p_client.close(); - } - }) - }); - - collection.find({"user_id":"4e9fc8d55883d90100000003","lc_status":{"$ne":"deleted"},"owner_rating":{"$exists":false}}, - {"skip":0,"limit":10,"sort":{"updated":-1}}, function(err, cursor) { - cursor.count(function(err, count) { - numberOfOperations = numberOfOperations + 1; - if(numberOfOperations == 2) { - test.done(); - p_client.close(); - } - }) - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReturnErrorFromMongodbOnFindAndModifyForcedError = function(test) { - client.createCollection('shouldCorrectlyReturnErrorFromMongodbOnFindAndModifyForcedError', function(err, collection) { - var q = { x: 1 }; - var set = { y:2, _id: new ObjectID() }; - var opts = { new: true, upsert: true }; - // Original doc - var doc = {_id: new ObjectID(), x:1}; - - // Insert original doc - collection.insert(doc, {safe:true}, function(err, result) { - collection.findAndModify(q, [], set, opts, function (err, res) { - test.ok(err != null); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteFindAndModifyUnderConcurrentLoad = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:10, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - var running = true; - - p_client.open(function(err, p_client) { - // Create a collection - p_client.collection("collection1", function(err, collection) { - // Wait a bit and then execute something that will throw a duplicate error - setTimeout(function() { - var id = new ObjectID(); - - collection.insert({_id:id, a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - collection.insert({_id:id, a:1}, {safe:true}, function(err, result) { - running = false; - test.done(); - p_client.close(); - }); - }); - }, 200); - }); - - p_client.collection("collection2", function(err, collection) { - // Keep hammering in inserts - var insert = function() { - process.nextTick(function() { - collection.insert({a:1}); - if(running) process.nextTick(insert); - }); - } - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyIterateOverCollection = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize:1, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - var numberOfSteps = 0; - - // Open db connection - p_client.open(function(err, p_client) { - // Create a collection - p_client.createCollection('shouldCorrectlyIterateOverCollection', function(err, collection) { - for(var i = 0; i < 1000; i++) { - collection.insert({a:1, b:2, c:{d:3, f:'sfdsffffffffffffffffffffffffffffff'}}); - } - - collection.find({}, {}, function(err,cursor) { - cursor.count(function(err,count) { - cursor.each(function(err, obj) { - if (obj == null) { - p_client.close(); - test.equal(1000, numberOfSteps); - test.done(); - } else { - numberOfSteps = numberOfSteps + 1; - } - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyErrorOutFindAndModifyOnDuplicateRecord = function(test) { - var p_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - p_client.open(function(err, p_client) { - p_client.createCollection('shouldCorrectlyErrorOutFindAndModifyOnDuplicateRecord', function(err, collection) { - // Test return old document on change - collection.insert([{'login':'user1'}, {'login':'user2'}], {safe:true}, function(err, docs) { - var id = docs[1]._id; - // Set an index - collection.ensureIndex('login', {unique:true}, function(err, result) { - // Attemp to modify document - collection.findAndModify({_id: id}, [], { $set: {login: 'user1'} }, {}, function(err, user){ - test.ok(err != null); - p_client.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * An example of using find with a very large in parameter - * - * @ignore - */ -exports.shouldPerformSimpleFindInArray = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_find_in_array', function(err, collection) { - test.equal(null, err); - - var docs = []; - for(var i = 0; i < 100; i++) docs.push({a:i}); - - // Insert some test documentations - collection.insert(docs, {safe:true}, function(err, result) { - test.equal(null, err); - - // Find all the variables in a specific array - var inArray = []; - for(var i = 0; i < 100; i++) docs.push(i); - - // Fin all in - collection.find({a:{$in:docs}}).toArray(function(err, items) { - test.equal(null, err); - test.equal(100, items.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - - -/** - * A whole set of different ways to use the findAndModify command. - * - * The first findAndModify command modifies a document and returns the modified document back. - * The second findAndModify command removes the document. - * The second findAndModify command upserts a document and returns the new document. - * @_class collection - * @_function findAndModify - */ -exports.shouldPerformSimpleFindAndModifyOperations = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_find_and_modify_operations_', function(err, collection) { - test.equal(null, err); - - // Insert some test documentations - collection.insert([{a:1}, {b:1}, {c:1}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Simple findAndModify command returning the new document - collection.findAndModify({a:1}, [['a', 1]], {$set:{b1:1}}, {new:true}, function(err, doc) { - test.equal(null, err); - test.equal(1, doc.a); - test.equal(1, doc.b1); - - // Simple findAndModify command returning the new document and - // removing it at the same time - collection.findAndModify({b:1}, [['b', 1]], - {$set:{b:2}}, {remove:true}, function(err, doc) { - - // Verify that the document is gone - collection.findOne({b:1}, function(err, item) { - test.equal(null, err); - test.equal(null, item); - - // Simple findAndModify command performing an upsert and returning the new document - // executing the command safely - collection.findAndModify({d:1}, [['b', 1]], - {d:1, f:1}, {new:true, upsert:true, safe:true}, function(err, doc) { - test.equal(null, err); - test.equal(1, doc.d); - test.equal(1, doc.f); - - db.close(); - test.done(); - }) - }); - }); - }); - }); - }); - }); -} - -/** - * An example of using findAndRemove - * - * @_class collection - * @_function findAndRemove - */ -exports.shouldPerformSimpleFindAndModifyOperations = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_find_and_modify_operations_', function(err, collection) { - test.equal(null, err); - - // Insert some test documentations - collection.insert([{a:1}, {b:1}, {c:1}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Simple findAndModify command returning the new document and - // removing it at the same time - collection.findAndRemove({b:1}, [['b', 1]], function(err, doc) { - test.equal(null, err); - test.equal(1, doc.b); - - // Verify that the document is gone - collection.findOne({b:1}, function(err, item) { - test.equal(null, err); - test.equal(null, item); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple query using the find method on the collection. - * - * @_class collection - * @_function find - */ -exports.shouldPeformASimpleQuery = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_query', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.find().toArray(function(err, docs) { - test.equal(null, err); - test.equal(3, docs.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple query showing the explain for a query - * - * @_class collection - * @_function find - */ -exports.shouldPeformASimpleExplainQuery = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_explain_query', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1}, {a:2}, {a:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.find({}, {explain:true}).toArray(function(err, docs) { - test.equal(null, err); - test.equal(1, docs.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple query showing skip and limit - * - * @_class collection - * @_function find - */ -exports.shouldPeformASimpleLimitSkipQuery = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_limit_skip_query', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.find({}, {skip:1, limit:1, fields:{b:1}}).toArray(function(err, docs) { - test.equal(null, err); - test.equal(1, docs.length); - test.equal(null, docs[0].a); - test.equal(2, docs[0].b); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple query using findOne - * - * @_class collection - * @_function findOne - */ -exports.shouldPeformASimpleLimitSkipFindOneQuery = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_limit_skip_find_one_query', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.findOne({a:2}, {fields:{b:1}}, function(err, doc) { - test.equal(null, err); - test.equal(null, doc.a); - test.equal(2, doc.b); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple query using find and fields - */ -exports.shouldPeformASimpleLimitSkipFindWithFields = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_find_with_fields', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.find({a:2}, ['b']).toArray(function(err, docs) { - test.equal(null, err); - test.equal(1, docs.length); - test.equal(null, docs[0].a); - test.equal(2, docs[0].b); - - // Peform a simple find and return all the documents - collection.find({a:2}, {b:1}).toArray(function(err, docs) { - test.equal(null, err); - test.equal(1, docs.length); - test.equal(null, docs[0].a); - test.equal(2, docs[0].b); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple query using find and fields - */ -exports.shouldPeformASimpleLimitSkipFindWithFields2 = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_find_with_fields_2', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the testing - collection.insert([{a:1, b:1}, {a:2, b:2}, {a:3, b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Peform a simple find and return all the documents - collection.find({a:2}, {fields: ['b']}).toArray(function(err, docs) { - test.equal(null, err); - test.equal(1, docs.length); - test.equal(null, docs[0].a); - test.equal(2, docs[0].b); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/geo_search_test.js b/node_modules/reg/node_modules/mongodb/test/geo_search_test.js deleted file mode 100644 index e27979c..0000000 --- a/node_modules/reg/node_modules/mongodb/test/geo_search_test.js +++ /dev/null @@ -1,146 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Long = require('../lib/mongodb/bson/long').Long, - Step = require("../deps/step/lib/step"), - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * Example of a simple geoNear query across some documents - * - * @_class collection - * @_function geoNear - * @ignore - */ -exports.shouldCorrectlyPerformSimpleGeoNearCommand = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch the collection - db.collection("simple_geo_near_command", function(err, collection) { - - // Add a location based index - collection.ensureIndex({loc:"2d"}, function(err, result) { - - // Save a new location tagged document - collection.insert([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {safe:true}, function(err, result) { - - // Use geoNear command to find document - collection.geoNear(50, 50, {query:{a:1}, num:1}, function(err, docs) { - test.equal(1, docs.results.length); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Example of a simple geoHaystackSearch query across some documents - * - * @_class collection - * @_function geoHaystackSearch - * @ignore - */ -exports.shouldCorrectlyPerformSimpleGeoHaystackSearchCommand = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch the collection - db.collection("simple_geo_haystack_command", function(err, collection) { - - // Add a location based index - collection.ensureIndex({loc: "geoHaystack", type: 1}, {bucketSize: 1}, function(err, result) { - - // Save a new location tagged document - collection.insert([{a:1, loc:[50, 30]}, {a:1, loc:[30, 50]}], {safe:true}, function(err, result) { - - // Use geoNear command to find document - collection.geoHaystackSearch(50, 50, {search:{a:1}, limit:1, maxDistance:100}, function(err, docs) { - test.equal(1, docs.results.length); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/gridstore/grid_store_file_test.js b/node_modules/reg/node_modules/mongodb/test/gridstore/grid_store_file_test.js deleted file mode 100644 index a715fb6..0000000 --- a/node_modules/reg/node_modules/mongodb/test/gridstore/grid_store_file_test.js +++ /dev/null @@ -1,947 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - ObjectID = require('../../lib/mongodb/bson/objectid').ObjectID, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - GridStore = mongodb.GridStore, - Chunk = mongodb.Chunk, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyFailDueToMissingChunks = function(test) { - var FILE = "empty.test.file"; - client.collection('fs.files', function(err, collection) { - collection.insert({filename: FILE, - "contentType" : "application/json; charset=UTF-8", - "length" : 91, - "chunkSize" : 262144, - "aliases" : null, - "metadata" : {}, - "md5" : "4e638392b289870da9291a242e474930"}, - {safe:true}, function(err, result) { - new mongodb.GridStore(client, FILE, "r").open(function (err, gs) { - gs.read(function(err, data) { - test.ok(err != null); - gs.close(function (){}); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteASmallPayload = function(test) { - var gridStore = new GridStore(client, "test_gs_small_write", "w"); - gridStore.open(function(err, gridStore) { - - gridStore.write("hello world!", function(err, gridStore) { - - gridStore.close(function(err, result) { - - client.collection('fs.files', function(err, collection) { - - collection.find({'filename':'test_gs_small_write'}, function(err, cursor) { - - cursor.toArray(function(err, items) { - test.equal(1, items.length); - var item = items[0]; - test.ok(item._id instanceof ObjectID || Object.prototype.toString.call(item._id) === '[object ObjectID]'); - - client.collection('fs.chunks', function(err, collection) { - var id = ObjectID.createFromHexString(item._id.toHexString()); - - collection.find({'files_id':id}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(1, items.length); - test.done(); - }) - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteSmallFileUsingABuffer = function(test) { - var gridStore = new GridStore(client, "test_gs_small_write_with_buffer", "w"); - gridStore.open(function(err, gridStore) { - var data = new Buffer("hello world", "utf8"); - - gridStore.write(data, function(err, gridStore) { - gridStore.close(function(err, result) { - client.collection('fs.files', function(err, collection) { - collection.find({'filename':'test_gs_small_write_with_buffer'}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(1, items.length); - var item = items[0]; - test.ok(item._id instanceof ObjectID || Object.prototype.toString.call(item._id) === '[object ObjectID]'); - - client.collection('fs.chunks', function(err, collection) { - collection.find({'files_id':item._id}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(1, items.length); - test.done(); - }) - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldSaveSmallFileToGridStore = function(test) { - var gridStore = new GridStore(client, "test_gs_small_file", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - client.collection('fs.files', function(err, collection) { - - collection.find({'filename':'test_gs_small_file'}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(1, items.length); - - // Read test of the file - GridStore.read(client, 'test_gs_small_file', function(err, data) { - test.equal('hello world!', data); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyOverwriteFile = function(test) { - var gridStore = new GridStore(client, "test_gs_overwrite", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - var gridStore2 = new GridStore(client, "test_gs_overwrite", "w"); - gridStore2.open(function(err, gridStore) { - gridStore2.write("overwrite", function(err, gridStore) { - gridStore2.close(function(err, result) { - - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_overwrite', function(err, data) { - test.equal('overwrite', data); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the seek method. - * - * @_class gridstore - * @_function seek - * @ignore - */ -exports.shouldCorrectlySeekWithBuffer = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a file and open it - var gridStore = new GridStore(db, "test_gs_seek_with_buffer", "w"); - gridStore.open(function(err, gridStore) { - // Write some content to the file - gridStore.write(new Buffer("hello, world!", "utf8"), function(err, gridStore) { - // Flush the file to GridFS - gridStore.close(function(result) { - - // Open the file in read mode - var gridStore2 = new GridStore(db, "test_gs_seek_with_buffer", "r"); - gridStore2.open(function(err, gridStore) { - // Seek to start - gridStore.seek(0, function(err, gridStore) { - // Read first character and verify - gridStore.getc(function(err, chr) { - test.equal('h', chr); - }); - }); - }); - - // Open the file in read mode - var gridStore3 = new GridStore(db, "test_gs_seek_with_buffer", "r"); - gridStore3.open(function(err, gridStore) { - // Seek to 7 characters from the beginning off the file and verify - gridStore.seek(7, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - }); - }); - }); - - // Open the file in read mode - var gridStore5 = new GridStore(db, "test_gs_seek_with_buffer", "r"); - gridStore5.open(function(err, gridStore) { - // Seek to -1 characters from the end off the file and verify - gridStore.seek(-1, GridStore.IO_SEEK_END, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('!', chr); - }); - }); - }); - - // Open the file in read mode - var gridStore6 = new GridStore(db, "test_gs_seek_with_buffer", "r"); - gridStore6.open(function(err, gridStore) { - // Seek to -6 characters from the end off the file and verify - gridStore.seek(-6, GridStore.IO_SEEK_END, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - }); - }); - }); - - // Open the file in read mode - var gridStore7 = new GridStore(db, "test_gs_seek_with_buffer", "r"); - gridStore7.open(function(err, gridStore) { - - // Seek forward 7 characters from the current read position and verify - gridStore.seek(7, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - - // Seek forward -1 characters from the current read position and verify - gridStore.seek(-1, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - - // Seek forward -4 characters from the current read position and verify - gridStore.seek(-4, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('o', chr); - - // Seek forward 3 characters from the current read position and verify - gridStore.seek(3, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('o', chr); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySeekWithString = function(test) { - var gridStore = new GridStore(client, "test_gs_seek", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(result) { - var gridStore2 = new GridStore(client, "test_gs_seek", "r"); - gridStore2.open(function(err, gridStore) { - gridStore.seek(0, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('h', chr); - }); - }); - }); - - var gridStore3 = new GridStore(client, "test_gs_seek", "r"); - gridStore3.open(function(err, gridStore) { - gridStore.seek(7, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - }); - }); - }); - - var gridStore4 = new GridStore(client, "test_gs_seek", "r"); - gridStore4.open(function(err, gridStore) { - gridStore.seek(4, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('o', chr); - }); - }); - }); - - var gridStore5 = new GridStore(client, "test_gs_seek", "r"); - gridStore5.open(function(err, gridStore) { - gridStore.seek(-1, GridStore.IO_SEEK_END, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('!', chr); - }); - }); - }); - - var gridStore6 = new GridStore(client, "test_gs_seek", "r"); - gridStore6.open(function(err, gridStore) { - gridStore.seek(-6, GridStore.IO_SEEK_END, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - }); - }); - }); - - var gridStore7 = new GridStore(client, "test_gs_seek", "r"); - gridStore7.open(function(err, gridStore) { - gridStore.seek(7, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - - gridStore.seek(-1, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('w', chr); - - gridStore.seek(-4, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('o', chr); - - gridStore.seek(3, GridStore.IO_SEEK_CUR, function(err, gridStore) { - gridStore.getc(function(err, chr) { - test.equal('o', chr); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyAppendToFile = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - var gridStore = new GridStore(fs_client, "test_gs_append", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(fs_client, "test_gs_append", "w+"); - gridStore2.open(function(err, gridStore) { - gridStore.write(" how are you?", function(err, gridStore) { - gridStore.close(function(err, result) { - - fs_client.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - - GridStore.read(fs_client, 'test_gs_append', function(err, data) { - test.equal("hello, world! how are you?", data); - - fs_client.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing how to rewind and overwrite the file. - * - * @_class gridstore - * @_function rewind - * @ignore - */ -exports.shouldCorrectlyRewingAndTruncateOnWrite = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Create a new file - var gridStore = new GridStore(db, fileId, "w"); - // Open the file - gridStore.open(function(err, gridStore) { - // Write to the file - gridStore.write("hello, world!", function(err, gridStore) { - // Flush the file to disk - gridStore.close(function(err, result) { - - // Reopen the file - gridStore = new GridStore(db, fileId, "w"); - gridStore.open(function(err, gridStore) { - // Write some more text to the file - gridStore.write('some text is inserted here', function(err, gridStore) { - - // Let's rewind to truncate the file - gridStore.rewind(function(err, gridStore) { - - // Write something from the start - gridStore.write('abc', function(err, gridStore) { - - // Flush the data to mongodb - gridStore.close(function(err, result) { - - // Verify that the new data was written - GridStore.read(db, fileId, function(err, data) { - test.equal("abc", data); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveEmptyFile = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - var gridStore = new GridStore(fs_client, "test_gs_save_empty_file", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("", function(err, gridStore) { - gridStore.close(function(err, result) { - fs_client.collection('fs.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - }); - }); - - fs_client.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - - fs_client.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the eof method. - * - * @_class gridstore - * @_function eof - * @ignore - */ -exports.shouldCorrectlyDetectEOF = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Open the file in write mode - var gridStore = new GridStore(db, 'test_gs_empty_file_eof', "w"); - gridStore.open(function(err, gridStore) { - // Flush the empty file to GridFS - gridStore.close(function(err, gridStore) { - - // Open the file in read mode - var gridStore2 = new GridStore(db, 'test_gs_empty_file_eof', "r"); - gridStore2.open(function(err, gridStore) { - // Verify that we are at the end of the file - test.equal(true, gridStore.eof()); - - db.close(); - test.done(); - }) - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldEnsureThatChunkSizeCannotBeChangedDuringRead = function(test) { - var gridStore = new GridStore(client, "test_gs_cannot_change_chunk_size_on_read", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(client, "test_gs_cannot_change_chunk_size_on_read", "r"); - gridStore2.open(function(err, gridStore) { - gridStore.chunkSize = 42; - test.equal(Chunk.DEFAULT_CHUNK_SIZE, gridStore.chunkSize); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldEnsureChunkSizeCannotChangeAfterDataHasBeenWritten = function(test) { - var gridStore = new GridStore(client, "test_gs_cannot_change_chunk_size_after_data_written", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.chunkSize = 42; - test.equal(Chunk.DEFAULT_CHUNK_SIZE, gridStore.chunkSize); - test.done(); - }); - }); -} - -/** - * checks if 8 bit values will be preserved in gridstore - * - * @ignore - */ -exports.shouldCorrectlyStore8bitValues = function(test) { - var gridStore = new GridStore(client, "test_gs_check_high_bits", "w"); - var data = new Buffer(255); - for(var i=0; i<255; i++){ - data[i] = i; - } - - gridStore.open(function(err, gridStore) { - gridStore.write(data, function(err, gridStore) { - gridStore.close(function(err, result) { - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_check_high_bits', function(err, fileData) { - // change testvalue into a string like "0,1,2,...,255" - test.equal(Array.prototype.join.call(data), - Array.prototype.join.call(new Buffer(fileData, "binary"))); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldAllowChangingChunkSize = function(test) { - var gridStore = new GridStore(client, "test_change_chunk_size", "w"); - gridStore.open(function(err, gridStore) { - gridStore.chunkSize = 42 - - gridStore.write('foo', function(err, gridStore) { - gridStore.close(function(err, result) { - var gridStore2 = new GridStore(client, "test_change_chunk_size", "r"); - gridStore2.open(function(err, gridStore) { - test.equal(42, gridStore.chunkSize); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldAllowChangingChunkSizeAtCreationOfGridStore = function(test) { - var gridStore = new GridStore(client, "test_change_chunk_size", "w", {'chunk_size':42}); - gridStore.open(function(err, gridStore) { - gridStore.write('foo', function(err, gridStore) { - gridStore.close(function(err, result) { - var gridStore2 = new GridStore(client, "test_change_chunk_size", "r"); - gridStore2.open(function(err, gridStore) { - test.equal(42, gridStore.chunkSize); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCalculateMD5 = function(test) { - var gridStore = new GridStore(client, "new-file", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(err, result) { - var gridStore2 = new GridStore(client, "new-file", "r"); - gridStore2.open(function(err, gridStore) { - test.equal("6f5902ac237024bdd0c176cb93063dc4", gridStore.md5); - gridStore.md5 = "can't do this"; - test.equal("6f5902ac237024bdd0c176cb93063dc4", gridStore.md5); - - var gridStore2 = new GridStore(client, "new-file", "w"); - gridStore2.open(function(err, gridStore) { - gridStore.close(function(err, result) { - var gridStore3 = new GridStore(client, "new-file", "r"); - gridStore3.open(function(err, gridStore) { - test.equal("d41d8cd98f00b204e9800998ecf8427e", gridStore.md5); - test.done(); - }); - }) - }) - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyUpdateUploadDate = function(test) { - var now = new Date(); - var originalFileUploadDate = null; - - var gridStore = new GridStore(client, "test_gs_upload_date", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(client, "test_gs_upload_date", "r"); - gridStore2.open(function(err, gridStore) { - test.ok(gridStore.uploadDate != null); - originalFileUploadDate = gridStore.uploadDate; - - gridStore2.close(function(err, result) { - var gridStore3 = new GridStore(client, "test_gs_upload_date", "w"); - gridStore3.open(function(err, gridStore) { - gridStore3.write('new data', function(err, gridStore) { - gridStore3.close(function(err, result) { - var fileUploadDate = null; - - var gridStore4 = new GridStore(client, "test_gs_upload_date", "r"); - gridStore4.open(function(err, gridStore) { - test.equal(originalFileUploadDate.getTime(), gridStore.uploadDate.getTime()); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveContentType = function(test) { - var ct = null; - - var gridStore = new GridStore(client, "test_gs_content_type", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(client, "test_gs_content_type", "r"); - gridStore2.open(function(err, gridStore) { - ct = gridStore.contentType; - test.equal(GridStore.DEFAULT_CONTENT_TYPE, ct); - - var gridStore3 = new GridStore(client, "test_gs_content_type", "w+"); - gridStore3.open(function(err, gridStore) { - gridStore.contentType = "text/html"; - gridStore.close(function(err, result) { - var gridStore4 = new GridStore(client, "test_gs_content_type", "r"); - gridStore4.open(function(err, gridStore) { - test.equal("text/html", gridStore.contentType); - test.done(); - }); - }) - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveContentTypeWhenPassedInAtGridStoreCreation = function(test) { - var gridStore = new GridStore(client, "test_gs_content_type_option", "w", {'content_type':'image/jpg'}); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(result) { - - var gridStore2 = new GridStore(client, "test_gs_content_type_option", "r"); - gridStore2.open(function(err, gridStore) { - test.equal('image/jpg', gridStore.contentType); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReportIllegalMode = function(test) { - var gridStore = new GridStore(client, "test_gs_unknown_mode", "x"); - gridStore.open(function(err, gridStore) { - test.ok(err instanceof Error); - test.equal("Illegal mode x", err.message); - test.done(); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveAndRetrieveFileMetadata = function(test) { - var gridStore = new GridStore(client, "test_gs_metadata", "w", {'content_type':'image/jpg'}); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(client, "test_gs_metadata", "r"); - gridStore2.open(function(err, gridStore) { - test.equal(null, gridStore.metadata); - - var gridStore3 = new GridStore(client, "test_gs_metadata", "w+"); - gridStore3.open(function(err, gridStore) { - gridStore.metadata = {'a':1}; - gridStore.close(function(err, result) { - - var gridStore4 = new GridStore(client, "test_gs_metadata", "r"); - gridStore4.open(function(err, gridStore) { - test.equal(1, gridStore.metadata.a); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldNotThrowErrorOnClose = function(test) { - var gridStore = new GridStore(client, "test_gs_metadata", "w", {'content_type':'image/jpg'}); - gridStore.open(function(err, gridStore) { - gridStore.write('hello world\n', function(err, gridStore) { - gridStore.close(function(err, result) { - - var gridStore2 = new GridStore(client, "test_gs_metadata", "r"); - gridStore2.open(function(err, gridStore) { - gridStore.close(function(err, fo) { - test.ok(err == null); - test.ok(fo == null); - test.done(); - }) - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the tell method. - * - * @_class gridstore - * @_function tell - * @ignore - */ -exports.shouldCorrectlyExecuteGridstoreTell = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new file - var gridStore = new GridStore(db, "test_gs_tell", "w"); - // Open the file - gridStore.open(function(err, gridStore) { - // Write a string to the file - gridStore.write("hello, world!", function(err, gridStore) { - // Flush the file to GridFS - gridStore.close(function(err, result) { - - // Open the file in read only mode - var gridStore2 = new GridStore(db, "test_gs_tell", "r"); - gridStore2.open(function(err, gridStore) { - - // Read the first 5 characters - gridStore.read(5, function(err, data) { - test.equal("hello", data); - - // Get the current position of the read head - gridStore.tell(function(err, position) { - test.equal(5, position); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the seek method. - * - * @_class gridstore - * @_function getc - * @ignore - */ -exports.shouldCorrectlyRetrieveSingleCharacterUsingGetC = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a file and open it - var gridStore = new GridStore(db, "test_gs_getc_file", "w"); - gridStore.open(function(err, gridStore) { - // Write some content to the file - gridStore.write(new Buffer("hello, world!", "utf8"), function(err, gridStore) { - // Flush the file to GridFS - gridStore.close(function(result) { - - // Open the file in read mode - var gridStore2 = new GridStore(db, "test_gs_getc_file", "r"); - gridStore2.open(function(err, gridStore) { - - // Read first character and verify - gridStore.getc(function(err, chr) { - test.equal('h', chr); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/gridstore/grid_store_stream_test.js b/node_modules/reg/node_modules/mongodb/test/gridstore/grid_store_stream_test.js deleted file mode 100644 index d7eaec7..0000000 --- a/node_modules/reg/node_modules/mongodb/test/gridstore/grid_store_stream_test.js +++ /dev/null @@ -1,310 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - fs = require('fs'), - ObjectID = require('../../lib/mongodb/bson/objectid').ObjectID, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - GridStore = mongodb.GridStore, - Chunk = mongodb.Chunk, - Step = require("../../deps/step/lib/step"), - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteLargeFileStringAndReadBack = function(test) { - var db = client; - var fileId = new ObjectID(); - var gridStore = new GridStore(db, fileId, "w", {root:'fs'}); - gridStore.chunkSize = 5000; - - gridStore.open(function(err, gridStore) { - Step( - function writeData() { - var group = this.group(); - var d = ''; - for(var j = 0; j < 5000;j++) { - d = d + '+'; - } - - for(var i = 0; i < 15000; i += 5000) { - gridStore.write(d, false, group()); - } - }, - - function readAsStream() { - gridStore.close(function(err, result) { - var gotEnd = false; - var endLen = 0; - - var gridStore = new GridStore(db, fileId, "r"); - gridStore.open(function(err, gridStore) { - var stream = gridStore.stream(true); - - stream.on("data", function(chunk) { - endLen += chunk.length - // Test length of chunk - test.equal(5000, chunk.length); - // Check each chunk's data - for(var i = 0; i < 5000; i++) test.equal('+', String.fromCharCode(chunk[i])); - }); - - stream.on("end", function() { - gotEnd = true; - }); - - stream.on("close", function() { - test.equal(15000, endLen); - test.equal(true, gotEnd); - test.done(); - }); - }); - }); - } - ) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteLargeFileBufferAndReadBack = function(test) { - var db = client; - var fileId = new ObjectID(); - var gridStore = new GridStore(db, fileId, "w", {root:'fs'}); - gridStore.chunkSize = 5000; - - gridStore.open(function(err, gridStore) { - Step( - function writeData() { - var group = this.group(); - var d = new Buffer(5000); - for(var j = 0; j < 5000;j++) { - d[j] = 43; - } - - for(var i = 0; i < 15000; i += 5000) { - gridStore.write(d, false, group()); - } - }, - - function readAsStream() { - gridStore.close(function(err, result) { - var gotEnd = false; - var endLen = 0; - - var gridStore = new GridStore(db, fileId, "r"); - gridStore.open(function(err, gridStore) { - var stream = gridStore.stream(true); - - stream.on("data", function(chunk) { - endLen += chunk.length - // Test length of chunk - test.equal(5000, chunk.length); - // Check each chunk's data - for(var i = 0; i < 5000; i++) test.equal('+', String.fromCharCode(chunk[i])); - }); - - stream.on("end", function() { - gotEnd = true; - }); - - stream.on("close", function() { - test.equal(15000, endLen); - test.equal(true, gotEnd); - test.done(); - }); - }); - }); - } - ) - }); -} - -/** - * A simple example showing the usage of the stream method. - * - * @_class gridstore - * @_function stream - * @ignore - */ -exports.shouldCorrectlyReadFileUsingStream = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Open a file for reading - var gridStoreR = new GridStore(db, "test_gs_read_stream", "r"); - // Open a file for writing - var gridStoreW = new GridStore(db, "test_gs_read_stream", "w"); - // Read in the data of a file - var data = fs.readFileSync("./test/gridstore/test_gs_weird_bug.png"); - - var readLen = 0; - var gotEnd = 0; - - // Open the file we are writting to - gridStoreW.open(function(err, gs) { - // Write the file content - gs.write(data, function(err, gs) { - // Flush the file to GridFS - gs.close(function(err, result) { - - // Open the read file - gridStoreR.open(function(err, gs) { - - // Create a stream to the file - var stream = gs.stream(true); - - // Register events - stream.on("data", function(chunk) { - // Record the length of the file - readLen += chunk.length; - }); - - stream.on("end", function() { - // Record the end was called - ++gotEnd; - }); - - stream.on("close", function() { - // Verify the correctness of the read data - test.equal(data.length, readLen); - test.equal(1, gotEnd); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should return same data for streaming as for direct read'] = function(test) { - var gridStoreR = new GridStore(client, "test_gs_read_stream", "r"); - var gridStoreW = new GridStore(client, "test_gs_read_stream", "w", {chunkSize:56}); - // var data = fs.readFileSync("./test/gridstore/test_gs_weird_bug.png"); - var data = new Buffer(100); - for(var i = 0; i < 100; i++) { - data[i] = i; - } - - var readLen = 0; - var gotEnd = 0; - - gridStoreW.open(function(err, gs) { - gs.write(data, function(err, gs) { - gs.close(function(err, result) { - gridStoreR.open(function(err, gs) { - var chunks = []; - - var stream = gs.stream(true); - stream.on("data", function(chunk) { - readLen += chunk.length; - chunks.push(chunk); - }); - stream.on("end", function() { - ++gotEnd; - }); - stream.on("close", function() { - test.equal(data.length, readLen); - test.equal(1, gotEnd); - - // Read entire file in one go and compare - var gridStoreRead = new GridStore(client, "test_gs_read_stream", "r"); - gridStoreRead.open(function(err, gs) { - gridStoreRead.read(function(err, data2) { - // Put together all the chunks - var streamData = new Buffer(data.length); - var index = 0; - for(var i = 0; i < chunks.length; i++) { - chunks[i].copy(streamData, index, 0); - index = index + chunks[i].length; - } - - // Compare data - for(var i = 0; i < data.length; i++) { - test.equal(data2[i], data[i]) - test.equal(streamData[i], data[i]) - } - - test.done(); - }) - }) - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/gridstore/grid_store_test.js b/node_modules/reg/node_modules/mongodb/test/gridstore/grid_store_test.js deleted file mode 100644 index c32ef2e..0000000 --- a/node_modules/reg/node_modules/mongodb/test/gridstore/grid_store_test.js +++ /dev/null @@ -1,1351 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - fs = require('fs'), - ObjectID = require('../../lib/mongodb/bson/objectid').ObjectID, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - GridStore = mongodb.GridStore, - Chunk = mongodb.Chunk, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -// var MONGODB = 'ruby-test-db'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple example showing the usage of the Gridstore.exist method. - * - * @_class gridstore - * @_function GridStore.exist - * @ignore - */ -exports.shouldCorrectlyExecuteGridStoreExistsByObjectId = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Open a file for writing - var gridStore = new GridStore(db, null, "w"); - gridStore.open(function(err, gridStore) { - - // Writing some content to the file - gridStore.write("hello world!", function(err, gridStore) { - - // Flush the file to GridFS - gridStore.close(function(err, result) { - - // Check if the file exists using the id returned from the close function - GridStore.exist(db, result._id, function(err, result) { - test.equal(true, result); - }) - - // Show that the file does not exist for a random ObjectID - GridStore.exist(db, new ObjectID(), function(err, result) { - test.equal(false, result); - }); - - // Show that the file does not exist for a different file root - GridStore.exist(db, result._id, 'another_root', function(err, result) { - test.equal(false, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySafeFileAndReadFileByObjectId = function(test) { - var gridStore = new GridStore(client, null, "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - - // Let's read the file using object Id - GridStore.read(client, result._id, function(err, data) { - test.equal('hello world!', data); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteGridStoreExists = function(test) { - var gridStore = new GridStore(client, "foobar", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - GridStore.exist(client, 'foobar', function(err, result) { - test.equal(true, result); - }); - - GridStore.exist(client, 'does_not_exist', function(err, result) { - test.equal(false, result); - }); - - GridStore.exist(client, 'foobar', 'another_root', function(err, result) { - test.equal(false, result); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the eof method. - * - * @_class gridstore - * @_function GridStore.list - * @ignore - */ -exports.shouldCorrectlyExecuteGridStoreList = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Open a file for writing - var gridStore = new GridStore(db, "foobar2", "w"); - gridStore.open(function(err, gridStore) { - - // Write some content to the file - gridStore.write("hello world!", function(err, gridStore) { - // Flush to GridFS - gridStore.close(function(err, result) { - - // List the existing files - GridStore.list(db, function(err, items) { - var found = false; - items.forEach(function(filename) { - if(filename == 'foobar2') found = true; - }); - - test.ok(items.length >= 1); - test.ok(found); - }); - - // List the existing files but return only the file ids - GridStore.list(db, {id:true}, function(err, items) { - var found = false; - items.forEach(function(id) { - test.ok(typeof id == 'object'); - }); - - test.ok(items.length >= 1); - }); - - // List the existing files in a specific root collection - GridStore.list(db, 'fs', function(err, items) { - var found = false; - items.forEach(function(filename) { - if(filename == 'foobar2') found = true; - }); - - test.ok(items.length >= 1); - test.ok(found); - }); - - // List the existing files in a different root collection where the file is not located - GridStore.list(client, 'my_fs', function(err, items) { - var found = false; - items.forEach(function(filename) { - if(filename == 'foobar2') found = true; - }); - - test.ok(items.length >= 0); - test.ok(!found); - - // Write another file to GridFS - var gridStore2 = new GridStore(db, "foobar3", "w"); - gridStore2.open(function(err, gridStore) { - // Write the content - gridStore2.write('my file', function(err, gridStore) { - // Flush to GridFS - gridStore.close(function(err, result) { - - // List all the available files and verify that our files are there - GridStore.list(db, function(err, items) { - var found = false; - var found2 = false; - - items.forEach(function(filename) { - if(filename == 'foobar2') found = true; - if(filename == 'foobar3') found2 = true; - }); - - test.ok(items.length >= 2); - test.ok(found); - test.ok(found2); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPeformGridStoreReadLength = function(test) { - var gridStore = new GridStore(client, "test_gs_read_length", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello world!", function(err, gridStore) { - gridStore.close(function(err, result) { - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_read_length', 5, function(err, data) { - test.equal('hello', data); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadFromFileWithOffset = function(test) { - var gridStore = new GridStore(client, "test_gs_read_with_offset", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(err, result) { - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_read_with_offset', 5, 7, function(err, data) { - test.equal('world', data); - }); - - GridStore.read(client, 'test_gs_read_with_offset', null, 7, function(err, data) { - test.equal('world!', data); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleMultipleChunkGridStore = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - var gridStore = new GridStore(fs_client, "test_gs_multi_chunk", "w"); - gridStore.open(function(err, gridStore) { - gridStore.chunkSize = 512; - var file1 = ''; var file2 = ''; var file3 = ''; - for(var i = 0; i < gridStore.chunkSize; i++) { file1 = file1 + 'x'; } - for(var i = 0; i < gridStore.chunkSize; i++) { file2 = file2 + 'y'; } - for(var i = 0; i < gridStore.chunkSize; i++) { file3 = file3 + 'z'; } - - gridStore.write(file1, function(err, gridStore) { - gridStore.write(file2, function(err, gridStore) { - gridStore.write(file3, function(err, gridStore) { - gridStore.close(function(err, result) { - fs_client.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(3, count); - - GridStore.read(fs_client, 'test_gs_multi_chunk', function(err, data) { - test.equal(512*3, data.length); - fs_client.close(); - - test.done(); - }); - }) - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the puts method. - * - * @_class gridstore - * @_function puts - * @ignore - */ -exports.shouldCorrectlyReadlinesAndPutLines = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Open a file for writing - var gridStore = new GridStore(db, "test_gs_puts_and_readlines", "w"); - gridStore.open(function(err, gridStore) { - - // Write a line to the file using the puts method - gridStore.puts("line one", function(err, gridStore) { - - // Flush the file to GridFS - gridStore.close(function(err, result) { - - // Read in the entire contents - GridStore.read(db, 'test_gs_puts_and_readlines', function(err, data) { - test.equal("line one\n", data.toString()); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleUnlinkingWeirdName = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - var gridStore = new GridStore(fs_client, "9476700.937375426_1271170118964-clipped.png", "w", {'root':'articles'}); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(err, result) { - fs_client.collection('articles.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - }) - }); - - fs_client.collection('articles.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - - // Unlink the file - GridStore.unlink(fs_client, '9476700.937375426_1271170118964-clipped.png', {'root':'articles'}, function(err, gridStore) { - fs_client.collection('articles.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - }) - }); - - fs_client.collection('articles.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - - fs_client.close(); - test.done(); - }) - }); - }); - }) - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the GridStore.unlink method. - * - * @_class gridstore - * @_function GridStore.unlink - * @ignore - */ -exports.shouldCorrectlyUnlink = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Open a new file for writing - var gridStore = new GridStore(db, "test_gs_unlink", "w"); - gridStore.open(function(err, gridStore) { - - // Write some content - gridStore.write("hello, world!", function(err, gridStore) { - - // Flush file to GridFS - gridStore.close(function(err, result) { - - // Verify the existance of the fs.files document - db.collection('fs.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - }) - }); - - // Verify the existance of the fs.chunks chunk document - db.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - - // Unlink the file (removing it) - GridStore.unlink(db, 'test_gs_unlink', function(err, gridStore) { - - // Verify that fs.files document is gone - db.collection('fs.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - }) - }); - - // Verify that fs.chunks chunk documents are gone - db.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - - db.close(); - test.done(); - }) - }); - }); - }) - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyUnlinkAnArrayOfFiles = function(test) { - var fs_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - fs_client.open(function(err, fs_client) { - fs_client.dropDatabase(function(err, done) { - var gridStore = new GridStore(fs_client, "test_gs_unlink_as_array", "w"); - gridStore.open(function(err, gridStore) { - gridStore.write("hello, world!", function(err, gridStore) { - gridStore.close(function(err, result) { - fs_client.collection('fs.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - }) - }); - - fs_client.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(1, count); - - // Unlink the file - GridStore.unlink(fs_client, ['test_gs_unlink_as_array'], function(err, gridStore) { - fs_client.collection('fs.files', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - }) - }); - - fs_client.collection('fs.chunks', function(err, collection) { - collection.count(function(err, count) { - test.equal(0, count); - fs_client.close(); - - test.done(); - }) - }); - }); - }) - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteFileToGridStore= function(test) { - var gridStore = new GridStore(client, 'test_gs_writing_file', 'w'); - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - gridStore.writeFile('./test/gridstore/test_gs_weird_bug.png', function(err, doc) { - GridStore.read(client, 'test_gs_writing_file', function(err, fileData) { - test.equal(data.toString('hex'), fileData.toString('hex')); - test.equal(fileSize, fileData.length); - - // Ensure we have a md5 - var gridStore2 = new GridStore(client, 'test_gs_writing_file', 'r'); - gridStore2.open(function(err, gridStore2) { - test.ok(gridStore2.md5 != null) - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyWriteFileToGridStoreUsingObjectId= function(test) { - var gridStore = new GridStore(client, null, 'w'); - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - gridStore.writeFile('./test/gridstore/test_gs_weird_bug.png', function(err, doc) { - - GridStore.read(client, doc._id, function(err, fileData) { - test.equal(data.toString('hex'), fileData.toString('hex')); - test.equal(fileSize, fileData.length); - - // Ensure we have a md5 - var gridStore2 = new GridStore(client, doc._id, 'r'); - gridStore2.open(function(err, gridStore2) { - test.ok(gridStore2.md5 != null) - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformWorkingFiledRead = function(test) { - var gridStore = new GridStore(client, "test_gs_working_field_read", "w"); - var data = fs.readFileSync("./test/gridstore/test_gs_working_field_read.pdf", 'binary'); - - gridStore.open(function(err, gridStore) { - gridStore.write(data, function(err, gridStore) { - gridStore.close(function(err, result) { - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_working_field_read', function(err, fileData) { - test.equal(data.length, fileData.length); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadAndWriteFile = function(test) { - var gridStore = new GridStore(client, "test_gs_weird_bug", "w"); - var data = fs.readFileSync("./test/gridstore/test_gs_weird_bug.png", 'binary'); - - gridStore.open(function(err, gridStore) { - gridStore.write(data, function(err, gridStore) { - gridStore.close(function(err, result) { - // Assert that we have overwriten the data - GridStore.read(client, 'test_gs_weird_bug', function(err, fileData) { - test.equal(data.length, fileData.length); - test.done(); - }); - }); - }); - }); -} - - -/** - * A simple example showing the usage of the read method. - * - * @_class gridstore - * @_function read - * @ignore - */ -exports.shouldCorrectlyWriteAndReadJpgImage = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Read in the content of a file - var data = fs.readFileSync('./test/gridstore/iya_logo_final_bw.jpg'); - // Create a new file - var gs = new GridStore(db, "test", "w"); - // Open the file - gs.open(function(err, gs) { - // Write the file to GridFS - gs.write(data, function(err, gs) { - // Flush to the GridFS - gs.close(function(err, gs) { - - // Define the file we wish to read - var gs2 = new GridStore(db, "test", "r"); - // Open the file - gs2.open(function(err, gs) { - // Set the pointer of the read head to the start of the gridstored file - gs2.seek(0, function() { - // Read the entire file - gs2.read(function(err, data2) { - // Compare the file content against the orgiinal - test.equal(data.toString('hex'), data2.toString('hex')); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadAndWriteBuffersMultipleChunks = function(test) { - var gridStore = new GridStore(client, null, 'w'); - // Force multiple chunks to be stored - gridStore.chunkSize = 5000; - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - - // Write the file using write - gridStore.write(data, function(err, doc) { - gridStore.close(function(err, doc) { - - // Read the file using readBuffer - new GridStore(client, doc._id, 'r').open(function(err, gridStore) { - gridStore.read(function(err, data2) { - test.equal(data.toString('base64'), data2.toString('base64')); - test.done(); - }) - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadAndWriteBuffersSingleChunks = function(test) { - var gridStore = new GridStore(client, null, 'w'); - // Force multiple chunks to be stored - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - - // Write the file using writeBuffer - gridStore.write(data, function(err, doc) { - gridStore.close(function(err, doc) { - - // Read the file using readBuffer - new GridStore(client, doc._id, 'r').open(function(err, gridStore) { - gridStore.read(function(err, data2) { - test.equal(data.toString('base64'), data2.toString('base64')); - test.done(); - }) - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadAndWriteBuffersUsingNormalWriteWithMultipleChunks = function(test) { - var gridStore = new GridStore(client, null, 'w'); - // Force multiple chunks to be stored - gridStore.chunkSize = 5000; - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - - // Write the buffer using the .write method that should use writeBuffer correctly - gridStore.write(data, function(err, doc) { - gridStore.close(function(err, doc) { - - // Read the file using readBuffer - new GridStore(client, doc._id, 'r').open(function(err, gridStore) { - gridStore.read(function(err, data2) { - test.equal(data.toString('base64'), data2.toString('base64')); - test.done(); - }) - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyReadAndWriteBuffersSingleChunksAndVerifyExistance = function(test) { - var gridStore = new GridStore(client, null, 'w'); - // Force multiple chunks to be stored - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - gridStore.open(function(err, gridStore) { - - // Write the file using writeBuffer - gridStore.write(data, function(err, doc) { - gridStore.close(function(err, doc) { - - // Read the file using readBuffer - GridStore.exist(client, doc._id, function(err, result) { - test.equal(null, err); - test.equal(true, result); - - client.close(); - test.done(); - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySaveDataByObjectID = function(test) { - var id = new ObjectID(); - var gridStore = new GridStore(client, id, 'w'); - - gridStore.open(function(err, gridStore) { - gridStore.write('bar', function(err, gridStore) { - gridStore.close(function(err, result) { - - GridStore.exist(client, id, function(err, result) { - test.equal(null, err); - test.equal(true, result); - - client.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCheckExistsByUsingRegexp = function(test) { - var gridStore = new GridStore(client, 'shouldCheckExistsByUsingRegexp.txt', 'w'); - - gridStore.open(function(err, gridStore) { - gridStore.write('bar', function(err, gridStore) { - gridStore.close(function(err, result) { - - GridStore.exist(client, /shouldCheck/, function(err, result) { - test.equal(null, err); - test.equal(true, result); - - client.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing opening a file using a filename, writing to it and saving it. - * - * @_class gridstore - * @_function open - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingFilename = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new instance of the gridstore - var gridStore = new GridStore(db, 'ourexamplefiletowrite.txt', 'w'); - - // Open the file - gridStore.open(function(err, gridStore) { - - // Write some data to the file - gridStore.write('bar', function(err, gridStore) { - test.equal(null, err); - - // Close (Flushes the data to MongoDB) - gridStore.close(function(err, result) { - test.equal(null, err); - - // Verify that the file exists - GridStore.exist(db, 'ourexamplefiletowrite.txt', function(err, result) { - test.equal(null, err); - test.equal(true, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing opening a file using an ObjectID, writing to it and saving it. - * - * @_class gridstore - * @_function open - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingObjectID = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Create a new instance of the gridstore - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the file - gridStore.open(function(err, gridStore) { - - // Write some data to the file - gridStore.write('bar', function(err, gridStore) { - test.equal(null, err); - - // Close (Flushes the data to MongoDB) - gridStore.close(function(err, result) { - test.equal(null, err); - - // Verify that the file exists - GridStore.exist(db, fileId, function(err, result) { - test.equal(null, err); - test.equal(true, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing how to write a file to Gridstore using file location path. - * - * @_class gridstore - * @_function writeFile - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingWriteFile = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Read the filesize of file on disk (provide your own) - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - // Read the buffered data for comparision reasons - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write the file to gridFS - gridStore.writeFile('./test/gridstore/test_gs_weird_bug.png', function(err, doc) { - - // Read back all the written content and verify the correctness - GridStore.read(db, fileId, function(err, fileData) { - test.equal(data.toString('hex'), fileData.toString('hex')) - test.equal(fileSize, fileData.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing how to write a file to Gridstore using a file handle. - * - * @_class gridstore - * @_function writeFile - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingWriteFileWithHandle = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Read the filesize of file on disk (provide your own) - var fileSize = fs.statSync('./test/gridstore/test_gs_weird_bug.png').size; - // Read the buffered data for comparision reasons - var data = fs.readFileSync('./test/gridstore/test_gs_weird_bug.png'); - - // Open a file handle for reading the file - var fd = fs.openSync('./test/gridstore/test_gs_weird_bug.png', 'r', 0666); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write the file to gridFS using the file handle - gridStore.writeFile(fd, function(err, doc) { - - // Read back all the written content and verify the correctness - GridStore.read(db, fileId, function(err, fileData) { - test.equal(data.toString('hex'), fileData.toString('hex')); - test.equal(fileSize, fileData.length); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing how to use the write command with strings and Buffers. - * - * @_class gridstore - * @_function write - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingWriteWithStringsAndBuffers = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write a text string - gridStore.write('Hello world', function(err, gridStore) { - - // Write a buffer - gridStore.write(new Buffer('Buffer Hello world'), function(err, gridStore) { - - // Close the - gridStore.close(function(err, result) { - - // Read back all the written content and verify the correctness - GridStore.read(db, fileId, function(err, fileData) { - test.equal('Hello worldBuffer Hello world', fileData.toString()); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing how to use the write command with strings and Buffers. - * - * @_class gridstore - * @_function close - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingClose = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write a text string - gridStore.write('Hello world', function(err, gridStore) { - - // Close the - gridStore.close(function(err, result) { - test.equal(err, null); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * A simple example showing how to access the chunks collection object. - * - * @_class gridstore - * @_function chunkCollection - * @ignore - */ -exports.shouldCorrectlyAccessChunkCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Access the Chunk collection - gridStore.chunkCollection(function(err, collection) { - test.equal(err, null); - test.ok(collection instanceof Collection); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * A simple example showing how to use the instance level unlink command to delete a gridstore item. - * - * @_class gridstore - * @_function unlink - * @ignore - */ -exports.shouldCorrectlySaveSimpleFileToGridStoreUsingCloseAndThenUnlinkIt = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write a text string - gridStore.write('Hello world', function(err, gridStore) { - - // Close the - gridStore.close(function(err, result) { - test.equal(err, null); - - // Open the file again and unlin it - new GridStore(db, fileId, 'r').open(function(err, gridStore) { - - // Unlink the file - gridStore.unlink(function(err, result) { - test.equal(null, err); - - // Verify that the file no longer exists - GridStore.exist(db, fileId, function(err, result) { - test.equal(null, err); - test.equal(false, result); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing how to access the files collection object. - * - * @_class gridstore - * @_function collection - * @ignore - */ -exports.shouldCorrectlyAccessFilesCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Access the Chunk collection - gridStore.collection(function(err, collection) { - test.equal(err, null); - test.ok(collection instanceof Collection); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * A simple example showing reading back using readlines to split the text into lines by the seperator provided. - * - * @_class gridstore - * @_function GridStore.readlines - * @ignore - */ -exports.shouldCorrectlyPutACoupleOfLinesInGridStoreAndUseReadlines = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write one line to gridStore - gridStore.puts("line one", function(err, gridStore) { - - // Write second line to gridStore - gridStore.puts("line two", function(err, gridStore) { - - // Write third line to gridStore - gridStore.puts("line three", function(err, gridStore) { - - // Flush file to disk - gridStore.close(function(err, result) { - - // Read back all the lines - GridStore.readlines(db, fileId, function(err, lines) { - test.deepEqual(["line one\n", "line two\n", "line three\n"], lines); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing reading back using readlines to split the text into lines by the seperator provided. - * - * @_class gridstore - * @_function readlines - * @ignore - */ -exports.shouldCorrectlyPutACoupleOfLinesInGridStoreAndUseInstanceReadlines = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Our file ID - var fileId = new ObjectID(); - - // Open a new file - var gridStore = new GridStore(db, fileId, 'w'); - - // Open the new file - gridStore.open(function(err, gridStore) { - - // Write one line to gridStore - gridStore.puts("line one", function(err, gridStore) { - - // Write second line to gridStore - gridStore.puts("line two", function(err, gridStore) { - - // Write third line to gridStore - gridStore.puts("line three", function(err, gridStore) { - - // Flush file to disk - gridStore.close(function(err, result) { - - // Open file for reading - gridStore = new GridStore(db, fileId, 'r'); - gridStore.open(function(err, gridStore) { - - // Read all the lines and verify correctness - gridStore.readlines(function(err, lines) { - test.deepEqual(["line one\n", "line two\n", "line three\n"], lines); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the usage of the read method. - * - * @_class gridstore - * @_function GridStore.read - * @ignore - */ -exports.shouldCorrectlyPutACoupleOfLinesInGridStoreRead = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new file - var gridStore = new GridStore(db, null, "w"); - // Read in the content from a file, replace with your own - var data = fs.readFileSync("./test/gridstore/test_gs_weird_bug.png"); - - // Open the file - gridStore.open(function(err, gridStore) { - // Write the binary file data to GridFS - gridStore.write(data, function(err, gridStore) { - // Flush the remaining data to GridFS - gridStore.close(function(err, result) { - - // Read in the whole file and check that it's the same content - GridStore.read(client, result._id, function(err, fileData) { - test.equal(data.length, fileData.length); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/gridstore/grid_test.js b/node_modules/reg/node_modules/mongodb/test/gridstore/grid_test.js deleted file mode 100644 index 7c0edb1..0000000 --- a/node_modules/reg/node_modules/mongodb/test/gridstore/grid_test.js +++ /dev/null @@ -1,189 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../../lib/mongodb').native() : require('../../lib/mongodb').pure(); - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - GridStore = mongodb.GridStore, - Grid = mongodb.Grid, - Chunk = mongodb.Chunk, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple example showing the usage of the put method. - * - * @_class grid - * @_function put - * @ignore - */ -exports.shouldPutFileCorrectlyToGridUsingObjectId = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new grid instance - var grid = new Grid(db, 'fs'); - // Some data to write - var originalData = new Buffer('Hello world'); - // Write data to grid - grid.put(originalData, {}, function(err, result) { - // Fetch the content - grid.get(result._id, function(err, data) { - test.deepEqual(originalData.toString('hex'), data.toString('hex')); - - db.close(); - test.done(); - }); - }); - }); -} - -/** - * A simple example showing the usage of the get method. - * - * @_class grid - * @_function get - * @ignore - */ -exports.shouldPutAndGetFileCorrectlyToGridUsingObjectId = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new grid instance - var grid = new Grid(db, 'fs'); - // Some data to write - var originalData = new Buffer('Hello world'); - // Write data to grid - grid.put(originalData, {}, function(err, result) { - // Fetch the content - grid.get(result._id, function(err, data) { - test.deepEqual(originalData.toString('base64'), data.toString('base64')); - - // Should fail due to illegal objectID - grid.get('not an id', function(err, result) { - test.ok(err != null); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldFailToPutFileDueToDataObjectNotBeingBuffer = function(test) { - var grid = new Grid(client, 'fs'); - var originalData = 'Hello world'; - // Write data to grid - grid.put(originalData, {}, function(err, result) { - test.ok(err != null); - test.done(); - }) -} - -/** - * A simple example showing the usage of the delete method. - * - * @_class grid - * @_function delete - * @ignore - */ -exports.shouldCorrectlyWriteFileAndThenDeleteIt = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // Create a new grid instance - var grid = new Grid(client, 'fs'); - // Some data to write - var originalData = new Buffer('Hello world'); - // Write data to grid - grid.put(originalData, {}, function(err, result) { - - // Delete file - grid.delete(result._id, function(err, result2) { - test.equal(null, err); - test.equal(true, result2); - - // Fetch the content, showing that the file is gone - grid.get(result._id, function(err, data) { - test.ok(err != null); - test.equal(null, data); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/gridstore/iya_logo_final_bw.jpg b/node_modules/reg/node_modules/mongodb/test/gridstore/iya_logo_final_bw.jpg deleted file mode 100644 index 0f07b9e..0000000 Binary files a/node_modules/reg/node_modules/mongodb/test/gridstore/iya_logo_final_bw.jpg and /dev/null differ diff --git a/node_modules/reg/node_modules/mongodb/test/gridstore/readstream_test.js b/node_modules/reg/node_modules/mongodb/test/gridstore/readstream_test.js deleted file mode 100644 index ef0d869..0000000 --- a/node_modules/reg/node_modules/mongodb/test/gridstore/readstream_test.js +++ /dev/null @@ -1,239 +0,0 @@ -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../../deps/nodeunit'), - gleak = require('../../dev/tools/gleak'), - Db = require('../../lib/mongodb').Db, - ObjectID = require('../../lib/mongodb').ObjectID, - Cursor = require('../../lib/mongodb').Cursor, - Step = require("../../deps/step/lib/step"), - Collection = require('../../lib/mongodb').Collection, - GridStore = require('../../lib/mongodb').GridStore, - fs = require('fs'), - Server = require('../../lib/mongodb').Server; - -var MONGODB = 'integration_tests'; -var useSSL = process.env['USE_SSL'] != null ? true : false; -var client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple example showing the use of the readstream pause function. - * - * @_class readstream - * @_function pause - * @ignore - */ -exports.shouldStreamDocumentsUsingTheReadStreamPauseFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // File id - var fileId = new ObjectID(); - // Create a file - var file = new GridStore(db, fileId, "w"); - file.open(function(err, file) { - // Write some content and flush to disk - file.write('Hello world', function(err, file) { - file.close(function(err, result) { - - // Let's create a read file - file = new GridStore(db, fileId, "r"); - // Open the file - file.open(function(err, file) { - // Peform a find to get a cursor - var stream = file.stream(); - - // For each data item - stream.on("data", function(item) { - // Check if stream is paused - test.equal(false, stream.paused); - // Pause stream - stream.pause(); - // Check if cursor is paused - test.equal(true, stream.paused); - - // Restart the stream after 1 miliscecond - setTimeout(function() { - stream.resume(); - // Check if cursor is paused - test.equal(false, stream.paused); - }, 1); - }); - - // For each data item - stream.on("end", function(item) {}); - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the readstream resume function. - * - * @_class readstream - * @_function resume - * @ignore - */ -exports.shouldStreamDocumentsUsingTheReadStreamResumeFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // File id - var fileId = new ObjectID(); - // Create a file - var file = new GridStore(db, fileId, "w"); - file.open(function(err, file) { - // Write some content and flush to disk - file.write('Hello world', function(err, file) { - file.close(function(err, result) { - - // Let's create a read file - file = new GridStore(db, fileId, "r"); - // Open the file - file.open(function(err, file) { - // Peform a find to get a cursor - var stream = file.stream(); - - // For each data item - stream.on("data", function(item) { - // Check if stream is paused - test.equal(false, stream.paused); - // Pause stream - stream.pause(); - // Check if cursor is paused - test.equal(true, stream.paused); - - // Restart the stream after 1 miliscecond - setTimeout(function() { - stream.resume(); - // Check if cursor is paused - test.equal(false, stream.paused); - }, 1); - }); - - // For each data item - stream.on("end", function(item) {}); - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple example showing the use of the readstream destroy function. - * - * @_class readstream - * @_function destroy - * @ignore - */ -exports.shouldStreamDocumentsUsingTheReadStreamDestroyFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 1, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - // File id - var fileId = new ObjectID(); - // Create a file - var file = new GridStore(db, fileId, "w"); - file.open(function(err, file) { - // Write some content and flush to disk - file.write('Hello world', function(err, file) { - file.close(function(err, result) { - - // Let's create a read file - file = new GridStore(db, fileId, "r"); - // Open the file - file.open(function(err, file) { - // Peform a find to get a cursor - var stream = file.stream(); - - // For each data item - stream.on("data", function(item) { - // Destroy the stream - stream.destroy(); - }); - - // When the stream is done - stream.on("close", function() { - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/gridstore/test_gs_weird_bug.png b/node_modules/reg/node_modules/mongodb/test/gridstore/test_gs_weird_bug.png deleted file mode 100644 index 1554dc3..0000000 Binary files a/node_modules/reg/node_modules/mongodb/test/gridstore/test_gs_weird_bug.png and /dev/null differ diff --git a/node_modules/reg/node_modules/mongodb/test/gridstore/test_gs_working_field_read.pdf b/node_modules/reg/node_modules/mongodb/test/gridstore/test_gs_working_field_read.pdf deleted file mode 100644 index 4b1247a..0000000 Binary files a/node_modules/reg/node_modules/mongodb/test/gridstore/test_gs_working_field_read.pdf and /dev/null differ diff --git a/node_modules/reg/node_modules/mongodb/test/index_test.js b/node_modules/reg/node_modules/mongodb/test/index_test.js deleted file mode 100644 index 5c43cdb..0000000 --- a/node_modules/reg/node_modules/mongodb/test/index_test.js +++ /dev/null @@ -1,699 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple createIndex using a simple single field index - * - * @_class collection - * @_function createIndex - */ -exports.shouldCreateASimpleIndexOnASingleField = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('simple_index_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1}, {a:2}, {a:3}, {a:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.createIndex('a', function(err, indexName) { - test.equal("a_1", indexName); - - // Peform a query, with explain to show we hit the query - collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { - test.deepEqual([[2, 2]], explanation[0].indexBounds.a); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * A more complex createIndex using a compound unique index in the background and dropping duplicated documents - * - * @_class collection - * @_function createIndex - */ -exports.shouldCreateComplexIndexOnTwoFields = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_complex_index_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.createIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Show that duplicate records got dropped - collection.find({}).toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - - // Peform a query, with explain to show we hit the query - collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { - test.equal(null, err); - test.ok(explanation[0].indexBounds.a != null); - test.ok(explanation[0].indexBounds.b != null); - - db.close(); - test.done(); - }); - }) - }); - }); - }); - }); -} - -/** - * A more complex ensureIndex using a compound unique index in the background and dropping duplicated documents. - * - * @_class collection - * @_function ensureIndex - */ -exports.shouldCreateComplexEnsureIndex = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_complex_ensure_index_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Show that duplicate records got dropped - collection.find({}).toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - - // Peform a query, with explain to show we hit the query - collection.find({a:2}, {explain:true}).toArray(function(err, explanation) { - test.equal(null, err); - test.ok(explanation[0].indexBounds.a != null); - test.ok(explanation[0].indexBounds.b != null); - - db.close(); - test.done(); - }); - }) - }); - }); - }); - }); -} - -/** - * An examples showing the information returned by indexInformation - * - * @_class collection - * @_function indexInformation - */ -exports.shouldCorrectlyShowTheResultsFromIndexInformation = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('more_index_information_test', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Fetch basic indexInformation for collection - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); - - // Fetch full index information - collection.indexInformation({full:true}, function(err, indexInformation) { - test.deepEqual({ _id: 1 }, indexInformation[0].key); - test.deepEqual({ a: 1, b: 1 }, indexInformation[1].key); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An examples showing the creation and dropping of an index - * - * @_class collection - * @_function dropIndex - */ -exports.shouldCorrectlyCreateAndDropIndex = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('create_and_drop_an_index', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Drop the index - collection.dropIndex("a_1_b_1", function(err, result) { - test.equal(null, err); - - // Verify that the index is gone - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.equal(null, indexInformation.a_1_b_1); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * An examples showing the creation and dropping of an index - * - * @_class collection - * @_function dropIndexes - */ -exports.shouldCorrectlyCreateAndDropAllIndex = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('create_and_drop_all_indexes', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Create an additional index - collection.ensureIndex({c:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Drop the index - collection.dropAllIndexes(function(err, result) { - test.equal(null, err); - - // Verify that the index is gone - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.equal(null, indexInformation.a_1_b_1); - test.equal(null, indexInformation.c_1); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * An example showing how to force a reindex of a collection. - * - * @_class collection - * @_function reIndex - */ -exports.shouldCorrectlyForceReindexOnCollection = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a collection we want to drop later - db.createCollection('create_and_drop_all_indexes', function(err, collection) { - test.equal(null, err); - - // Insert a bunch of documents for the index - collection.insert([{a:1, b:1}, {a:1, b:1} - , {a:2, b:2}, {a:3, b:3}, {a:4, b:4, c:4}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Create an index on the a field - collection.ensureIndex({a:1, b:1} - , {unique:true, background:true, dropDups:true}, function(err, indexName) { - - // Force a reindex of the collection - collection.reIndex(function(err, result) { - test.equal(null, err); - test.equal(true, result); - - // Verify that the index is gone - collection.indexInformation(function(err, indexInformation) { - test.deepEqual([ [ '_id', 1 ] ], indexInformation._id_); - test.deepEqual([ [ 'a', 1 ], [ 'b', 1 ] ], indexInformation.a_1_b_1); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExtractIndexInformation = function(test) { - client.createCollection('test_index_information', function(err, collection) { - collection.insert({a:1}, {safe:true}, function(err, ids) { - // Create an index on the collection - client.createIndex(collection.collectionName, 'a', function(err, indexName) { - test.equal("a_1", indexName); - // Let's fetch the index information - client.indexInformation(collection.collectionName, function(err, collectionInfo) { - test.ok(collectionInfo['_id_'] != null); - test.equal('_id', collectionInfo['_id_'][0][0]); - test.ok(collectionInfo['a_1'] != null); - test.deepEqual([["a", 1]], collectionInfo['a_1']); - - client.indexInformation(function(err, collectionInfo2) { - var count1 = 0, count2 = 0; - // Get count of indexes - for(var i in collectionInfo) { count1 += 1;} - for(var i in collectionInfo2) { count2 += 1;} - - // Tests - test.ok(count2 >= count1); - test.ok(collectionInfo2['_id_'] != null); - test.equal('_id', collectionInfo2['_id_'][0][0]); - test.ok(collectionInfo2['a_1'] != null); - test.deepEqual([["a", 1]], collectionInfo2['a_1']); - test.ok((collectionInfo[indexName] != null)); - test.deepEqual([["a", 1]], collectionInfo[indexName]); - - // Let's close the db - test.done(); - }); - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleMultipleColumnIndexes = function(test) { - client.createCollection('test_multiple_index_cols', function(err, collection) { - collection.insert({a:1}, function(err, ids) { - // Create an index on the collection - client.createIndex(collection.collectionName, [['a', -1], ['b', 1], ['c', -1]], function(err, indexName) { - test.equal("a_-1_b_1_c_-1", indexName); - // Let's fetch the index information - client.indexInformation(collection.collectionName, function(err, collectionInfo) { - var count1 = 0; - // Get count of indexes - for(var i in collectionInfo) { count1 += 1;} - - // Test - test.equal(2, count1); - test.ok(collectionInfo[indexName] != null); - test.deepEqual([['a', -1], ['b', 1], ['c', -1]], collectionInfo[indexName]); - - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleUniqueIndex = function(test) { - // Create a non-unique index and test inserts - client.createCollection('test_unique_index', function(err, collection) { - client.createIndex(collection.collectionName, 'hello', function(err, indexName) { - // Insert some docs - collection.insert([{'hello':'world'}, {'hello':'mike'}, {'hello':'world'}], {safe:true}, function(err, errors) { - // Assert that we have no erros - client.error(function(err, errors) { - test.equal(1, errors.length); - test.equal(null, errors[0].err); - - // Create a unique index and test that insert fails - client.createCollection('test_unique_index2', function(err, collection) { - client.createIndex(collection.collectionName, 'hello', {unique:true}, function(err, indexName) { - // Insert some docs - collection.insert([{'hello':'world'}, {'hello':'mike'}, {'hello':'world'}], {safe:true}, function(err, ids) { - test.ok(err != null); - test.equal(11000, err.code); - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCreateSubfieldIndex = function(test) { - // Create a non-unique index and test inserts - client.createCollection('test_index_on_subfield', function(err, collection) { - collection.insert([{'hello': {'a':4, 'b':5}}, {'hello': {'a':7, 'b':2}}, {'hello': {'a':4, 'b':10}}], {safe:true}, function(err, ids) { - // Assert that we have no erros - client.error(function(err, errors) { - test.equal(1, errors.length); - test.ok(errors[0].err == null); - - // Create a unique subfield index and test that insert fails - client.createCollection('test_index_on_subfield2', function(err, collection) { - client.createIndex(collection.collectionName, 'hello.a', true, function(err, indexName) { - collection.insert([{'hello': {'a':4, 'b':5}}, {'hello': {'a':7, 'b':2}}, {'hello': {'a':4, 'b':10}}], {safe:true}, function(err, ids) { - // Assert that we have erros - test.ok(err != null); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyDropIndexes = function(test) { - client.createCollection('test_drop_indexes', function(err, collection) { - collection.insert({a:1}, {safe:true}, function(err, ids) { - // Create an index on the collection - client.createIndex(collection.collectionName, 'a', function(err, indexName) { - test.equal("a_1", indexName); - // Drop all the indexes - collection.dropAllIndexes(function(err, result) { - test.equal(true, result); - - collection.indexInformation(function(err, result) { - test.ok(result['a_1'] == null); - test.done(); - }) - }) - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleDistinctIndexes = function(test) { - client.createCollection('test_distinct_queries', function(err, collection) { - collection.insert([{'a':0, 'b':{'c':'a'}}, - {'a':1, 'b':{'c':'b'}}, - {'a':1, 'b':{'c':'c'}}, - {'a':2, 'b':{'c':'a'}}, {'a':3}, {'a':3}], {safe:true}, function(err, ids) { - collection.distinct('a', function(err, docs) { - test.deepEqual([0, 1, 2, 3], docs.sort()); - }); - - collection.distinct('b.c', function(err, docs) { - test.deepEqual(['a', 'b', 'c'], docs.sort()); - test.done(); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteEnsureIndex = function(test) { - client.createCollection('test_ensure_index', function(err, collection) { - // Create an index on the collection - client.ensureIndex(collection.collectionName, 'a', function(err, indexName) { - test.equal("a_1", indexName); - // Let's fetch the index information - client.indexInformation(collection.collectionName, function(err, collectionInfo) { - test.ok(collectionInfo['_id_'] != null); - test.equal('_id', collectionInfo['_id_'][0][0]); - test.ok(collectionInfo['a_1'] != null); - test.deepEqual([["a", 1]], collectionInfo['a_1']); - - client.ensureIndex(collection.collectionName, 'a', function(err, indexName) { - test.equal("a_1", indexName); - // Let's fetch the index information - client.indexInformation(collection.collectionName, function(err, collectionInfo) { - test.ok(collectionInfo['_id_'] != null); - test.equal('_id', collectionInfo['_id_'][0][0]); - test.ok(collectionInfo['a_1'] != null); - test.deepEqual([["a", 1]], collectionInfo['a_1']); - // Let's close the db - test.done(); - }); - }); - }); - }); - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyCreateAndUseSparseIndex = function(test) { - client.createCollection('create_and_use_sparse_index_test', function(err, r) { - client.collection('create_and_use_sparse_index_test', function(err, collection) { - - collection.ensureIndex({title:1}, {sparse:true}, function(err, indexName) { - collection.insert([{name:"Jim"}, {name:"Sarah", title:"Princess"}], {safe:true}, function(err, result) { - collection.find({title:{$ne:null}}).sort({title:1}).toArray(function(err, items) { - test.equal(1, items.length); - test.equal("Sarah", items[0].name); - - // Fetch the info for the indexes - collection.indexInformation({full:true}, function(err, indexInfo) { - test.equal(null, err); - test.equal(2, indexInfo.length); - test.done(); - }) - }) - }); - }) - }) - }) -} - -/** - * @ignore - */ -exports["Should correctly execute insert with keepGoing option on mongod >= 1.9.1"] = function(test) { - client.admin().serverInfo(function(err, result){ - if(parseInt((result.version.replace(/\./g, ''))) >= 191) { - client.createCollection('shouldCorrectlyExecuteKeepGoingWithMongodb191OrHigher', function(err, collection) { - collection.ensureIndex({title:1}, {unique:true}, function(err, indexName) { - collection.insert([{name:"Jim"}, {name:"Sarah", title:"Princess"}], {safe:true}, function(err, result) { - // Force keep going flag, ignoring unique index issue - collection.insert([{name:"Jim"}, {name:"Sarah", title:"Princess"}, {name:'Gump', title:"Gump"}], {safe:true, keepGoing:true}, function(err, result) { - collection.count(function(err, count) { - test.equal(3, count); - test.done(); - }) - }); - }); - }); - }); - } else { - test.done(); - } - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleGeospatialIndexes = function(test) { - client.admin().serverInfo(function(err, result){ - if(parseInt((result.version.replace(/\./g, ''))) >= 191) { - client.createCollection('geospatial_index_test', function(err, r) { - client.collection('geospatial_index_test', function(err, collection) { - collection.ensureIndex({loc:'2d'}, function(err, indexName) { - collection.insert({'loc': [-100,100]}, {safe:true}, function(err, result) { - test.equal(err,null); - collection.insert({'loc': [200,200]}, {safe:true}, function(err, result) { - err = err ? err : {}; - test.equal(err.err,"point not in interval of [ -180, 180 )"); - test.done(); - }); - }); - }); - }); - }); - } else { - test.done(); - } - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleGeospatialIndexesAlteredRange = function(test) { - client.admin().serverInfo(function(err, result){ - if(parseInt((result.version.replace(/\./g, ''))) >= 191) { - client.createCollection('geospatial_index_altered_test', function(err, r) { - client.collection('geospatial_index_altered_test', function(err, collection) { - collection.ensureIndex({loc:'2d'},{min:0,max:1024}, function(err, indexName) { - collection.insert({'loc': [100,100]}, {safe:true}, function(err, result) { - test.equal(err,null); - collection.insert({'loc': [200,200]}, {safe:true}, function(err, result) { - test.equal(err,null); - collection.insert({'loc': [-200,-200]}, {safe:true}, function(err, result) { - err = err ? err : {}; - test.equal(err.err,"point not in interval of [ 0, 1024 )"); - test.done(); - }); - }); - }); - }); - }); - }); - } else { - test.done(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/insert_test.js b/node_modules/reg/node_modules/mongodb/test/insert_test.js deleted file mode 100644 index 32da730..0000000 --- a/node_modules/reg/node_modules/mongodb/test/insert_test.js +++ /dev/null @@ -1,1132 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Script = require('vm'), - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Binary = require('../lib/mongodb/bson/binary').Binary, - Code = require('../lib/mongodb/bson/code').Code, - DBRef = require('../lib/mongodb/bson/db_ref').DBRef, - Timestamp = require('../lib/mongodb/bson/timestamp').Timestamp, - Long = require('../lib/mongodb/bson/long').Long, - Collection = mongodb.Collection, - Server = mongodb.Server, - Step = require("../deps/step/lib/step"), - ServerManager = require('./tools/server_manager').ServerManager; - -var MONGODB = 'integration_tests'; -var client = null; -var useSSL = process.env['USE_SSL'] != null ? true : false; -var native_parser = (process.env['TEST_NATIVE'] != null); - -/** - * Module for parsing an ISO 8601 formatted string into a Date object. - * @ignore - */ -var ISODate = function (string) { - var match; - - if (typeof string.getTime === "function") - return string; - else if (match = string.match(/^(\d{4})(-(\d{2})(-(\d{2})(T(\d{2}):(\d{2})(:(\d{2})(\.(\d+))?)?(Z|((\+|-)(\d{2}):(\d{2}))))?)?)?$/)) { - var date = new Date(); - date.setUTCFullYear(Number(match[1])); - date.setUTCMonth(Number(match[3]) - 1 || 0); - date.setUTCDate(Number(match[5]) || 0); - date.setUTCHours(Number(match[7]) || 0); - date.setUTCMinutes(Number(match[8]) || 0); - date.setUTCSeconds(Number(match[10]) || 0); - date.setUTCMilliseconds(Number("." + match[12]) * 1000 || 0); - - if (match[13] && match[13] !== "Z") { - var h = Number(match[16]) || 0, - m = Number(match[17]) || 0; - - h *= 3600000; - m *= 60000; - - var offset = h + m; - if (match[15] == "+") - offset = -offset; - - new Date(date.valueOf() + offset); - } - - return date; - } else - throw new Error("Invalid ISO 8601 date given.", __filename); -}; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A simple document insert example, not using safe mode to ensure document persistance on MongoDB - * - * @_class collection - * @_function insert - * @ignore - */ -exports.shouldCorrectlyPerformASimpleSingleDocumentInsertNoCallbackNoSafe = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection to insert document into - db.collection("simple_document_insert_collection_no_safe", function(err, collection) { - - // Insert a single document - collection.insert({hello:'world_no_safe'}); - - // Wait for a second before finishing up, to ensure we have written the item to disk - setTimeout(function() { - - // Fetch the document - collection.findOne({hello:'world_no_safe'}, function(err, item) { - test.equal(null, err); - test.equal('world_no_safe', item.hello); - test.done(); - db.close(); - }) - }, 1000); - }); - }); -} - -/** - * A batch document insert example, using safe mode to ensure document persistance on MongoDB - * - * @_class collection - * @_function insert - * @ignore - */ -exports.shouldCorrectlyPerformABatchDocumentInsertSafe = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection to insert document into - db.collection("batch_document_insert_collection_safe", function(err, collection) { - - // Insert a single document - collection.insert([{hello:'world_safe1'} - , {hello:'world_safe2'}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Fetch the document - collection.findOne({hello:'world_safe2'}, function(err, item) { - test.equal(null, err); - test.equal('world_safe2', item.hello); - test.done(); - db.close(); - }) - }); - }); - }); -} - -/** - * Example of inserting a document containing functions - * - * @_class collection - * @_function insert - * @ignore - */ -exports.shouldCorrectlyPerformASimpleDocumentInsertWithFunctionSafe = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection to insert document into - db.collection("simple_document_insert_with_function_safe", function(err, collection) { - - // Insert a single document - collection.insert({hello:'world' - , func:function() {}}, {safe:true, serializeFunctions:true}, function(err, result) { - test.equal(null, err); - - // Fetch the document - collection.findOne({hello:'world'}, function(err, item) { - test.equal(null, err); - test.ok("function() {}", item.code); - test.done(); - db.close(); - }) - }); - }); - }); -} - -/** - * Example of using keepGoing to allow batch insert to complete even when there are illegal documents in the batch - * - * @_class collection - * @_function insert - * @ignore - */ -exports["Should correctly execute insert with keepGoing option on mongod >= 1.9.1"] = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Only run the rest of the code if we have a mongodb server with version >= 1.9.1 - db.admin().serverInfo(function(err, result){ - - // Ensure we are running at least MongoDB v1.9.1 - if(parseInt((result.version.replace(/\./g, ''))) >= 191) { - - // Create a collection - client.createCollection('keepGoingExample', function(err, collection) { - - // Add an unique index to title to force errors in the batch insert - collection.ensureIndex({title:1}, {unique:true}, function(err, indexName) { - - // Insert some intial data into the collection - collection.insert([{name:"Jim"} - , {name:"Sarah", title:"Princess"}], {safe:true}, function(err, result) { - - // Force keep going flag, ignoring unique index issue - collection.insert([{name:"Jim"} - , {name:"Sarah", title:"Princess"} - , {name:'Gump', title:"Gump"}], {safe:true, keepGoing:true}, function(err, result) { - - // Count the number of documents left (should not include the duplicates) - collection.count(function(err, count) { - test.equal(3, count); - db.close(); - test.done(); - }) - }); - }); - }); - }); - } else { - db.close(); - test.done(); - } - }); - }); -} - -/** - * @ignore - */ -exports.shouldForceMongoDbServerToAssignId = function(test) { - /// Set up server with custom pk factory - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null), 'forceServerObjectId':true}); - db.open(function(err, client) { - client.createCollection('test_insert2', function(err, r) { - client.collection('test_insert2', function(err, collection) { - - Step( - function inserts() { - var group = this.group(); - - for(var i = 1; i < 1000; i++) { - collection.insert({c:i}, {safe:true}, group()); - } - }, - - function done(err, result) { - collection.insert({a:2}, {safe:true}, function(err, r) { - collection.insert({a:3}, {safe:true}, function(err, r) { - collection.count(function(err, count) { - test.equal(1001, count); - // Locate all the entries using find - collection.find(function(err, cursor) { - cursor.toArray(function(err, results) { - test.equal(1001, results.length); - test.ok(results[0] != null); - - client.close(); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - } - ) - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformSingleInsert = function(test) { - client.createCollection('shouldCorrectlyPerformSingleInsert', function(err, collection) { - collection.insert({a:1}, {safe:true}, function(err, result) { - collection.findOne(function(err, item) { - test.equal(1, item.a); - test.done(); - }) - }) - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformBasicInsert = function(test) { - client.createCollection('test_insert', function(err, r) { - client.collection('test_insert', function(err, collection) { - - Step( - function inserts() { - var group = this.group(); - - for(var i = 1; i < 1000; i++) { - collection.insert({c:i}, {safe:true}, group()); - } - }, - - function done(err, result) { - collection.insert({a:2}, {safe:true}, function(err, r) { - collection.insert({a:3}, {safe:true}, function(err, r) { - collection.count(function(err, count) { - test.equal(1001, count); - // Locate all the entries using find - collection.find(function(err, cursor) { - cursor.toArray(function(err, results) { - test.equal(1001, results.length); - test.ok(results[0] != null); - - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - } - ) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleMultipleDocumentInsert = function(test) { - client.createCollection('test_multiple_insert', function(err, r) { - var collection = client.collection('test_multiple_insert', function(err, collection) { - var docs = [{a:1}, {a:2}]; - - collection.insert(docs, {safe:true}, function(err, ids) { - ids.forEach(function(doc) { - test.ok(((doc['_id']) instanceof ObjectID || Object.prototype.toString.call(doc['_id']) === '[object ObjectID]')); - }); - - // Let's ensure we have both documents - collection.find(function(err, cursor) { - cursor.toArray(function(err, docs) { - test.equal(2, docs.length); - var results = []; - // Check that we have all the results we want - docs.forEach(function(doc) { - if(doc.a == 1 || doc.a == 2) results.push(1); - }); - test.equal(2, results.length); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteSaveInsertUpdate= function(test) { - client.createCollection('shouldCorrectlyExecuteSaveInsertUpdate', function(err, collection) { - collection.save({ email : 'save' }, {safe:true}, function() { - collection.insert({ email : 'insert' }, {safe:true}, function() { - collection.update( - { email : 'update' }, - { email : 'update' }, - { upsert: true, safe:true}, - - function() { - collection.find(function(e, c) { - c.toArray(function(e, a) { - test.equal(3, a.length) - test.done(); - }); - }); - } - ); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertAndRetrieveLargeIntegratedArrayDocument = function(test) { - client.createCollection('test_should_deserialize_large_integrated_array', function(err, collection) { - var doc = {'a':0, - 'b':['tmp1', 'tmp2', 'tmp3', 'tmp4', 'tmp5', 'tmp6', 'tmp7', 'tmp8', 'tmp9', 'tmp10', 'tmp11', 'tmp12', 'tmp13', 'tmp14', 'tmp15', 'tmp16'] - }; - // Insert the collection - collection.insert(doc, {safe:true}, function(err, r) { - // Fetch and check the collection - collection.findOne({'a': 0}, function(err, result) { - test.deepEqual(doc.a, result.a); - test.deepEqual(doc.b, result.b); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertAndRetrieveDocumentWithAllTypes = function(test) { - client.createCollection('test_all_serialization_types', function(err, collection) { - var date = new Date(); - var oid = new ObjectID(); - var string = 'binstring' - var bin = new Binary() - for(var index = 0; index < string.length; index++) { - bin.put(string.charAt(index)) - } - - var motherOfAllDocuments = { - 'string': 'hello', - 'array': [1,2,3], - 'hash': {'a':1, 'b':2}, - 'date': date, - 'oid': oid, - 'binary': bin, - 'int': 42, - 'float': 33.3333, - 'regexp': /regexp/, - 'boolean': true, - 'long': date.getTime(), - 'where': new Code('this.a > i', {i:1}), - 'dbref': new DBRef('namespace', oid, 'integration_tests_') - } - - collection.insert(motherOfAllDocuments, {safe:true}, function(err, docs) { - collection.findOne(function(err, doc) { - // Assert correct deserialization of the values - test.equal(motherOfAllDocuments.string, doc.string); - test.deepEqual(motherOfAllDocuments.array, doc.array); - test.equal(motherOfAllDocuments.hash.a, doc.hash.a); - test.equal(motherOfAllDocuments.hash.b, doc.hash.b); - test.equal(date.getTime(), doc.long); - test.equal(date.toString(), doc.date.toString()); - test.equal(date.getTime(), doc.date.getTime()); - test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString()); - test.equal(motherOfAllDocuments.binary.value(), doc.binary.value()); - - test.equal(motherOfAllDocuments.int, doc.int); - test.equal(motherOfAllDocuments.long, doc.long); - test.equal(motherOfAllDocuments.float, doc.float); - test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString()); - test.equal(motherOfAllDocuments.boolean, doc.boolean); - test.equal(motherOfAllDocuments.where.code, doc.where.code); - test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i); - - test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace); - test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString()); - test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db); - test.done(); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertAndUpdateDocumentWithNewScriptContext= function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, db) { - //convience curried handler for functions of type 'a -> (err, result) - function getResult(callback){ - return function(error, result) { - test.ok(error == null); - return callback(result); - } - }; - - db.collection('users', getResult(function(user_collection){ - user_collection.remove({}, {safe:true}, function(err, result) { - //first, create a user object - var newUser = { name : 'Test Account', settings : {} }; - user_collection.insert([newUser], {safe:true}, getResult(function(users){ - var user = users[0]; - - var scriptCode = "settings.block = []; settings.block.push('test');"; - var context = { settings : { thisOneWorks : "somestring" } }; - - Script.runInNewContext(scriptCode, context, "testScript"); - - //now create update command and issue it - var updateCommand = { $set : context }; - - user_collection.update({_id : user._id}, updateCommand, {safe:true}, - getResult(function(updateCommand) { - // Fetch the object and check that the changes are persisted - user_collection.findOne({_id : user._id}, function(err, doc) { - test.ok(err == null); - test.equal("Test Account", doc.name); - test.equal("somestring", doc.settings.thisOneWorks); - test.equal("test", doc.settings.block[0]); - - // Let's close the db - db.close(); - test.done(); - }); - }) - ); - })); - }); - })); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlySerializeDocumentWithAllTypesInNewContext = function(test) { - client.createCollection('test_all_serialization_types_new_context', function(err, collection) { - var date = new Date(); - var scriptCode = - "var string = 'binstring'\n" + - "var bin = new mongo.Binary()\n" + - "for(var index = 0; index < string.length; index++) {\n" + - " bin.put(string.charAt(index))\n" + - "}\n" + - "motherOfAllDocuments['string'] = 'hello';" + - "motherOfAllDocuments['array'] = [1,2,3];" + - "motherOfAllDocuments['hash'] = {'a':1, 'b':2};" + - "motherOfAllDocuments['date'] = date;" + - "motherOfAllDocuments['oid'] = new mongo.ObjectID();" + - "motherOfAllDocuments['binary'] = bin;" + - "motherOfAllDocuments['int'] = 42;" + - "motherOfAllDocuments['float'] = 33.3333;" + - "motherOfAllDocuments['regexp'] = /regexp/;" + - "motherOfAllDocuments['boolean'] = true;" + - "motherOfAllDocuments['long'] = motherOfAllDocuments['date'].getTime();" + - "motherOfAllDocuments['where'] = new mongo.Code('this.a > i', {i:1});" + - "motherOfAllDocuments['dbref'] = new mongo.DBRef('namespace', motherOfAllDocuments['oid'], 'integration_tests_');"; - - var context = { - motherOfAllDocuments : {}, - mongo:{ - ObjectID:ObjectID, - Binary:Binary, - Code:Code, - DBRef:DBRef - }, - date:date}; - - // Execute function in context - Script.runInNewContext(scriptCode, context, "testScript"); - // sys.puts(sys.inspect(context.motherOfAllDocuments)) - var motherOfAllDocuments = context.motherOfAllDocuments; - - collection.insert(context.motherOfAllDocuments, {safe:true}, function(err, docs) { - collection.findOne(function(err, doc) { - // Assert correct deserialization of the values - test.equal(motherOfAllDocuments.string, doc.string); - test.deepEqual(motherOfAllDocuments.array, doc.array); - test.equal(motherOfAllDocuments.hash.a, doc.hash.a); - test.equal(motherOfAllDocuments.hash.b, doc.hash.b); - test.equal(date.getTime(), doc.long); - test.equal(date.toString(), doc.date.toString()); - test.equal(date.getTime(), doc.date.getTime()); - test.equal(motherOfAllDocuments.oid.toHexString(), doc.oid.toHexString()); - test.equal(motherOfAllDocuments.binary.value(), doc.binary.value()); - - test.equal(motherOfAllDocuments.int, doc.int); - test.equal(motherOfAllDocuments.long, doc.long); - test.equal(motherOfAllDocuments.float, doc.float); - test.equal(motherOfAllDocuments.regexp.toString(), doc.regexp.toString()); - test.equal(motherOfAllDocuments.boolean, doc.boolean); - test.equal(motherOfAllDocuments.where.code, doc.where.code); - test.equal(motherOfAllDocuments.where.scope['i'], doc.where.scope.i); - test.equal(motherOfAllDocuments.dbref.namespace, doc.dbref.namespace); - test.equal(motherOfAllDocuments.dbref.oid.toHexString(), doc.dbref.oid.toHexString()); - test.equal(motherOfAllDocuments.dbref.db, doc.dbref.db); - - test.done(); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyDoToJsonForLongValue = function(test) { - client.createCollection('test_to_json_for_long', function(err, collection) { - test.ok(collection instanceof Collection); - - collection.insert([{value: Long.fromNumber(32222432)}], {safe:true}, function(err, ids) { - collection.findOne({}, function(err, item) { - test.equal(32222432, item.value); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertAndUpdateWithNoCallback = function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, poolSize: 1, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, client) { - client.createCollection('test_insert_and_update_no_callback', function(err, collection) { - // Insert the update - collection.insert({i:1}, {safe:true}) - // Update the record - collection.update({i:1}, {"$set":{i:2}}, {safe:true}) - - // Make sure we leave enough time for mongodb to record the data - setTimeout(function() { - // Locate document - collection.findOne({}, function(err, item) { - test.equal(2, item.i) - - client.close(); - test.done(); - }); - }, 100) - }) - }); -} - -/** - * @ignore - */ -exports.shouldInsertAndQueryTimestamp = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - db.createCollection('test_insert_and_query_timestamp', function(err, collection) { - // Insert the update - collection.insert({i:Timestamp.fromNumber(100), j:Long.fromNumber(200)}, {safe:true}, function(err, r) { - // Locate document - collection.findOne({}, function(err, item) { - test.ok(item.i instanceof Timestamp); - test.equal(100, item.i); - test.ok(typeof item.j == "number"); - test.equal(200, item.j); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertAndQueryUndefined = function(test) { - client.createCollection('test_insert_and_query_undefined', function(err, collection) { - // Insert the update - collection.insert({i:undefined}, {safe:true}, function(err, r) { - // Locate document - collection.findOne({}, function(err, item) { - test.equal(null, item.i) - - test.done(); - }); - }) - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlySerializeDBRefToJSON = function(test) { - var dbref = new DBRef("foo", ObjectID.createFromHexString("fc24a04d4560531f00000000"), null); - JSON.stringify(dbref); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyPerformSafeInsert = function(test) { - var fixtures = [{ - name: "empty", array: [], bool: false, dict: {}, float: 0.0, string: "" - }, { - name: "not empty", array: [1], bool: true, dict: {x: "y"}, float: 1.0, string: "something" - }, { - name: "simple nested", array: [1, [2, [3]]], bool: true, dict: {x: "y", array: [1,2,3,4], dict: {x: "y", array: [1,2,3,4]}}, float: 1.5, string: "something simply nested" - }]; - - - client.createCollection('test_safe_insert', function(err, collection) { - Step( - function inserts() { - var group = this.group(); - - for(var i = 0; i < fixtures.length; i++) { - collection.insert(fixtures[i], {safe:true}, group()); - } - }, - - function done() { - collection.count(function(err, count) { - test.equal(3, count); - - collection.find().toArray(function(err, docs) { - test.equal(3, docs.length) - }); - }); - - - collection.find({}, {}, function(err, cursor) { - var counter = 0; - - cursor.each(function(err, doc) { - if(doc == null) { - test.equal(3, counter); - test.done(); - } else { - counter = counter + 1; - } - }); - }); - } - ) - }) -} - -/** - * @ignore - */ -exports.shouldThrowErrorIfSerializingFunction = function(test) { - client.createCollection('test_should_throw_error_if_serializing_function', function(err, collection) { - var func = function() { return 1}; - // Insert the update - collection.insert({i:1, z:func }, {safe:true, serializeFunctions:true}, function(err, result) { - collection.findOne({_id:result[0]._id}, function(err, object) { - test.equal(func.toString(), object.z.code); - test.equal(1, object.i); - test.done(); - }) - }) - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertDocumentWithUUID = function(test) { - client.collection("insert_doc_with_uuid", function(err, collection) { - collection.insert({_id : "12345678123456781234567812345678", field: '1'}, {safe:true}, function(err, result) { - test.equal(null, err); - - collection.find({_id : "12345678123456781234567812345678"}).toArray(function(err, items) { - test.equal(null, err); - test.equal(items[0]._id, "12345678123456781234567812345678") - test.equal(items[0].field, '1') - - // Generate a binary id - var binaryUUID = new Binary('00000078123456781234567812345678', Binary.SUBTYPE_UUID); - - collection.insert({_id : binaryUUID, field: '2'}, {safe:true}, function(err, result) { - collection.find({_id : binaryUUID}).toArray(function(err, items) { - test.equal(null, err); - test.equal(items[0].field, '2') - test.done(); - }); - }); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCallCallbackWithDbDriverInStrictMode = function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, poolSize: 1, ssl:useSSL}), {strict:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, client) { - client.createCollection('test_insert_and_update_no_callback_strict', function(err, collection) { - collection.insert({_id : "12345678123456781234567812345678", field: '1'}, {safe:true}, function(err, result) { - test.equal(null, err); - - collection.update({ '_id': "12345678123456781234567812345678" }, { '$set': { 'field': 0 }}, function(err, numberOfUpdates) { - test.equal(null, err); - test.equal(1, numberOfUpdates); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertDBRefWithDbNotDefined = function(test) { - client.createCollection('shouldCorrectlyInsertDBRefWithDbNotDefined', function(err, collection) { - var doc = {_id: new ObjectID()}; - var doc2 = {_id: new ObjectID()}; - var doc3 = {_id: new ObjectID()}; - collection.insert(doc, {safe:true}, function(err, result) { - // Create object with dbref - doc2.ref = new DBRef('shouldCorrectlyInsertDBRefWithDbNotDefined', doc._id); - doc3.ref = new DBRef('shouldCorrectlyInsertDBRefWithDbNotDefined', doc._id, MONGODB); - - collection.insert([doc2, doc3], {safe:true}, function(err, result) { - // Get all items - collection.find().toArray(function(err, items) { - test.equal("shouldCorrectlyInsertDBRefWithDbNotDefined", items[1].ref.namespace); - test.equal(doc._id.toString(), items[1].ref.oid.toString()); - test.equal(null, items[1].ref.db); - - test.equal("shouldCorrectlyInsertDBRefWithDbNotDefined", items[2].ref.namespace); - test.equal(doc._id.toString(), items[2].ref.oid.toString()); - test.equal(MONGODB, items[2].ref.db); - - test.done(); - }) - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertUpdateRemoveWithNoOptions = function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, db) { - db.collection('shouldCorrectlyInsertUpdateRemoveWithNoOptions', function(err, collection) { - collection.insert({a:1}); - collection.update({a:1}, {a:2}); - collection.remove({a:2}); - - collection.count(function(err, count) { - test.equal(0, count); - - db.close(); - test.done(); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyExecuteMultipleFetches = function(test) { - var db = new Db(MONGODB, new Server('localhost', 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Search parameter - var to = 'ralph' - // Execute query - db.open(function(err, db) { - db.collection('shouldCorrectlyExecuteMultipleFetches', function(err, collection) { - collection.insert({addresses:{localPart:'ralph'}}, {safe:true}, function(err, result) { - // Let's find our user - collection.findOne({"addresses.localPart" : to}, function( err, doc ) { - test.equal(null, err); - test.equal(to, doc.addresses.localPart); - - db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyFailWhenNoObjectToUpdate= function(test) { - client.createCollection('shouldCorrectlyExecuteSaveInsertUpdate', function(err, collection) { - collection.update({_id : new ObjectID()}, { email : 'update' }, {safe:true}, - function(err, result) { - test.equal(0, result); - test.done(); - } - ); - }); -} - -/** - * @ignore - */ -exports['Should correctly insert object and retrieve it when containing array and IsoDate'] = function(test) { - var doc = { - "_id" : new ObjectID("4e886e687ff7ef5e00000162"), - "str" : "foreign", - "type" : 2, - "timestamp" : ISODate("2011-10-02T14:00:08.383Z"), - "links" : [ - "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" - ] - } - - client.createCollection('Should_correctly_insert_object_and_retrieve_it_when_containing_array_and_IsoDate', function(err, collection) { - collection.insert(doc, {safe:true}, function(err, result) { - test.ok(err == null); - - collection.findOne(function(err, item) { - test.ok(err == null); - test.deepEqual(doc, item); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should correctly insert object with timestamps'] = function(test) { - var doc = { - "_id" : new ObjectID("4e886e687ff7ef5e00000162"), - "str" : "foreign", - "type" : 2, - "timestamp" : new Timestamp(10000), - "links" : [ - "http://www.reddit.com/r/worldnews/comments/kybm0/uk_home_secretary_calls_for_the_scrapping_of_the/" - ], - "timestamp2" : new Timestamp(33333), - } - - client.createCollection('Should_correctly_insert_object_with_timestamps', function(err, collection) { - collection.insert(doc, {safe:true}, function(err, result) { - test.ok(err == null); - - collection.findOne(function(err, item) { - test.ok(err == null); - test.deepEqual(doc, item); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should fail on insert due to key starting with $'] = function(test) { - var doc = { - "_id" : new ObjectID("4e886e687ff7ef5e00000162"), - "$key" : "foreign", - } - - client.createCollection('Should_fail_on_insert_due_to_key_starting_with', function(err, collection) { - collection.insert(doc, {safe:true}, function(err, result) { - test.ok(err != null); - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly allow for control of serialization of functions on command level'] = function(test) { - var doc = { - str : "String", - func : function() {} - } - - client.createCollection("Should_Correctly_allow_for_control_of_serialization_of_functions_on_command_level", function(err, collection) { - test.ok(err == null); - - collection.insert(doc, {safe:true}, function(err, result) { - - collection.update({str:"String"}, {$set:{c:1, d:function(){}}}, {safe:true, serializeFunctions:false}, function(err, result) { - test.equal(1, result); - - collection.findOne({str:"String"}, function(err, item) { - test.equal(null, item.d); - - // Execute a safe insert with replication to two servers - collection.findAndModify({str:"String"}, [['a', 1]], {'$set':{'f':function() {}}}, {new:true, safe: true, serializeFunctions:true}, function(err, result) { - test.ok(result.f instanceof Code) - test.done(); - }) - }) - }) - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly allow for control of serialization of functions on collection level'] = function(test) { - var doc = { - str : "String", - func : function() {} - } - - client.createCollection("Should_Correctly_allow_for_control_of_serialization_of_functions_on_collection_level", {serializeFunctions:true}, function(err, collection) { - test.ok(err == null); - - collection.insert(doc, {safe:true}, function(err, result) { - test.equal(null, err); - - collection.findOne({str : "String"}, function(err, item) { - test.ok(item.func instanceof Code); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly allow for using a Date object as _id'] = function(test) { - var doc = { - _id : new Date(), - str : 'hello' - } - - client.createCollection("Should_Correctly_allow_for_using_a_Date_object_as__id", {serializeFunctions:true}, function(err, collection) { - test.ok(err == null); - - collection.insert(doc, {safe:true}, function(err, result) { - test.equal(null, err); - - collection.findOne({str : "hello"}, function(err, item) { - test.ok(item._id instanceof Date); - test.done(); - }); - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly fail to update returning 0 results'] = function(test) { - client.createCollection("Should_Correctly_fail_to_update_returning_0_results", {serializeFunctions:true}, function(err, collection) { - test.ok(err == null); - - collection.update({a:1}, {$set: {a:1}}, {safe:true}, function(err, numberOfUpdated) { - test.equal(0, numberOfUpdated); - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports['Should Correctly update two fields including a sub field'] = function(test) { - var doc = { - _id: new ObjectID(), - Prop1: 'p1', - Prop2: 'p2', - More: { - Sub1: 's1', - Sub2: 's2', - Sub3: 's3' - } - } - - client.createCollection("Should_Correctly_update_two_fields_including_a_sub_field", {}, function(err, collection) { - collection.insert(doc, {safe:true}, function(err, result) { - test.equal(null, err); - - // Update two fields - collection.update({_id:doc._id}, {$set:{Prop1:'p1_2', 'More.Sub2':'s2_2'}}, {safe:true}, function(err, numberOfUpdatedDocs) { - test.equal(null, err); - test.equal(1, numberOfUpdatedDocs); - - collection.findOne({_id:doc._id}, function(err, item) { - test.equal(null, err); - test.equal('p1_2', item.Prop1); - test.equal('s2_2', item.More.Sub2); - test.done(); - }) - }); - }) - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/logging_test.js b/node_modules/reg/node_modules/mongodb/test/logging_test.js deleted file mode 100644 index 2094c8d..0000000 --- a/node_modules/reg/node_modules/mongodb/test/logging_test.js +++ /dev/null @@ -1,93 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlyLogContent = function(test) { - var loggedOutput = false; - var logger = { - doDebug:true, - doError:true, - doLog:true, - - error:function(message, object) {}, - log:function(message, object) {}, - - debug:function(message, object) { - loggedOutput = true; - } - } - - var automatic_connect_client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null), retryMiliSeconds:50, logger:logger}); - automatic_connect_client.open(function(err, automatic_connect_client) { - automatic_connect_client.close(); - test.equal(true, loggedOutput); - test.done(); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/manual_tests/grids_fs_compatibility_test.js b/node_modules/reg/node_modules/mongodb/test/manual_tests/grids_fs_compatibility_test.js deleted file mode 100644 index 4f1f738..0000000 --- a/node_modules/reg/node_modules/mongodb/test/manual_tests/grids_fs_compatibility_test.js +++ /dev/null @@ -1,20 +0,0 @@ -var Server = require("../../lib/mongodb").Server, - Db = require("../../lib/mongodb").Db, - ObjectID = require("../../lib/mongodb").ObjectID, - GridStore = require("../../lib/mongodb").GridStore; - -var options = { - auto_reconnect: true, - poolSize: 1, - socketOptions: { timeout:8000 } -}; - -var db = new Db("data", new Server( 'localhost', 27017, options)); -db.open(function(err, client){ - var id = new ObjectID(); - // Write a file into gridfs and then verify that it's readable - var gridStore = new GridStore(client, 'manual_test.jpg', "w"); - gridStore.writeFile('/Users/christiankvalheim/coding/projects/node-mongodb-native/test/gridstore/iya_logo_final_bw.jpg', function(err, result) { - db.close(); - }) -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/manual_tests/hanging_queries_test.js b/node_modules/reg/node_modules/mongodb/test/manual_tests/hanging_queries_test.js deleted file mode 100644 index 09ac425..0000000 --- a/node_modules/reg/node_modules/mongodb/test/manual_tests/hanging_queries_test.js +++ /dev/null @@ -1,182 +0,0 @@ -var ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager; - -var mongo = require('../../lib/mongodb'), - // website = new mongo.Db('simplereach_website_production', new mongo.Server('localhost', 27017, {auto_reconnect:true, poolSize:5})), - // adserver = new mongo.Db('adserver', new mongo.Server('localhost', 27017, {auto_reconnect:true, poolSize:5})), - accounts = [], accountsCollection, contentCollection, count = 0; - -RS = new ReplicaSetManager({retries:120, secondary_count:1, passive_count:0, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new mongo.ReplSetServers( [ - new mongo.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongo.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongo.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, read_secondary:true, readPreference:mongo.Server.READ_SECONDARY_ONLY} - ); - - // Replica configuration - var replSet2 = new mongo.ReplSetServers( [ - new mongo.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongo.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongo.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, read_secondary:true, readPreference:mongo.Server.READ_SECONDARY_ONLY} - ); - - var adserver = new mongo.Db('adserver', replSet); - var website = new mongo.Db('simplereach_website_production', replSet2); - - website.on('error', function(err){ - console.log(err); process.exit(1); - }); - - adserver.on('error', function(err){ - console.log(err); process.exit(1); - }); - - /** - * loads content for accounts in the array - */ - function loadContent(){ - var account = accounts.shift(); - fields = ['account_id','avg_ctr','cat','channels','ckw','ctr','published','topics','url', 'updated_at', 'disabled'], - sort = [['published','desc']], - criteria = { account_id:account, $or:[ { end_date: null }, { end_date:{ $gte:new Date() }} ]}; - - if(account === undefined){ - process.exit(1); - // no more accounts to process - // the return here goes into limbo - return; - } - console.log('GETTING CONTENT'); - contentCollection.find(criteria, {fields:fields, limit:100000, sort:sort}, function(err, cursor){ - - cursor.each(function(err, doc) { - if(err){ console.log(err); process.exit(1); } - if(doc === null){ - //once this account is done, load the next - console.log('FINISHED ACCOUNT', account, 'WITH', count, 'ITEMS'); - count = 0; - process.nextTick(function() { - loadContent(); - }) - } else { - count += 1; - } - }); - }); - } - - /** - * loads content for accounts in the array - */ - function loadContentParallel(account, callback){ - var fields = ['account_id','avg_ctr','cat','channels','ckw','ctr','published','topics','url', 'updated_at', 'disabled'], - sort = [['published','desc']], - criteria = { account_id:account, $or:[ { end_date: null }, { end_date:{ $gte:new Date() }} ]}; - - if(account === undefined){ - process.exit(1); - - // no more accounts to process - // the return here goes into limbo - return; - } - console.log('GETTING CONTENT'); - contentCollection.find(criteria, {fields:fields, limit:100000, sort:sort}, function(err, cursor){ - cursor.each(function(err, doc) { - if(err){ - return callback(err, account); - } - - if(doc === null){ - //once this account is done, load the next - console.log('FINISHED ACCOUNT', account, 'WITH', count, 'ITEMS'); - count = 0; - callback(null, account); - } else { - count += 1; - } - }); - }); - } - - /** - * Loads account ids and pushes them onto an array - **/ - function loadAccountsParallel(){ - accountsCollection.find({active:{$ne:null}}, { fields:{'_id':1, 'a':1}}).toArray(function(err, accounts) { - // keep track of the number of accounts - var numberOfFinishedAccount = accounts.length; - - for(var i = 0; i < accounts.length; i++) { - loadContentParallel(accounts[i].a, function(err, result) { - numberOfFinishedAccount = numberOfFinishedAccount - 1; - - if(numberOfFinishedAccount == 0) process.exit(0); - }); - } - }); - } - - /** - * Loads account ids and pushes them onto an array - **/ - function loadAccounts(){ - accountsCollection.find({active:{$ne:null}}, { fields:{'_id':1, 'a':1}}, function(err, cursor) { - if(err){ console.log(err); process.exit(1); } - console.log('GETTING ACCOUNTS'); - cursor.each(function(err, doc){ - if(err){ console.log(err); process.exit(1); } - if(doc !== null){ - accounts.push(doc.a); - } else { - console.log('FOUND', accounts.length, 'ACCOUNTS'); - loadContent(); - } - }); - }); - } - - console.log('OPENING CONNECTION TO WEBSITE'); - website.open(function(err, wsClient){ - if(err){console.log(err); process.exit(1); } - console.log('OPENING CONNECTION TO ADSERVER'); - adserver.open(function(err, asClient){ - if(err){ console.log(err); process.exit(1); } - - // Get collections and remove the content - accountsCollection = asClient.collection('accounts'); - accountsCollection.remove(); - - contentCollection = asClient.collection('content'); - contentCollection.remove(); - - // insert a bunch of account docs to trigger flows - var accountDocs = []; - for(var i = 0; i < 1000; i++) { - accountDocs.push({a:i, active:true}); - } - - // insert a bunch of account docs to trigger flows - var contentDocs = []; - for(var i = 0; i < 1000; i++) { - var a_id = Math.floor(Math.random()*1000); - contentDocs.push({a:1, end_date:null, account_id:a_id}); - } - - // Just insert some test data - accountsCollection.insert(accountDocs, {safe:{w:2, wtimout:1000}}, function(err, r) { - contentCollection.insert(contentDocs, {safe:{w:2, wtimout:1000}}, function(err, r) { - // process.exit(0); - loadAccounts(); - // loadAccountsParallel(); - }); - }); - }); - }); -}); - diff --git a/node_modules/reg/node_modules/mongodb/test/manual_tests/issue_replicaset_test.js b/node_modules/reg/node_modules/mongodb/test/manual_tests/issue_replicaset_test.js deleted file mode 100644 index ed5692b..0000000 --- a/node_modules/reg/node_modules/mongodb/test/manual_tests/issue_replicaset_test.js +++ /dev/null @@ -1,43 +0,0 @@ -var mongodb = require("../../lib/mongodb"), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 4, - socketOptions: { keepAlive: 100, timeout:6000 } -}; - -var userObjects = []; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({'user_id':i}); -} - -// Manual config -// mongod --rest --replSet mlocal --oplogSize 8 --dbpath=./d1 -// mongod --port 27018 --rest --replSet mlocal --dbpath=./d2 -// mongod --port=27019 --rest --replSet mlocal --dbpath=./d3 -// {"_id" : "mlocal", "members" : [{"_id" : 0,"host" : "localhost:27017"},{"_id" : 1,"host" : "localhost:27018"},{"_id" : 2,"host" : "localhost:27019","arbiterOnly" : true}]} - -// Replica configuration -var replSet = new mongodb.ReplSetServers( [ - new mongodb.Server( 'localhost', 27017, { auto_reconnect: true } ), - new mongodb.Server( 'localhost', 27018, { auto_reconnect: true } ), - new mongodb.Server( 'localhost', 27019, { auto_reconnect: true } ) - ], - {rs_name:'mlocal'} -); - -var queryCount = 0; -var users; -var db = new mongodb.Db("data", replSet); -db.on("error", function(err) { - console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") - console.dir(err) -}) - -db.open(function(err, client){ - // Just close the connection - db.close(); -}); diff --git a/node_modules/reg/node_modules/mongodb/test/manual_tests/manual_larger_queries.js b/node_modules/reg/node_modules/mongodb/test/manual_tests/manual_larger_queries.js deleted file mode 100644 index 09aceeb..0000000 --- a/node_modules/reg/node_modules/mongodb/test/manual_tests/manual_larger_queries.js +++ /dev/null @@ -1,137 +0,0 @@ -var mongodb = require("../../lib/mongodb"), - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 4, - socketOptions: { keepAlive: 100, timeout:30000 } -}; - -var userObjects = []; -var counter = 0; -var counter2 = 0; -var maxUserId = 10000; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({a:true, b:true}); -} - -RS = new ReplicaSetManager({retries:120, secondary_count:1, passive_count:0, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new mongodb.ReplSetServers( [ - new mongodb.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, read_secondary:true, readPreference:mongodb.Server.READ_SECONDARY} - ); - - var collA; - var collB; - - var db = new mongodb.Db("data", replSet); - db.open(function(err, client){ - console.log("Connected"); - if(err != null) { - console.dir(err); - return; - } - - var userCollection = client.collection('users'); - var accountCollection = client.collection('accounts'); - - // Generate a bunch of fake accounts - var accountDocs = []; - for(var i = 0; i < 10000; i++) { - accountDocs.push({ - account_id:i, - 'somedata': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata2': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata3': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata4': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata5': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata6': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata7': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata8': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata9': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad' - }) - } - - // Generate a bunch of false users - var userDocs = []; - for(var i = 0; i < maxUserId; i++) { - // Generate a random number of account ids - var numberOfAccounts = Math.floor(Math.random(10000)); - // Generate an array of random numbers - var accountIds = []; - for(var j = 0; j < numberOfAccounts; j++) { - numberOfAccounts.push(Math.floor(Math.random(10000))); - } - - // Generate a user - userDocs.push({ - user_id:i, - ids:accountIds, - 'somedata': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata2': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata3': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata4': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata5': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata6': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata7': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata8': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad', - 'somedata9': 'dfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaaddfdfdsaaad' - }) - } - - // Insert all the docs - userCollection.insert(userDocs, {safe:true}, function(err, result) { - console.dir(err); - - accountCollection.insert(accountDocs, {safe:true}, function(err, result) { - console.dir(err); - - var timeoutFunc = function() { - lookup(function(err, result) { - console.log("-------------------------------------------- lookedup :: " + counter); - counter = counter + 1; - process.nextTick(timeoutFunc, 1); - }); - } - - process.nextTick(timeoutFunc, 1); - }); - }); - }); - - function lookup(cb){ - // Locate a random user - db.collection('users', function(err, userCollection) { - - userCollection.findOne({user_id:Math.floor(Math.random(maxUserId))}, function(err, user) { - if(err == null && user != null) { - console.log("-------------------------------------------- findOne"); - - // Fetch all the accounts - db.collection('accounts', function(err, accountCollection) { - - accountCollection.find({account_id:{$in:user.ids}}).toArray(function(err, accounts) { - if(err == null && accounts != null) { - console.log("-------------------------------------------- findAccounts :: " + accounts.length); - cb(null, null); - } else { - console.log("-------------------------------------------- findAccounts ERROR"); - cb(err, null); - } - }); - }); - } else { - console.log("-------------------------------------------- findOne ERROR"); - cb(err, null); - } - }); - }); - } -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/manual_tests/manual_lock.js b/node_modules/reg/node_modules/mongodb/test/manual_tests/manual_lock.js deleted file mode 100644 index 33da8be..0000000 --- a/node_modules/reg/node_modules/mongodb/test/manual_tests/manual_lock.js +++ /dev/null @@ -1,84 +0,0 @@ -var mongodb = require("../../lib/mongodb"), - ReplicaSetManager = require('../../test/tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 4, - socketOptions: { keepAlive: 100, timeout:30000 } -}; - -var userObjects = []; -var counter = 0; -var counter2 = 0; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({a:true, b:true}); -} - -RS = new ReplicaSetManager({retries:120, secondary_count:1, passive_count:0, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new mongodb.ReplSetServers( [ - new mongodb.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var collA; - var collB; - - var db = new mongodb.Db("data", replSet); - db.open(function(err, client){ - console.log("Connected"); - client.collection("collA", function(err, coll){ - collA = coll; - - coll.insert(userObjects, {safe:true}, function(err, result) { - - client.collection("collB", function(err, coll){ - collB = coll; - - coll.insert(userObjects, {safe:true}, function(err, result) { - - var timeoutFunc = function() { - lookup(function(err, result) { - console.log("-------------------------------------------- lookedup") - process.nextTick(timeoutFunc, 1); - }) - } - - process.nextTick(timeoutFunc, 1); - }); - }); - }); - }); - }); - - function lookup(cb){ - var a, b; - var waiting = 2; - - collA.findOne({ a: true }, function(err, result){ - a = result; - waiting--; - if(waiting === 0){ - console.log("---------------------------------------------------------------------- collA :: " + counter); - counter = counter + 1; - cb(null, [a, b]); - } - }); - - collB.findOne({ b: true }, function(err, result){ - b = result; - waiting--; - if(waiting === 0){ - console.log("---------------------------------------------------------------------- collB :: " + counter); - counter = counter + 1; - cb(null, [a, b]); - } - }); - } -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/manual_tests/replicaset_test.js b/node_modules/reg/node_modules/mongodb/test/manual_tests/replicaset_test.js deleted file mode 100644 index fc61965..0000000 --- a/node_modules/reg/node_modules/mongodb/test/manual_tests/replicaset_test.js +++ /dev/null @@ -1,70 +0,0 @@ -var mongodb = require("../../lib/mongodb"), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 4, - socketOptions: { keepAlive: 100, timeout:6000 } -}; - -var userObjects = []; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({'user_id':i}); -} - -RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new mongodb.ReplSetServers( [ - new mongodb.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var queryCount = 0; - var users; - var db = new mongodb.Db("data", replSet); - db.on("error", function(err) { - console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") - console.dir(err) - }) - - db.open(function(err, client){ - if(err){ - console.log("[%s] %s", new Date, err.stack || err); - return; - } - - if(users){ - console.log("[%s] Reconnected?!", new Date); - return; - } - - client.collection("users", function(err, coll){ - coll.insert(userObjects, {safe:true}, function(err, result) { - users = coll; - query(); - }) - }); - }); - - function query(){ - var current = queryCount++; - console.log("[%s] #%s querying all users", new Date, current); - // setTimeout(query, 32 * 1000); - setTimeout(query, 7 * 1000); - users.find().count(function(err, all){ - if(err){ - console.log("[%s] #%s %s", new Date, current, err.stack || err); - }else{ - console.log("[%s] #%s found %s users", new Date, current, all); - } - }); - } -}); - - diff --git a/node_modules/reg/node_modules/mongodb/test/manual_tests/server_load.js b/node_modules/reg/node_modules/mongodb/test/manual_tests/server_load.js deleted file mode 100644 index 5640234..0000000 --- a/node_modules/reg/node_modules/mongodb/test/manual_tests/server_load.js +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env node -var mongo = require("../../lib/mongodb"); -var express = require("express"); -var ObjectID = mongo.ObjectID; -var DBRef = mongo.DBRef; -var util = require("util"); - -var app = express.createServer(); - -app.configure(function() { - app.set('dbconnection', { - "port": 27017, - "host": "localhost" - }); -}); - -app.renderResponse = function(res, err, data, allCount) { - res.header('Content-Type', 'application/json'); - - if(err == null) { - if(typeof allCount == "undefined") { - res.send({data: data, success: true}); - } else { - res.send({allCount: allCount, data: data, success: true}); - } - } else { - util.log(util.inspect(err)); - console.log(err.stack); - res.send({success: false, error:err.message}); - } -}; - -app.use(express.bodyParser()); -app.use(app.router); -app.use(express.logger()); -app.use(express.errorHandler({ dumpExceptions: true, showStack: true })); - -var isISO8601 = function(dString) { - var regexp = /(\d\d\d\d)(-)?(\d\d)(-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([+-])(\d\d)(:)?(\d\d))?/; - if (dString.toString().match(new RegExp(regexp))) { - return true; - } - else - { - return false; - } -}; - - -var decodeField = function(value) { - if(value == null) - return null; - - if(typeof value == "object" && value['namespace'] && value['oid']) { - if(/^[0-9a-fA-F]{24}$/.test(value['oid'])) - return new DBRef(value['namespace'], new ObjectID(value['oid'])); - else - return new DBRef(value['namespace'], value['oid']); - } - - if(isISO8601(value)) - return new Date(value); - - return value; -}; - -var deepDecode = function(obj) { - for(var i in obj) - { - if(obj[i] == null) { - // do nothing - } - else if(i == "_id" && /^[0-9a-fA-F]{24}$/.test(obj[i])) { - obj[i] = new ObjectID(obj[i]); - } - else if(typeof obj[i] == "object" && typeof obj[i]['namespace'] == "undefined" && typeof obj[i]['oid'] == "undefined") { - deepDecode(obj[i]); - } - else { - obj[i] = decodeField(obj[i]); - } - } -}; - -db = null; -var openConnection = function(dbname, config, callback) { - if(db) { - callback(null, db); - } - else { - var target; - target = new mongo.Server(config.host, config.port, {'auto_reconnect':true, 'poolSize':4}); - db = new mongo.Db(dbname, target, {native_parser:false}); - db.open(callback); - } -} - -var listCommand = function (target, spec, options, next){ - deepDecode(spec); - openConnection(target.db, target.connection, function(err,db) { - if(err) { next(err); return; } - // open collection - db.collection(target.collection, function(err, collection) { - - if(spec._id) { - collection.findOne(spec, options, function(err, doc){ - next(err, doc); - }); - } - else - { - // console.dir(options) - options['limit'] = 10; - - collection.find(spec, options, function(err, cursor) - { - - cursor.toArray(function(err, docs) - { - next(err, docs); - //db.close(); - }); - }); - } - }); - }); -} - -app.get('/:db/:collection/:id?', function(req, res, next) -{ - var spec = req.query.query? JSON.parse(req.query.query) : {}; - spec = req.query.spec? JSON.parse(req.query.spec) : spec; - - if(req.params.id) - spec._id = req.params.id; - - // JSON decode options - var options = req.query.options?JSON.parse(req.query.options) : {}; - - listCommand({ - connection: app.set("dbconnection"), - db: req.params.db, - collection: req.params.collection - }, - spec, - options, - function(err, docs, allCount) { - app.renderResponse(res, err, docs, allCount); - }); -}); - -app.listen(9999, '127.0.0.1'); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/manual_tests/simple_test.js b/node_modules/reg/node_modules/mongodb/test/manual_tests/simple_test.js deleted file mode 100644 index 55b561e..0000000 --- a/node_modules/reg/node_modules/mongodb/test/manual_tests/simple_test.js +++ /dev/null @@ -1,23 +0,0 @@ -var Db = require('../../lib/mongodb').Db, - Server = require('../../lib/mongodb').Server; - -var _db = new Db('mydb', new Server('localhost', 27017, {auto_reconnect: true, poolSize: 2})); -_db.open(function(err, db) { - - db.collection('coll1', function(err, coll) { - var expireDate = new Date(); - expireDate.setHours(expireDate.getHours() + 24); - coll.remove({valid_to: {$lt: expireDate}}, {safe: true}, function(err) { - console.log('Deleted the items'); - }); - }); - - db.collection('coll2', function(err, coll) { - coll.find({}, {}, function(err, cursor) { - console.log('Turning the cursor into an array'); - cursor.toArray(function(err, docs) { - console.log('Got the array'); - }); - }); - }); -}); \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/manual_tests/single_test.js b/node_modules/reg/node_modules/mongodb/test/manual_tests/single_test.js deleted file mode 100644 index 662b921..0000000 --- a/node_modules/reg/node_modules/mongodb/test/manual_tests/single_test.js +++ /dev/null @@ -1,61 +0,0 @@ -var mongodb = require("../../lib/mongodb"), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 1, - // socketOptions: { keepAlive: 100, timeout:8000 } - socketOptions: { timeout:8000 } -}; - -var userObjects = []; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({'user_id':i}); -} - -var queryCount = 0; -var replSet = new mongodb.Server( 'localhost', 27017, options); - -var users; -var db = new mongodb.Db("data", replSet); -db.on("error", function(err) { - console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@") - console.dir(err) -}) - -db.open(function(err, client){ - if(err){ - console.log("[%s] %s", new Date, err.stack || err); - return; - } - - if(users){ - console.log("[%s] Reconnected?!", new Date); - return; - } - - client.collection("users", function(err, coll){ - coll.remove({}, {safe:true}, function(err) { - coll.insert(userObjects, {safe:true}, function(err, result) { - users = coll; - query(); - }) - }); - }); -}); - -function query(){ - var current = queryCount++; - console.log("[%s] #%s querying all users", new Date, current); - // setTimeout(query, 32 * 1000); - setTimeout(query, 7 * 1000); - users.find().count(function(err, all){ - if(err){ - console.log("[%s] #%s %s", new Date, current, err.stack || err); - }else{ - console.log("[%s] #%s found %s users", new Date, current, all); - } - }); -} \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/manual_tests/test.js b/node_modules/reg/node_modules/mongodb/test/manual_tests/test.js deleted file mode 100644 index 006668b..0000000 --- a/node_modules/reg/node_modules/mongodb/test/manual_tests/test.js +++ /dev/null @@ -1,83 +0,0 @@ -var mongodb = require("./lib/mongodb"), - ReplicaSetManager = require('./test/tools/replica_set_manager').ReplicaSetManager; - -var options = { - auto_reconnect: true, - poolSize: 4, - socketOptions: { keepAlive: 100, timeout:30000 } -}; - -var userObjects = []; - -// Build user array -for(var i = 0; i < 122; i++) { - userObjects.push({'user_id':i}); -} - -// var replSet = new mongodb.ReplSetServers([ -// new mongodb.Server("mongo-1", 27017, options), -// new mongodb.Server("mongo-2", 27017, options), -// new mongodb.Server("mongo-3", 27017, options) -// ]); - -RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); -RS.startSet(true, function(err, result) { - // Replica configuration - var replSet = new mongodb.ReplSetServers( [ - new mongodb.Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new mongodb.Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - // {rs_name:RS.name, strategy:'ping'} - // {rs_name:RS.name, strategy:'statistical'} - ); - - var users; - var db = new mongodb.Db("data", replSet); - db.open(function(err, client){ - if(err){ - console.log("[%s] %s", new Date, err.stack || err); - return; - } - - if(users){ - console.log("[%s] Reconnected?!", new Date); - return; - } - - client.collection("users", function(err, coll){ - console.log("Connected"); - coll.insert(userObjects, {safe:true}, function(err, result) { - users = coll; - query(); - }) - }); - // client.collection("users", function(err, users){ - // console.log("Connected"); - // db.users = users; - // query(); - // }); - }); - - function query(){ - console.log("[%s] querying all users", new Date); - // setTimeout(query, 70 * 60 * 1000); - setTimeout(query, 32 * 1000); - db.collection('users', function(err, coll) { - if(err){ - console.log("[0] :: [%s] %s", new Date, err.stack || err); - } - - coll.find().count(function(err, all){ - if(err){ - console.log("[1] :: [%s] %s", new Date, err.stack || err); - }else{ - console.log("[2] :: [%s] found %s users", new Date, all); - } - }); - }) - } -}); - - diff --git a/node_modules/reg/node_modules/mongodb/test/map_reduce_test.js b/node_modules/reg/node_modules/mongodb/test/map_reduce_test.js deleted file mode 100644 index 032f4d8..0000000 --- a/node_modules/reg/node_modules/mongodb/test/map_reduce_test.js +++ /dev/null @@ -1,517 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Code = require('../lib/mongodb/bson/code').Code, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * A whole lot of different wayt to execute the group command - * - * @_class collection - * @_function group - */ -exports.shouldCorrectlyExecuteGroupFunction = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection - db.createCollection('test_group', function(err, collection) { - - // Peform a simple group by on an empty collection - collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", function(err, results) { - test.deepEqual([], results); - - // Trigger some inserts on the collection - collection.insert([{'a':2}, {'b':5}, {'a':1}], {safe:true}, function(err, ids) { - - // Perform a group count - collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }" - , function(err, results) { - test.equal(3, results[0].count); - - // Pefrom a group count using the eval method - collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }" - , false, function(err, results) { - test.equal(3, results[0].count); - - // Group with a conditional - collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }" - , function(err, results) { - // Results - test.equal(1, results[0].count); - - // Group with a conditional using the EVAL method - collection.group([], {'a':{'$gt':1}}, {"count":0}, "function (obj, prev) { prev.count++; }" - , false, function(err, results) { - // Results - test.equal(1, results[0].count); - - // Insert some more test data - collection.insert([{'a':2}, {'b':3}], {safe:true}, function(err, ids) { - - // Do a Group by field a - collection.group(['a'], {}, {"count":0}, "function (obj, prev) { prev.count++; }" - , function(err, results) { - // Results - test.equal(2, results[0].a); - test.equal(2, results[0].count); - test.equal(null, results[1].a); - test.equal(2, results[1].count); - test.equal(1, results[2].a); - test.equal(1, results[2].count); - - // Do a Group by field a - collection.group({'a':true}, {}, {"count":0}, function (obj, prev) { prev.count++; } - , true, function(err, results) { - // Results - test.equal(2, results[0].a); - test.equal(2, results[0].count); - test.equal(null, results[1].a); - test.equal(2, results[1].count); - test.equal(1, results[2].a); - test.equal(1, results[2].count); - - // Correctly handle illegal function - collection.group([], {}, {}, "5 ++ 5", function(err, results) { - test.ok(err instanceof Error); - test.ok(err.message != null); - - // Use a function to select the keys used to group by - var keyf = function(doc) { return {a: doc.a}; }; - collection.group(keyf, {a: {$gt: 0}}, {"count": 0, "value": 0} - , function(obj, prev) { prev.count++; prev.value += obj.a; }, true, function(err, results) { - // Results - results.sort(function(a, b) { return b.count - a.count; }); - test.equal(2, results[0].count); - test.equal(2, results[0].a); - test.equal(4, results[0].value); - test.equal(1, results[1].count); - test.equal(1, results[1].a); - test.equal(1, results[1].value); - - // Correctly handle illegal function when using the EVAL method - collection.group([], {}, {}, "5 ++ 5", false, function(err, results) { - test.ok(err instanceof Error); - test.ok(err.message != null); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldCorrectlyExecuteGroupFunctionWithFinalizeFunction = function(test) { - client.createCollection('test_group2', function(err, collection) { - collection.group([], {}, {"count":0}, "function (obj, prev) { prev.count++; }", true, function(err, results) { - test.deepEqual([], results); - - // Trigger some inserts - collection.insert([{'a':2}, {'b':5, 'a':0}, {'a':1}, {'c':2, 'a':0}], {safe:true}, function(err, ids) { - collection.group([], {}, {count: 0, running_average: 0} - , function (doc, out) { - out.count++; - out.running_average += doc.a; - } - , function(out) { - out.average = out.running_average / out.count; - }, true, function(err, results) { - test.equal(3, results[0].running_average) - test.equal(0.75, results[0].average) - test.done(); - }); - }); - }); - }); -} - -/** - * A simple map reduce example - * - * @_class collection - * @_function mapReduce - */ -exports.shouldPerformSimpleMapReduceFunctions = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection - db.createCollection('test_map_reduce_functions', function(err, collection) { - - // Insert some documents to perform map reduce over - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - - // Map function - var map = function() { emit(this.user_id, 1); }; - // Reduce function - var reduce = function(k,vals) { return 1; }; - - // Peform the map reduce - collection.mapReduce(map, reduce, function(err, collection) { - // Mapreduce returns the temporary collection with the results - collection.findOne({'_id':1}, function(err, result) { - test.equal(1, result.value); - - collection.findOne({'_id':2}, function(err, result) { - test.equal(1, result.value); - - db.close(); - test.done(); - }); - }); - }); - }); - }); - }); -} - -/** - * A simple map reduce example using the inline output type on MongoDB > 1.7.6 - * - * @_class collection - * @_function mapReduce - */ -exports.shouldPerformMapReduceFunctionInline = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Parse version of server if available - db.admin().serverInfo(function(err, result){ - - // Only run if the MongoDB version is higher than 1.7.6 - if(parseInt((result.version.replace(/\./g, ''))) >= 176) { - - // Create a test collection - db.createCollection('test_map_reduce_functions_inline', function(err, collection) { - - // Insert some test documents - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - - // Map function - var map = function() { emit(this.user_id, 1); }; - // Reduce function - var reduce = function(k,vals) { return 1; }; - - // Execute map reduce and return results inline - collection.mapReduce(map, reduce, {out : {inline: 1}}, function(err, results) { - test.equal(2, results.length); - - db.close(); - test.done(); - }); - }); - }); - } else { - test.done(); - } - }); - }); -} - -/** -* Mapreduce different test with a provided scope containing a javascript function. -* -* @_class collection -* @_function mapReduce -*/ -exports.shouldPerformMapReduceInContext = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Create a test collection - client.createCollection('test_map_reduce_functions_scope', function(err, collection) { - - // Insert some test documents - collection.insert([{'user_id':1, 'timestamp':new Date()} - , {'user_id':2, 'timestamp':new Date()}], {safe:true}, function(err, r) { - - // Map function - var map = function(){ - emit(test(this.timestamp.getYear()), 1); - } - - // Reduce function - var reduce = function(k, v){ - count = 0; - for(i = 0; i < v.length; i++) { - count += v[i]; - } - return count; - } - - // Javascript function available in the map reduce scope - var t = function(val){ return val+1; } - - // Execute the map reduce with the custom scope - collection.mapReduce(map, reduce, {scope:{test:new Code(t.toString())} - , out: {replace:'replacethiscollection'}}, function(err, collection) { - - // Find all entries in the map-reduce collection - collection.find().toArray(function(err, results) { - test.equal(2, results[0].value) - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** -* Mapreduce tests -* @ignore -*/ -exports.shouldPerformMapReduceWithStringFunctions = function(test) { - client.createCollection('test_map_reduce', function(err, collection) { - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - // String functions - var map = "function() { emit(this.user_id, 1); }"; - var reduce = "function(k,vals) { return 1; }"; - - collection.mapReduce(map, reduce, function(err, collection) { - collection.findOne({'_id':1}, function(err, result) { - test.equal(1, result.value); - }); - - collection.findOne({'_id':2}, function(err, result) { - test.equal(1, result.value); - test.done(); - }); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldPerformMapReduceWithParametersBeingFunctions = function(test) { - client.createCollection('test_map_reduce_with_functions_as_arguments', function(err, collection) { - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - // String functions - var map = function() { emit(this.user_id, 1); }; - var reduce = function(k,vals) { return 1; }; - - collection.mapReduce(map, reduce, function(err, collection) { - collection.findOne({'_id':1}, function(err, result) { - test.equal(1, result.value); - }); - collection.findOne({'_id':2}, function(err, result) { - test.equal(1, result.value); - test.done(); - }); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldPerformMapReduceWithCodeObjects = function(test) { - client.createCollection('test_map_reduce_with_code_objects', function(err, collection) { - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - // String functions - var map = new Code("function() { emit(this.user_id, 1); }"); - var reduce = new Code("function(k,vals) { return 1; }"); - - collection.mapReduce(map, reduce, function(err, collection) { - collection.findOne({'_id':1}, function(err, result) { - test.equal(1, result.value); - }); - collection.findOne({'_id':2}, function(err, result) { - test.equal(1, result.value); - test.done(); - }); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldPerformMapReduceWithOptions = function(test) { - client.createCollection('test_map_reduce_with_options', function(err, collection) { - collection.insert([{'user_id':1}, {'user_id':2}, {'user_id':3}], {safe:true}, function(err, r) { - // String functions - var map = new Code("function() { emit(this.user_id, 1); }"); - var reduce = new Code("function(k,vals) { return 1; }"); - - collection.mapReduce(map, reduce, {'query': {'user_id':{'$gt':1}}}, function(err, collection) { - collection.count(function(err, count) { - test.equal(2, count); - - collection.findOne({'_id':2}, function(err, result) { - test.equal(1, result.value); - }); - collection.findOne({'_id':3}, function(err, result) { - test.equal(1, result.value); - test.done(); - }); - }); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldHandleMapReduceErrors = function(test) { - client.createCollection('test_map_reduce_error', function(err, collection) { - collection.insert([{'user_id':1}, {'user_id':2}, {'user_id':3}], {safe:true}, function(err, r) { - // String functions - var map = new Code("function() { throw 'error'; }"); - var reduce = new Code("function(k,vals) { throw 'error'; }"); - - collection.mapReduce(map, reduce, {'query': {'user_id':{'$gt':1}}}, function(err, r) { - test.ok(err != null); - test.done(); - }); - }); - }); -} - -/** -* @ignore -*/ -exports.shouldCorrectlyReturnNestedKeys = function(test) { - var start = new Date().setTime(new Date().getTime() - 10000); - var end = new Date().setTime(new Date().getTime() + 10000); - - var keys = { - "data.lastname": true - }; - - var condition = { - "data.date": { - $gte: start, - $lte: end - } - }; - - condition = {} - - var initial = { - count : 0 - }; - - var reduce = function(doc, output) { - output.count++; - } - - // Execute the group - client.createCollection('data', function(err, collection) { - collection.insert({ - data: { - lastname:'smith', - date:new Date() - } - }, {safe:true}, function(err, result) { - - // Execute the group - collection.group(keys, condition, initial, reduce, true, function(err, r) { - test.equal(1, r[0].count) - test.equal('smith', r[0]['data.lastname']); - test.done(); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/multiple_dbs_on_connection_pool_test.js b/node_modules/reg/node_modules/mongodb/test/multiple_dbs_on_connection_pool_test.js deleted file mode 100644 index 5e1fa24..0000000 --- a/node_modules/reg/node_modules/mongodb/test/multiple_dbs_on_connection_pool_test.js +++ /dev/null @@ -1,256 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - ServerManager = require('../test/tools/server_manager').ServerManager, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyEmitErrorOnAllDbsOnPoolClose = function(test) { - if(process.platform !== 'linux') { - var db = new Db('tests', new Server("127.0.0.1", 27027, {auto_reconnect: true}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - // All inserted docs - var docs = []; - var errs = []; - var insertDocs = []; - var numberOfCloses = 0; - - // Start server - var serverManager = new ServerManager({auth:false, purgedirectories:true, journal:false, start_port:27027}) - serverManager.start(false, function() { - db.on("close", function(err) { - numberOfCloses = numberOfCloses + 1; - }) - - db.open(function(err, db) { - db.createCollection('shouldCorrectlyErrorOnAllDbs', function(err, collection) { - test.equal(null, err); - - collection.insert({a:1}, {safe:true}, function(err, result) { - test.equal(null, err); - - // Open a second db - var db2 = db.db('tests_2'); - // Add a close handler - db2.on("close", function(err) { - numberOfCloses = numberOfCloses + 1; - }); - - db.serverConfig.connectionPool.openConnections[0].connection.destroy(); - - // Kill server and end test - serverManager.stop(9, function() { - test.equal(2, numberOfCloses) - test.done(); - }); - }); - }); - }); - }); - } else { - test.done(); - } -} - -/** - * Test the auto connect functionality of the db - * - * @ignore - */ -exports.shouldCorrectlyUseSameConnectionsForTwoDifferentDbs = function(test) { - var second_test_database = new Db(MONGODB + "_2", new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null), retryMiliSeconds:50}); - // Just create second database - second_test_database.open(function(err, second_test_database) { - // Close second database - second_test_database.close(); - // Let's grab a connection to the different db resusing our connection pools - var secondDb = client.db(MONGODB + "_2"); - secondDb.createCollection('shouldCorrectlyUseSameConnectionsForTwoDifferentDbs', function(err, collection) { - // Insert a dummy document - collection.insert({a:20}, {safe: true}, function(err, r) { - test.equal(null, err); - - // Query it - collection.findOne({}, function(err, item) { - test.equal(20, item.a); - - // Use the other db - client.createCollection('shouldCorrectlyUseSameConnectionsForTwoDifferentDbs', function(err, collection) { - // Insert a dummy document - collection.insert({b:20}, {safe: true}, function(err, r) { - test.equal(null, err); - - // Query it - collection.findOne({}, function(err, item) { - test.equal(20, item.b); - - // Drop the second db - secondDb.dropDatabase(function(err, item) { - test.equal(null, err); - test.done(); - }) - }) - }); - }); - }) - }); - }); - }); -} - -/** - * Test the auto connect functionality of the db - * - * @ignore - */ -exports.shouldCorrectlyUseSameConnectionsForTwoDifferentDbs = function(test) { - var second_test_database = new Db(MONGODB + "_2", new Server("127.0.0.1", 27017, {auto_reconnect: true, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null), retryMiliSeconds:50}); - // Just create second database - second_test_database.open(function(err, second_test_database) { - // Close second database - second_test_database.close(); - // Let's grab a connection to the different db resusing our connection pools - var secondDb = client.db(MONGODB + "_2"); - secondDb.createCollection('shouldCorrectlyUseSameConnectionsForTwoDifferentDbs', function(err, collection) { - // Insert a dummy document - collection.insert({a:20}, {safe: true}, function(err, r) { - test.equal(null, err); - - // Query it - collection.findOne({}, function(err, item) { - test.equal(20, item.a); - - // Use the other db - client.createCollection('shouldCorrectlyUseSameConnectionsForTwoDifferentDbs', function(err, collection) { - // Insert a dummy document - collection.insert({b:20}, {safe: true}, function(err, r) { - test.equal(null, err); - - // Query it - collection.findOne({}, function(err, item) { - test.equal(20, item.b); - - // Drop the second db - secondDb.dropDatabase(function(err, item) { - test.equal(null, err); - test.done(); - }) - }) - }); - }); - }) - }); - }); - }); -} - -/** - * Simple example connecting to two different databases sharing the socket connections below. - * - * @_class db - * @_function db - */ -exports.shouldCorrectlyShareConnectionPoolsAcrossMultipleDbInstances = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - test.equal(null, err); - - // Reference a different database sharing the same connections - // for the data transfer - var secondDb = db.db("integration_tests_2"); - - // Fetch the collections - var multipleColl1 = db.collection("multiple_db_instances"); - var multipleColl2 = secondDb.collection("multiple_db_instances"); - - // Write a record into each and then count the records stored - multipleColl1.insert({a:1}, {safe:true}, function(err, result) { - multipleColl2.insert({a:1}, {safe:true}, function(err, result) { - - // Count over the results ensuring only on record in each collection - multipleColl1.count(function(err, count) { - test.equal(1, count); - - multipleColl2.count(function(err, count) { - test.equal(1, count); - - db.close(); - test.done(); - }); - }); - }); - }); - }); -} - - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/objectid_test.js b/node_modules/reg/node_modules/mongodb/test/objectid_test.js deleted file mode 100644 index ef51288..0000000 --- a/node_modules/reg/node_modules/mongodb/test/objectid_test.js +++ /dev/null @@ -1,351 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyGenerateObjectID = function(test) { - var number_of_tests_done = 0; - - client.collection('test_object_id_generation.data', function(err, collection) { - // Insert test documents (creates collections and test fetch by query) - collection.insert({name:"Fred", age:42}, {safe:true}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]['_id'].toHexString().length == 24); - // Locate the first document inserted - collection.findOne({name:"Fred"}, function(err, document) { - test.equal(ids[0]['_id'].toHexString(), document._id.toHexString()); - number_of_tests_done++; - }); - }); - - // Insert another test document and collect using ObjectId - collection.insert({name:"Pat", age:21}, {safe:true}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]['_id'].toHexString().length == 24); - // Locate the first document inserted - collection.findOne(ids[0]['_id'], function(err, document) { - test.equal(ids[0]['_id'].toHexString(), document._id.toHexString()); - number_of_tests_done++; - }); - }); - - // Manually created id - var objectId = new ObjectID(null); - // Insert a manually created document with generated oid - collection.insert({"_id":objectId, name:"Donald", age:95}, {safe:true}, function(err, ids) { - test.equal(1, ids.length); - test.ok(ids[0]['_id'].toHexString().length == 24); - test.equal(objectId.toHexString(), ids[0]['_id'].toHexString()); - // Locate the first document inserted - collection.findOne(ids[0]['_id'], function(err, document) { - test.equal(ids[0]['_id'].toHexString(), document._id.toHexString()); - test.equal(objectId.toHexString(), document._id.toHexString()); - number_of_tests_done++; - }); - }); - }); - - var intervalId = setInterval(function() { - if(number_of_tests_done == 3) { - clearInterval(intervalId); - test.done(); - } - }, 100); -} - -/** - * Generate 12 byte binary string representation using a second based timestamp or - * default value - * - * @_class objectid - * @_function getTimestamp - * @ignore - */ -exports.shouldCorrectlyGenerate12ByteStringFromTimestamp = function(test) { - // Get a timestamp in seconds - var timestamp = Math.floor(new Date().getTime()/1000); - // Create a date with the timestamp - var timestampDate = new Date(timestamp*1000); - - // Create a new ObjectID with a specific timestamp - var objectId = new ObjectID(timestamp); - - // Get the timestamp and validate correctness - test.equal(timestampDate.toString(), objectId.getTimestamp().toString()); - test.done(); -} - -/** - * Generate a 24 character hex string representation of the ObjectID - * - * @_class objectid - * @_function toHexString - * @ignore - */ -exports.shouldCorrectlyRetrieve24CharacterHexStringFromToString = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Verify that the hex string is 24 characters long - test.equal(24, objectId.toHexString().length); - test.done(); -} - -/** - * Get and set the generation time for an ObjectID - * - * @_class objectid - * @_function generationTime - * @ignore - */ -exports.shouldCorrectlyGetAndSetObjectIDUsingGenerationTimeProperty = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Get the generation time - var generationTime = objectId.generationTime; - // Add 1000 miliseconds to the generation time - objectId.generationTime = generationTime + 1000; - - // Create a timestamp - var timestampDate = new Date(); - timestampDate.setTime((generationTime + 1000) * 1000); - - // Get the timestamp and validate correctness - test.equal(timestampDate.toString(), objectId.getTimestamp().toString()); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyRetrieve24CharacterHexStringFromToString = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Verify that the hex string is 24 characters long - test.equal(24, objectId.toString().length); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyRetrieve24CharacterHexStringFromToString = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Verify that the hex string is 24 characters long - test.equal(24, objectId.toJSON().length); - test.done(); -} - -/** - * Convert a ObjectID into a hex string representation and then back to an ObjectID - * - * @_class objectid - * @_function ObjectID.createFromHexString - * @ignore - */ -exports.shouldCorrectlyTransformObjectIDToAndFromHexString = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Convert the object id to a hex string - var originalHex = objectId.toHexString(); - // Create a new ObjectID using the createFromHexString function - var newObjectId = new ObjectID.createFromHexString(originalHex) - // Convert the new ObjectID back into a hex string using the toHexString function - var newHex = newObjectId.toHexString(); - // Compare the two hex strings - test.equal(originalHex, newHex); - test.done(); -} - -/** - * Compare two different ObjectID's using the equals method - * - * @_class objectid - * @_function equals - * @ignore - */ -exports.shouldCorrectlyTransformObjectIDToAndFromHexString = function(test) { - // Create a new ObjectID - var objectId = new ObjectID(); - // Create a new ObjectID Based on the first ObjectID - var objectId2 = new ObjectID(objectId.id); - // Create another ObjectID - var objectId3 = new ObjectID(); - // objectId and objectId2 should be the same - test.ok(objectId.equals(objectId2)); - // objectId and objectId2 should be different - test.ok(!objectId.equals(objectId3)); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCreateOIDNotUsingObjectID = function(test) { - client.createCollection('test_non_oid_id', function(err, collection) { - var date = new Date(); - date.setUTCDate(12); - date.setUTCFullYear(2009); - date.setUTCMonth(11 - 1); - date.setUTCHours(12); - date.setUTCMinutes(0); - date.setUTCSeconds(30); - - collection.insert({'_id':date}, {safe:true}, function(err, ids) { - collection.find({'_id':date}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(("" + date), ("" + items[0]._id)); - - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyGenerateObjectIDFromTimestamp = function(test) { - var timestamp = Math.floor(new Date().getTime()/1000); - var objectID = new ObjectID(timestamp); - var time2 = objectID.generationTime; - test.equal(timestamp, time2); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyCreateAnObjectIDAndOverrideTheTimestamp = function(test) { - var timestamp = 1000; - var objectID = new ObjectID(); - var id1 = objectID.id; - // Override the timestamp - objectID.generationTime = timestamp - var id2 = objectID.id; - // Check the strings - test.equal(id1.substr(4), id2.substr(4)); - test.done(); -} - -/** - * @ignore - */ -exports.shouldCorrectlyInsertWithObjectId = function(test) { - client.createCollection('shouldCorrectlyInsertWithObjectId', function(err, collection) { - collection.insert({}, {safe:true}, function(err, ids) { - setTimeout(function() { - collection.insert({}, {safe:true}, function(err, ids) { - collection.find().toArray(function(err, items) { - var compareDate = new Date(); - - // Date 1 - var date1 = new Date(); - date1.setTime(items[0]._id.generationTime * 1000); - // Date 2 - var date2 = new Date(); - date2.setTime(items[1]._id.generationTime * 1000); - - // Compare - test.equal(compareDate.getFullYear(), date1.getFullYear()); - test.equal(compareDate.getDate(), date1.getDate()); - test.equal(compareDate.getMonth(), date1.getMonth()); - test.equal(compareDate.getHours(), date1.getHours()); - - test.equal(compareDate.getFullYear(), date2.getFullYear()); - test.equal(compareDate.getDate(), date2.getDate()); - test.equal(compareDate.getMonth(), date2.getMonth()); - test.equal(compareDate.getHours(), date2.getHours()); - // Let's close the db - test.done(); - }); - }); - }, 2000); - }); - }); -} - -/** - * Show the usage of the Objectid createFromTime function - * - * @_class objectid - * @_function ObjectID.createFromTime - * @ignore - */ -exports.shouldCorrectlyTransformObjectIDToAndFromHexString = function(test) { - var objectId = ObjectID.createFromTime(1); - test.equal("000000010000000000000000", objectId.toHexString()); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/raw_test.js b/node_modules/reg/node_modules/mongodb/test/raw_test.js deleted file mode 100644 index c08f9a2..0000000 --- a/node_modules/reg/node_modules/mongodb/test/raw_test.js +++ /dev/null @@ -1,397 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - ObjectID = require('../lib/mongodb/bson/objectid').ObjectID, - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlySaveDocumentsAndReturnAsRaw = function(test) { - client.createCollection('shouldCorrectlySaveDocumentsAndReturnAsRaw', function(err, collection) { - // Insert some documents - collection.insert([{a:1}, {b:2000}, {c:2.3}], {safe:true}, function(err, result) { - // You have to pass at least query + fields before passing options - collection.find({}, null, {raw:true}).toArray(function(err, items) { - var objects = []; - for(var i = 0; i < items.length; i++) { - test.ok(items[i] instanceof Buffer); - objects.push(client.bson.deserialize(items[i])); - } - - test.equal(1, objects[0].a); - test.equal(2000, objects[1].b); - test.equal(2.3, objects[2].c); - - // Execute findOne - collection.findOne({a:1}, {raw:true}, function(err, item) { - test.ok(item instanceof Buffer); - var object = client.bson.deserialize(item); - test.equal(1, object.a) - test.done(); - }) - }) - }) - }); -} - -exports.shouldCorrectlyRemoveDocumentAndReturnRaw = function(test) { - client.createCollection('shouldCorrectlyRemoveDocumentAndReturnRaw', function(err, collection) { - // Insert some documents - collection.insert([{a:1}, {b:2000}, {c:2.3}], {safe:true}, function(err, result) { - // Let's create a raw delete command - var queryObject = {b:2000}; - // Create raw bson buffer - var rawQueryObject = new Buffer(client.bson.calculateObjectSize(queryObject)); - client.bson.serializeWithBufferAndIndex(queryObject, false, rawQueryObject, 0); - - // Update the document and return the raw new document - collection.remove(rawQueryObject, {safe:true}, function(err, numberOfDeleted) { - test.equal(1, numberOfDeleted); - - collection.findOne({b:2000}, function(err, item) { - test.equal(null, item) - test.done(); - }); - }); - }); - }); -} - -exports.shouldCorrectlyUpdateDocumentAndReturnRaw = function(test) { - client.createCollection('shouldCorrectlyUpdateDocumentAndReturnRaw', function(err, collection) { - // Insert some documents - collection.insert([{a:1}, {b:2000}, {c:2.3}], {safe:true}, function(err, result) { - // Let's create a raw delete command - var selectorObject = {b:2000}; - // Create raw bson buffer - var rawSelectorObject = new Buffer(client.bson.calculateObjectSize(selectorObject)); - client.bson.serializeWithBufferAndIndex(selectorObject, false, rawSelectorObject, 0); - // Let's create a raw delete command - var updateObject = {"$set":{c:2}}; - // Create raw bson buffer - var rawUpdateObject = new Buffer(client.bson.calculateObjectSize(updateObject)); - client.bson.serializeWithBufferAndIndex(updateObject, false, rawUpdateObject, 0); - // Update the document and return the raw new document - collection.update(rawSelectorObject, rawUpdateObject, {safe:true}, function(err, numberOfUpdated) { - test.equal(1, numberOfUpdated); - - // Query the document - collection.find({}, {}, {raw:true}).toArray(function(err, items) { - var objects = []; - for(var i = 0; i < items.length; i++) { - test.ok(items[i] instanceof Buffer); - objects.push(client.bson.deserialize(items[i])); - } - - test.equal(1, objects[0].a); - test.equal(2.3, objects[1].c); - test.equal(2000, objects[2].b); - test.equal(2, objects[2].c); - test.done(); - }) - }); - }); - }); -} - -exports.shouldCorreclyInsertRawDocumentAndRetrieveThem = function(test) { - client.createCollection('shouldCorreclyInsertRawDocumentAndRetrieveThem', function(err, collection) { - // Create serialized insert objects - var id = new ObjectID(); - var inputObjects = [{_id:id}, {a:1}, {b:2}, {c:4}] - var serializedObjects = []; - - // Serialize all object - for(var i = 0; i < inputObjects.length; i++) { - // Create raw bson buffer - var rawObject = new Buffer(client.bson.calculateObjectSize(inputObjects[i])); - client.bson.serializeWithBufferAndIndex(inputObjects[i], false, rawObject, 0); - serializedObjects.push(rawObject); - } - - // Insert all raw objects - collection.insert(serializedObjects, {safe:true}, function(err, result) { - test.equal(null, err); - - // Query the document - collection.find({}, {}, {raw:true}).toArray(function(err, items) { - var objects = []; - for(var i = 0; i < items.length; i++) { - test.ok(items[i] instanceof Buffer); - objects.push(client.bson.deserialize(items[i])); - } - - test.equal(id.toHexString(), objects[0]._id.toHexString()); - test.equal(1, objects[1].a); - test.equal(2, objects[2].b); - test.equal(4, objects[3].c); - test.done(); - }) - }); - }); -} - -exports.shouldCorrectlyPeformQueryUsingRaw = function(test) { - client.createCollection('shouldCorrectlyPeformQueryUsingRaw', function(err, collection) { - collection.insert([{a:1}, {b:2}, {b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Let's create a raw query object - var queryObject = {b:3}; - // Create raw bson buffer - var rawQueryObject = new Buffer(client.bson.calculateObjectSize(queryObject)); - client.bson.serializeWithBufferAndIndex(queryObject, false, rawQueryObject, 0); - - // Let's create a raw fields object - var fieldsObject = {}; - // Create raw bson buffer - var rawFieldsObject = new Buffer(client.bson.calculateObjectSize(fieldsObject)); - client.bson.serializeWithBufferAndIndex(fieldsObject, false, rawFieldsObject, 0); - - collection.find(rawQueryObject, rawFieldsObject, {raw:true}).toArray(function(err, items) { - test.equal(1, items.length); - test.ok(items[0] instanceof Buffer); - if(items[0] == null) console.dir(items) - var object = client.bson.deserialize(items[0]); - test.equal(3, object.b) - - collection.findOne(rawQueryObject, rawFieldsObject, {raw:true}, function(err, item) { - test.equal(null, err); - test.ok(item != null); - var object = client.bson.deserialize(item); - test.equal(3, object.b) - test.done(); - }); - }); - }) - }); -} - -exports.shouldCorrectlyThrowErrorsWhenIllegalySizedMessages = function(test) { - client.createCollection('shouldCorrectlyThrowErrorsWhenIllegalySizedMessages', function(err, collection) { - var illegalBuffer = new Buffer(20); - try { - collection.insert(illegalBuffer, {safe:true}, function(err, result) {}); - } catch (err) { - test.ok(err.toString().indexOf("insert") != -1); - } - - try { - collection.update(illegalBuffer, {}, function(){}) - } catch(err) { - test.ok(err.toString().indexOf("update spec") != -1); - } - - try { - collection.update({}, illegalBuffer, function(){}) - } catch(err) { - test.ok(err.toString().indexOf("update document") != -1); - } - - try { - collection.remove(illegalBuffer, function(){}) - } catch(err) { - test.ok(err.toString().indexOf("delete") != -1); - } - - try { - collection.find(illegalBuffer).toArray(function() {}) - } catch(err) { - test.ok(err.toString().indexOf("query selector") != -1); - } - - try { - collection.find({}, illegalBuffer).toArray(function() {}) - } catch(err) { - test.ok(err.toString().indexOf("query fields") != -1); - } - - try { - collection.findOne(illegalBuffer, function() {}) - } catch(err) { - test.ok(err.toString().indexOf("query selector") != -1); - } - - try { - collection.findOne({}, illegalBuffer, function() {}) - } catch(err) { - test.ok(err.toString().indexOf("query fields") != -1); - test.done(); - } - }); -} - -exports.shouldCorrectlyPeformQueryUsingRawSettingRawAtCollectionLevel = function(test) { - client.createCollection('shouldCorrectlyPeformQueryUsingRawSettingRawAtCollectionLevel', function(err, collection) { - collection.insert([{a:1}, {b:2}, {b:3}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Let's create a raw query object - var queryObject = {b:3}; - // Create raw bson buffer - var rawQueryObject = new Buffer(client.bson.calculateObjectSize(queryObject)); - client.bson.serializeWithBufferAndIndex(queryObject, false, rawQueryObject, 0); - - // Let's create a raw fields object - var fieldsObject = {}; - // Create raw bson buffer - var rawFieldsObject = new Buffer(client.bson.calculateObjectSize(fieldsObject)); - client.bson.serializeWithBufferAndIndex(fieldsObject, false, rawFieldsObject, 0); - - client.collection('shouldCorrectlyPeformQueryUsingRaw', {raw:true}, function(err, collection) { - collection.find(rawQueryObject, rawFieldsObject).toArray(function(err, items) { - test.equal(1, items.length); - test.ok(items[0] instanceof Buffer); - var object = client.bson.deserialize(items[0]); - test.equal(3, object.b) - - collection.findOne(rawQueryObject, rawFieldsObject, {raw:true}, function(err, item) { - test.equal(null, err); - test.ok(item != null); - var object = client.bson.deserialize(item); - test.equal(3, object.b) - test.done(); - }); - }); - }); - }) - }); -} - -exports.shouldCorreclyInsertRawDocumentAndRetrieveThemSettingRawAtCollectionLevel = function(test) { - client.createCollection('shouldCorreclyInsertRawDocumentAndRetrieveThemSettingRawAtCollectionLevel', {raw:true}, function(err, collection) { - // Create serialized insert objects - var id = new ObjectID(); - var inputObjects = [{_id:id}, {a:1}, {b:2}, {c:4}] - var serializedObjects = []; - - // Serialize all object - for(var i = 0; i < inputObjects.length; i++) { - // Create raw bson buffer - var rawObject = new Buffer(client.bson.calculateObjectSize(inputObjects[i])); - client.bson.serializeWithBufferAndIndex(inputObjects[i], false, rawObject, 0); - serializedObjects.push(rawObject); - } - - // Insert all raw objects - collection.insert(serializedObjects, {safe:true}, function(err, result) { - test.equal(null, err); - - // Query the document - collection.find({}, {}).toArray(function(err, items) { - var objects = []; - for(var i = 0; i < items.length; i++) { - test.ok(items[i] instanceof Buffer); - objects.push(client.bson.deserialize(items[i])); - } - - test.equal(id.toHexString(), objects[0]._id.toHexString()); - test.equal(1, objects[1].a); - test.equal(2, objects[2].b); - test.equal(4, objects[3].c); - test.done(); - }) - }); - }); -} - -exports.shouldCorrectlyUpdateDocumentAndReturnRawSettingRawAtCollectionLevel = function(test) { - client.createCollection('shouldCorrectlyUpdateDocumentAndReturnRawSettingRawAtCollectionLevel', {raw:true}, function(err, collection) { - // Insert some documents - collection.insert([{a:1}, {b:2000}, {c:2.3}], {safe:true}, function(err, result) { - // Let's create a raw delete command - var selectorObject = {b:2000}; - // Create raw bson buffer - var rawSelectorObject = new Buffer(client.bson.calculateObjectSize(selectorObject)); - client.bson.serializeWithBufferAndIndex(selectorObject, false, rawSelectorObject, 0); - // Let's create a raw delete command - var updateObject = {"$set":{c:2}}; - // Create raw bson buffer - var rawUpdateObject = new Buffer(client.bson.calculateObjectSize(updateObject)); - client.bson.serializeWithBufferAndIndex(updateObject, false, rawUpdateObject, 0); - // Update the document and return the raw new document - collection.update(rawSelectorObject, rawUpdateObject, {safe:true}, function(err, numberOfUpdated) { - test.equal(1, numberOfUpdated); - - // Query the document - collection.find({}, {}).toArray(function(err, items) { - var objects = []; - for(var i = 0; i < items.length; i++) { - test.ok(items[i] instanceof Buffer); - objects.push(client.bson.deserialize(items[i])); - } - - test.equal(1, objects[0].a); - test.equal(2.3, objects[1].c); - test.equal(2000, objects[2].b); - test.equal(2, objects[2].c); - test.done(); - }) - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/reaper_test.js b/node_modules/reg/node_modules/mongodb/test/reaper_test.js deleted file mode 100644 index 4aa86c3..0000000 --- a/node_modules/reg/node_modules/mongodb/test/reaper_test.js +++ /dev/null @@ -1,88 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlySaveUnicodeContainingDocument = function(test) { - var reaperClient = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: false, ssl:useSSL}), {reaper:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - reaperClient.open(function(err, reaperClient) { - reaperClient._lastReaperTimestamp = (new Date().getTime() - 1000000); - var con = reaperClient.serverConfig.checkoutReader(); - // Prime the reaper with a bogus call - reaperClient._callBackStore._notReplied["3"] = {start: (new Date().getTime() - 50000), 'raw': false, chained:null, connection:con}; - reaperClient._callBackStore.once("3", function(err, result) { - reaperClient.close(); - test.done(); - }) - - reaperClient.collection("test", {safe:true}, function(err, col) { - // Does not matter - }); - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/regexp_test.js b/node_modules/reg/node_modules/mongodb/test/regexp_test.js deleted file mode 100644 index 213e6ae..0000000 --- a/node_modules/reg/node_modules/mongodb/test/regexp_test.js +++ /dev/null @@ -1,126 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlyInsertSimpleRegExpDocument = function(test) { - var regexp = /foobar/i; - - client.createCollection('test_regex', function(err, collection) { - collection.insert({'b':regexp}, {safe:true}, function(err, ids) { - collection.find({}, {'fields': ['b']}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(("" + regexp), ("" + items[0].b)); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -exports.shouldCorrectlyInsertSimpleUTF8Regexp = function(test) { - var regexp = /foobaré/; - - client.createCollection('test_utf8_regex', function(err, collection) { - collection.insert({'b':regexp}, {safe:true}, function(err, ids) { - collection.find({}, {'fields': ['b']}, function(err, cursor) { - cursor.toArray(function(err, items) { - test.equal(("" + regexp), ("" + items[0].b)); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -exports.shouldCorrectlyFindDocumentsByRegExp = function(test) { - // Serialized regexes contain extra trailing chars. Sometimes these trailing chars contain / which makes - // the original regex invalid, and leads to segmentation fault. - client.createCollection('test_regex_serialization', function(err, collection) { - collection.insert({keywords: ["test", "segmentation", "fault", "regex", "serialization", "native"]}, {safe:true}, function(err, r) { - - var count = 20, - run = function(i) { - // search by regex - collection.findOne({keywords: {$all: [/ser/, /test/, /seg/, /fault/, /nat/]}}, function(err, item) { - test.equal(6, item.keywords.length); - if (i === 0) { - test.done() - } - }); - }; - // loop a few times to catch the / in trailing chars case - while (count--) { - run(count); - } - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/remove_test.js b/node_modules/reg/node_modules/mongodb/test/remove_test.js deleted file mode 100644 index 440d0bf..0000000 --- a/node_modules/reg/node_modules/mongodb/test/remove_test.js +++ /dev/null @@ -1,171 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -/** - * An example removing all documents in a collection not using safe mode - * - * @_class collection - * @_function remove - * @ignore - */ -exports.shouldRemoveAllDocumentsNoSafe = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection to insert document into - db.collection("remove_all_documents_no_safe", function(err, collection) { - - // Insert a bunch of documents - collection.insert([{a:1}, {b:2}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Remove all the document - collection.remove(); - - // Wait for a second to ensure command went through - setTimeout(function() { - - // Fetch all results - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(0, items.length); - db.close(); - test.done(); - }); - }, 1000); - }); - }) - }); -} - -/** - * An example removing a subset of documents using safe mode to ensure removal of documents - * - * @_class collection - * @_function remove - * @ignore - */ -exports.shouldRemoveSubsetOfDocumentsSafeMode = function(test) { - var db = new Db('integration_tests', new Server("127.0.0.1", 27017, - {auto_reconnect: false, poolSize: 4, ssl:useSSL}), {native_parser: native_parser}); - - // Establish connection to db - db.open(function(err, db) { - - // Fetch a collection to insert document into - db.collection("remove_subset_of_documents_safe", function(err, collection) { - - // Insert a bunch of documents - collection.insert([{a:1}, {b:2}], {safe:true}, function(err, result) { - test.equal(null, err); - - // Remove all the document - collection.remove({a:1}, {safe:true}, function(err, numberOfRemovedDocs) { - test.equal(null, err); - test.equal(1, numberOfRemovedDocs); - db.close(); - test.done(); - }); - }); - }) - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyClearOutCollection = function(test) { - client.createCollection('test_clear', function(err, r) { - client.collection('test_clear', function(err, collection) { - collection.insert({i:1}, {safe:true}, function(err, ids) { - collection.insert({i:2}, {safe:true}, function(err, ids) { - collection.count(function(err, count) { - test.equal(2, count); - // Clear the collection - collection.remove({}, {safe:true}, function(err, result) { - test.equal(2, result); - - collection.count(function(err, count) { - test.equal(0, count); - // Let's close the db - test.done(); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/replicaset/connect_test.js b/node_modules/reg/node_modules/mongodb/test/replicaset/connect_test.js deleted file mode 100644 index e10def9..0000000 --- a/node_modules/reg/node_modules/mongodb/test/replicaset/connect_test.js +++ /dev/null @@ -1,518 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server; - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 3000); - } else { - return callback(null); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -/** - * @ignore - */ -exports.shouldThrowErrorDueToSharedConnectionUsage = function(test) { - var replSet = new ReplSetServers([ - new Server('localhost', 28390, { auto_reconnect: true } ), - new Server('localhost', 28391, { auto_reconnect: true } ), - new Server('localhost', 28392, { auto_reconnect: true } ) - ] - ); - - try { - var db = new Db(MONGODB, replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - var db1 = new Db(MONGODB, replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - } catch(err) { - test.done(); - } -} - -/** - * @ignore - */ -exports.shouldCorrectlyHandleErrorWhenNoServerUpInReplicaset = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server('localhost', 28390, { auto_reconnect: true } ), - new Server('localhost', 28391, { auto_reconnect: true } ), - new Server('localhost', 28392, { auto_reconnect: true } ) - ] - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.ok(err != null); - test.done(); - }); -} - -/** - * Simple replicaset connection setup, requires a running replicaset on the correct ports - * - * @_class db - * @_function open - */ -exports.shouldCorrectlyConnectWithDefaultReplicasetNoOption = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server('localhost', 30000, { auto_reconnect: true } ), - new Server('localhost', 30001, { auto_reconnect: true } ), - new Server('localhost', 30002, { auto_reconnect: true } ) - ] - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.equal(null, err); - test.done(); - p_db.close(); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyConnectWithDefaultReplicasetNoOption = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ] - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.equal(null, err); - test.done(); - p_db.close(); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyConnectWithDefaultReplicaset = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.equal(null, err); - test.done(); - p_db.close(); - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyConnectWithDefaultReplicasetAndSocketOptionsSet = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {socketOptions:{keepAlive:100}} - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.equal(null, err); - test.equal(100, db.serverConfig.checkoutWriter().socketOptions.keepAlive) - test.done(); - p_db.close(); - }) -} - -/** - * @ignore - */ -exports.shouldEmitCloseNoCallback = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], {} - ); - - new Db('integration_test_', replSet).open(function(err, db) { - test.equal(null, err); - var dbCloseCount = 0, serverCloseCount = 0; - db.on('close', function() { ++dbCloseCount; }); - db.close(); - - setTimeout(function() { - test.equal(dbCloseCount, 1); - test.done(); - }, 2000); - }) -} - -/** - * @ignore - */ -exports.shouldEmitCloseWithCallback = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], {} - ); - - new Db('integration_test_', replSet).open(function(err, db) { - test.equal(null, err); - var dbCloseCount = 0; - db.on('close', function() { ++dbCloseCount; }); - - db.close(function() { - // Let all events fire. - process.nextTick(function() { - test.equal(dbCloseCount, 0); - test.done(); - }); - }); - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyPassErrorWhenWrongReplicaSet = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name + "-wrong"} - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - test.notEqual(null, err); - test.done(); - }) -} - -/** - * @ignore - */ -exports.shouldConnectWithPrimarySteppedDown = function(test) { - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Step down primary server - RS.stepDownPrimary(function(err, result) { - // Wait for new primary to pop up - ensureConnection(test, retries, function(err, p_db) { - - new Db('integration_test_', replSet).open(function(err, p_db) { - test.ok(err == null); - test.equal(true, p_db.serverConfig.isConnected()); - - p_db.close(); - test.done(); - }) - }); - }); -} - -/** - * @ignore - */ -exports.shouldConnectWithThirdNodeKilled = function(test) { - RS.getNodeFromPort(RS.ports[2], function(err, node) { - if(err != null) debug("shouldConnectWithThirdNodeKilled :: " + inspect(err)); - - RS.kill(node, function(err, result) { - if(err != null) debug("shouldConnectWithThirdNodeKilled :: " + inspect(err)); - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Wait for new primary to pop up - ensureConnection(test, retries, function(err, p_db) { - new Db('integration_test_', replSet).open(function(err, p_db) { - test.ok(err == null); - test.equal(true, p_db.serverConfig.isConnected()); - - p_db.close(); - test.done(); - }) - }); - }); - }); -} - -/** - * @ignore - */ -exports.shouldConnectWithSecondaryNodeKilled = function(test) { - RS.killSecondary(function(node) { - - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= caught error") - console.dir(err) - if(err.stack != null) console.log(err.stack) - test.done(); - }) - - db.open(function(err, p_db) { - test.ok(err == null); - test.equal(true, p_db.serverConfig.isConnected()); - - // Close and cleanup - p_db.close(); - test.done(); - }) - }); -} - -/** - * @ignore - */ -exports.shouldConnectWithPrimaryNodeKilled = function(test) { - RS.killPrimary(function(node) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var db = new Db('integration_test_', replSet); - ensureConnection(test, retries, function(err, p_db) { - if(err != null && err.stack != null) console.log(err.stack) - test.done(); - }); - }); -} - -/** - * @ignore - */ -exports.shouldCorrectlyBeAbleToUsePortAccessors = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldCorrectlyBeAbleToUsePortAccessors :: " + inspect(err)); - test.equal(replSet.host, p_db.serverConfig.primary.host); - test.equal(replSet.port, p_db.serverConfig.primary.port); - - p_db.close(); - test.done(); - }) -} - -/** - * @ignore - */ -exports.shouldCorrectlyConnect = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Replica configuration - var replSet2 = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - var db = new Db('integration_test_', replSet ); - db.open(function(err, p_db) { - if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err)); - test.equal(true, p_db.serverConfig.isConnected()); - - // Test primary - RS.primary(function(err, primary) { - if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err)); - - test.notEqual(null, primary); - test.equal(primary, p_db.serverConfig.primary.host + ":" + p_db.serverConfig.primary.port); - - // Perform tests - RS.secondaries(function(err, items) { - if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err)); - - // Test if we have the right secondaries - test.deepEqual(items.sort(), p_db.serverConfig.allSecondaries.map(function(item) { - return item.host + ":" + item.port; - }).sort()); - - // Test if we have the right arbiters - RS.arbiters(function(err, items) { - if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err)); - - test.deepEqual(items.sort(), p_db.serverConfig.arbiters.map(function(item) { - return item.host + ":" + item.port; - }).sort()); - // Force new instance - var db2 = new Db('integration_test_', replSet2 ); - db2.open(function(err, p_db2) { - if(err != null) debug("shouldCorrectlyConnect :: " + inspect(err)); - - test.equal(true, p_db2.serverConfig.isConnected()); - // Close top instance - db.close(); - db2.close(); - test.done(); - }); - }); - }); - }) - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; diff --git a/node_modules/reg/node_modules/mongodb/test/replicaset/count_test.js b/node_modules/reg/node_modules/mongodb/test/replicaset/count_test.js deleted file mode 100644 index 071c7c5..0000000 --- a/node_modules/reg/node_modules/mongodb/test/replicaset/count_test.js +++ /dev/null @@ -1,208 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server; - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports.shouldRetrieveCorrectCountAfterInsertionReconnect = function(test) { - // debug("=========================================== shouldRetrieveCorrectCountAfterInsertionReconnect") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - // Drop collection on replicaset - p_db.dropCollection('testsets', function(err, r) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - // Recreate collection on replicaset - p_db.createCollection('testsets', function(err, collection) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - // Insert a dummy document - collection.insert({a:20}, {safe: {w:2, wtimeout: 10000}}, function(err, r) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - // Execute a count - collection.count(function(err, c) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - test.equal(1, c); - // Close starting connection - p_db.close(); - - // Ensure replication happened in time - setTimeout(function() { - // Kill the primary - RS.killPrimary(function(node) { - - // debug("=========================================== shouldRetrieveCorrectCountAfterInsertionReconnect :: 0") - // Ensure valid connection - // Do inserts - // ensureConnection(test, retries, function(err, p_db) { - // // debug("=========================================== shouldRetrieveCorrectCountAfterInsertionReconnect :: 1") - // if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - // test.ok(err == null); - - p_db.collection('testsets', function(err, collection) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - collection.insert({a:30}, {safe:true}, function(err, r) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - collection.insert({a:40}, {safe:true}, function(err, r) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - // Execute count - collection.count(function(err, c) { - if(err != null) debug("shouldRetrieveCorrectCountAfterInsertionReconnect :: " + inspect(err)); - - test.equal(3, c); - - p_db.close(); - test.done(); - }); - }); - }); - }); - // }); - }); - }, 2000); - }) - }) - }); - }); - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - - diff --git a/node_modules/reg/node_modules/mongodb/test/replicaset/insert_test.js b/node_modules/reg/node_modules/mongodb/test/replicaset/insert_test.js deleted file mode 100644 index 12bdb8b..0000000 --- a/node_modules/reg/node_modules/mongodb/test/replicaset/insert_test.js +++ /dev/null @@ -1,484 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // // Print any errors - // db.on("error", function(err) { - // console.log("============================= ensureConnection caught error") - // console.dir(err) - // if(err != null && err.stack != null) console.log(err.stack) - // db.close(); - // }) - - // Open the db - db.open(function(err, p_db) { - // Close connections - db.close(); - // Process result - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports.shouldCorrectlyWaitForReplicationToServersOnInserts = function(test) { - // debug("=========================================== shouldWorkCorrectlyWithInserts") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('shouldCorrectlyWaitForReplicationToServersOnInserts', function(err, r) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldCorrectlyWaitForReplicationToServersOnInserts', function(err, collection) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:2, wtimeout: 10000}}, function(err, r) { - test.equal(null, err); - test.done(); - p_db.close(); - }); - }); - }); - }); -} - -exports.shouldCorrectlyThrowTimeoutForReplicationToServersOnInserts = function(test) { - // debug("=========================================== shouldWorkCorrectlyWithInserts") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('shouldCorrectlyThrowTimeoutForReplicationToServersOnInserts', function(err, r) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldCorrectlyThrowTimeoutForReplicationToServersOnInserts', function(err, collection) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:7, wtimeout: 10000}}, function(err, r) { - test.equal('timeout', err.err); - test.equal(true, err.wtimeout); - test.done(); - p_db.close(); - }); - }); - }); - }); -} - -exports.shouldCorrectlyExecuteSafeFindAndModify = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('shouldCorrectlyExecuteSafeFindAndModify', function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldCorrectlyExecuteSafeFindAndModify', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:2, wtimeout: 10000}}, function(err, r) { - // Execute a safe insert with replication to two servers - collection.findAndModify({'a':20}, [['a', 1]], {'$set':{'b':3}}, {new:true, safe: {w:2, wtimeout: 10000}}, function(err, result) { - test.equal(20, result.a); - test.equal(3, result.b); - test.done(); - p_db.close(); - }) - }); - }); - }); - }); -} - -exports.shouldCorrectlyInsertAfterPrimaryComesBackUp = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - // {rs_name:RS.name, socketOptions:{timeout:30000}} - {rs_name:RS.name} - ); - - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - // Open db - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('shouldCorrectlyInsertAfterPrimaryComesBackUp', function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldCorrectlyInsertAfterPrimaryComesBackUp', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:'majority', wtimeout: 10000}}, function(err, r) { - // Kill the primary - RS.killPrimary(2, {killNodeWaitTime:0}, function(node) { - // Attempt insert (should fail) - collection.insert({a:30}, {safe: {w:2, wtimeout: 10000}}, function(err, r) { - test.ok(err != null) - - if(err != null) { - collection.insert({a:40}, {safe: {w:2, wtimeout: 10000}}, function(err, r) { - - // Peform a count - collection.count(function(err, count) { - - test.equal(2, count); - p_db.close(); - test.done(); - }); - }); - } else { - p_db.close(); - test.ok(false) - test.done(); - } - }); - }); - }); - }); - }); - }); -} - -exports.shouldCorrectlyQueryAfterPrimaryComesBackUp = function(test) { - // debug("=========================================== shouldWorkCorrectlyWithInserts") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - // Open db - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('shouldCorrectlyQueryAfterPrimaryComesBackUp', function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldCorrectlyQueryAfterPrimaryComesBackUp', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:'majority', wtimeout: 10000}}, function(err, r) { - // Kill the primary - RS.killPrimary(2, {killNodeWaitTime:0}, function(node) { - // Ok let's execute same query a couple of times - collection.find({}).toArray(function(err, items) { - // console.log("============================================ CALLED :: 0") - test.ok(err != null); - // console.dir(err) - - collection.find({}).toArray(function(err, items) { - // console.log("============================================ CALLED :: 1") - // console.dir(err) - // console.dir(items) - - test.ok(err == null); - test.equal(1, items.length); - - collection.find({}).toArray(function(err, items) { - test.ok(err == null); - test.equal(1, items.length); - p_db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports.shouldWorkCorrectlyWithInserts = function(test) { - // debug("=========================================== shouldWorkCorrectlyWithInserts") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {numberOfRetries:20, retryMiliSeconds:5000}); - db.open(function(err, p_db) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Drop collection on replicaset - p_db.dropCollection('shouldWorkCorrectlyWithInserts', function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('shouldWorkCorrectlyWithInserts', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Insert a dummy document - collection.insert({a:20}, {safe: {w:'majority', wtimeout: 10000}}, function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Execute a count - collection.count(function(err, c) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - test.equal(1, c); - - // Kill the primary - RS.killPrimary(function(node) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - test.ok(err == null); - - // p_db.collection('shouldWorkCorrectlyWithInserts', {safe:true}, function(err, collection) { - p_db.collection('shouldWorkCorrectlyWithInserts', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Execute a set of inserts - Step( - function inserts() { - var group = this.group(); - collection.save({a:30}, {safe:{w:2, wtimeout: 10000}}, group()); - collection.save({a:40}, {safe:{w:2, wtimeout: 10000}}, group()); - collection.save({a:50}, {safe:{w:2, wtimeout: 10000}}, group()); - collection.save({a:60}, {safe:{w:2, wtimeout: 10000}}, group()); - collection.save({a:70}, {safe:{w:2, wtimeout: 10000}}, group()); - }, - - function finishUp(err, values) { - if(err != null) console.log(err.stack) - // Restart the old master and wait for the sync to happen - RS.restartKilledNodes(function(err, result) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Contains the results - var results = []; - - // Just wait for the results - // setTimeout(function() { - // Ensure the connection - // ensureConnection(test, retries, function(err, p_db) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Get the collection - p_db.collection('shouldWorkCorrectlyWithInserts', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - collection.find().each(function(err, item) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - if(item == null) { - // Ensure we have the correct values - test.equal(6, results.length); - [20, 30, 40, 50, 60, 70].forEach(function(a) { - test.equal(1, results.filter(function(element) { - return element.a == a; - }).length); - }); - - // Run second check - collection.save({a:80}, {safe:true}, function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - collection.find().toArray(function(err, items) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Ensure we have the correct values - test.equal(7, items.length); - - // Sort items by a - items = items.sort(function(a,b) { return a.a > b.a}); - // Test all items - test.equal(20, items[0].a); - test.equal(30, items[1].a); - test.equal(40, items[2].a); - test.equal(50, items[3].a); - test.equal(60, items[4].a); - test.equal(70, items[5].a); - test.equal(80, items[6].a); - - p_db.close(); - test.done(); - }); - }); - } else { - results.push(item); - } - }); - }); - // }); - // }, 5000); - }) - } - ); - }); - }); - }) - }) - }); - }); - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - diff --git a/node_modules/reg/node_modules/mongodb/test/replicaset/map_reduce_test.js b/node_modules/reg/node_modules/mongodb/test/replicaset/map_reduce_test.js deleted file mode 100644 index 22bf66a..0000000 --- a/node_modules/reg/node_modules/mongodb/test/replicaset/map_reduce_test.js +++ /dev/null @@ -1,253 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Open the db - db.open(function(err, p_db) { - // Close connections - db.close(); - // Process result - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:0, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports['Should Correctly group using replicaset'] = function(test) { - var self = this; - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Insert some data - var db = new Db('integration_test_', replSet, {slave_ok:true}); - db.open(function(err, p_db) { - if(err != null) debug("shouldGroup :: " + inspect(err)); - - p_db.createCollection("testgroup_replicaset", {safe:{w:2, wtimeout:10000}}, function(err, collection) { - if(err != null) debug("shoulGroup :: " + inspect(err)); - - collection.insert([{key:1,x:10}, {key:2,x:30}, {key:1,x:20}, {key:3,x:20}], {safe:{w:2, wtimeout:10000}}, function(err, result) { - // Ensure replication happened in time - setTimeout(function() { - // Kill the primary - RS.killPrimary(function(node) { - // Do a collection find - collection.group(['key'], {}, {sum:0}, function reduce(record, memo){ - memo.sum += record.x; - }, true, function(err, items){ - if(err != null) debug("shouldGroup :: " + inspect(err)); - test.equal(null, err); - test.equal(3, items.length); - - p_db.close(); - test.done(); - }) - }); - }, 2000); - }) - }); - }) -} - -exports.shouldPerformMapReduceFunctionInline = function(test) { - var self = this; - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Establish connection to db - var db = new Db('integration_test_', replSet, {slave_ok:true}); - db.open(function(err, db) { - - // Parse version of server if available - db.admin().serverInfo(function(err, result){ - - // Only run if the MongoDB version is higher than 1.7.6 - if(parseInt((result.version.replace(/\./g, ''))) >= 176) { - - // Create a test collection - db.createCollection('test_map_reduce_functions_inline_map_reduce', {safe:{w:2, wtimeout:10000}}, function(err, collection) { - // console.log("==================================================================================") - // console.dir(err) - - - // Insert some test documents - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - - // Map function - var map = function() { emit(this.user_id, 1); }; - // Reduce function - var reduce = function(k,vals) { return 1; }; - - // Execute map reduce and return results inline - collection.mapReduce(map, reduce, {out : {inline: 1}}, function(err, results) { - // console.log("=============================================================================") - // console.dir(err) - // console.dir(results) - - test.equal(2, results.length); - - db.close(); - test.done(); - }); - }); - }); - } else { - test.done(); - } - }); - }); -} - -exports.shouldFailToDoMapReduceToOutCollection = function(test) { - var self = this; - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Establish connection to db - var db = new Db('integration_test_', replSet, {slave_ok:true}); - db.open(function(err, db) { - - // Parse version of server if available - db.admin().serverInfo(function(err, result){ - - // Only run if the MongoDB version is higher than 1.7.6 - if(parseInt((result.version.replace(/\./g, ''))) >= 176) { - - // Create a test collection - db.createCollection('test_map_reduce_functions_notInline_map_reduce', {safe:{w:2, wtimeout:10000}}, function(err, collection) { - - // Insert some test documents - collection.insert([{'user_id':1}, {'user_id':2}], {safe:true}, function(err, r) { - - // Map function - var map = function() { emit(this.user_id, 1); }; - // Reduce function - var reduce = function(k,vals) { return 1; }; - - // Execute map reduce and return results inline - collection.mapReduce(map, reduce, {out : {replace:'replacethiscollection'}}, function(err, results) { - test.ok(err != null); - - db.close(); - test.done(); - }); - }); - }); - } else { - test.done(); - } - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; diff --git a/node_modules/reg/node_modules/mongodb/test/replicaset/query_secondaries_test.js b/node_modules/reg/node_modules/mongodb/test/replicaset/query_secondaries_test.js deleted file mode 100644 index 31d2a88..0000000 --- a/node_modules/reg/node_modules/mongodb/test/replicaset/query_secondaries_test.js +++ /dev/null @@ -1,283 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports.shouldReadPrimary = function(test) { - // debug("=========================================== shouldReadPrimary") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - // Drop collection on replicaset - p_db.dropCollection('testsets', function(err, r) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - test.equal(false, p_db.serverConfig.isReadPrimary()); - test.equal(false, p_db.serverConfig.isPrimary()); - p_db.close(); - test.done(); - }); - }) -} - -exports.shouldCorrectlyTestConnection = function(test) { - // debug("=========================================== shouldCorrectlyTestConnection") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('testsets', function(err, r) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - - test.ok(p_db.serverConfig.primary != null); - test.ok(p_db.serverConfig.read != null); - test.ok(p_db.serverConfig.primary.port != p_db.serverConfig.read.port); - p_db.close(); - test.done(); - }); - }) -} - -exports.shouldCorrectlyQuerySecondaries = function(test) { - // debug("=========================================== shouldCorrectlyQuerySecondaries") - var self = this; - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - - p_db.createCollection("testsets", {safe:{w:2, wtimeout:10000}}, function(err, collection) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - - collection.insert([{a:20}, {a:30}, {a:40}], {safe:{w:2, wtimeout:10000}}, function(err, result) { - // Ensure replication happened in time - setTimeout(function() { - // Kill the primary - RS.killPrimary(function(node) { - // Do a collection find - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(3, items.length); - p_db.close(); - test.done(); - }); - }); - }, 2000); - }) - }); - }) -} - -exports.shouldCorrectlyQuerySecondaries = function(test) { - // debug("=========================================== shouldCorrectlyQuerySecondaries") - var self = this; - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:false} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - - // Ensure the checkoutReader gives us the actual writer object - var reader = replSet.checkoutReader(); - var writer = replSet.checkoutWriter(); - // Ensure the connections are the same - test.equal(reader.socketOptions.host, writer.socketOptions.host); - test.equal(reader.socketOptions.port, writer.socketOptions.port); - // Close connection to Spain - db.close(); - test.done(); - }); -} - -exports.shouldAllowToForceReadWithPrimary = function(test) { - // debug("=========================================== shouldAllowToForceReadWithPrimary") - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - ], - {rs_name:RS.name, read_secondary:true} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - if(err != null) debug("shouldReadPrimary :: " + inspect(err)); - // Create a collection - p_db.createCollection('shouldAllowToForceReadWithPrimary', function(err, collection) { - test.equal(null, err); - // Insert a document - collection.insert({a:1}, {safe:{w:2, wtimeout:10000}}, function(err, result) { - test.equal(null, err); - - // Force read using primary - var cursor = collection.find({}, {read:'primary'}) - // Get documents - cursor.toArray(function(err, items) { - test.equal(1, items.length); - test.equal(1, items[0].a); - p_db.close(); - test.done(); - }) - }); - }) - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - - diff --git a/node_modules/reg/node_modules/mongodb/test/replicaset/read_preference_replicaset_test.js b/node_modules/reg/node_modules/mongodb/test/replicaset/read_preference_replicaset_test.js deleted file mode 100644 index 0c33e28..0000000 --- a/node_modules/reg/node_modules/mongodb/test/replicaset/read_preference_replicaset_test.js +++ /dev/null @@ -1,424 +0,0 @@ -// Read Preference behaviour based on Python driver by A. Jesse Jiryu Davis -// https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/__init__.py -// +----------------------+--------------------------------------------------+ -// | Connection type | Read Preference | -// +======================+================+================+================+ -// | |`PRIMARY` |`SECONDARY` |`SECONDARY_ONLY`| -// +----------------------+----------------+----------------+----------------+ -// |Connection to a single|Queries are |Queries are |Same as | -// |host. |allowed if the |allowed if the |`SECONDARY` | -// | |connection is to|connection is to| | -// | |the replica set |the replica set | | -// | |primary. |primary or a | | -// | | |secondary. | | -// +----------------------+----------------+----------------+----------------+ -// |Connection to a |Queries are sent|Queries are |Same as | -// |mongos. |to the primary |distributed |`SECONDARY` | -// | |of a shard. |among shard | | -// | | |secondaries. | | -// | | |Queries are sent| | -// | | |to the primary | | -// | | |if no | | -// | | |secondaries are | | -// | | |available. | | -// | | | | | -// +----------------------+----------------+----------------+----------------+ -// |ReplicaSetConnection |Queries are sent|Queries are |Queries are | -// | |to the primary |distributed |never sent to | -// | |of the replica |among replica |the replica set | -// | |set. |set secondaries.|primary. An | -// | | |Queries are sent|exception is | -// | | |to the primary |raised if no | -// | | |if no |secondary is | -// | | |secondaries are |available. | -// | | |available. | | -// | | | | | -// +----------------------+----------------+----------------+----------------+ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -var identifyServers = function(rs, dbname, callback) { - // Total number of servers to query - var numberOfServersToCheck = Object.keys(rs.mongods).length; - - // Arbiters - var arbiters = []; - var secondaries = []; - var primary = null; - - // Let's establish what all servers so we can pick targets for our queries - var keys = Object.keys(rs.mongods); - for(var i = 0; i < keys.length; i++) { - var host = rs.mongods[keys[i]].host; - var port = rs.mongods[keys[i]].port; - - // Connect to the db and query the state - var server = new Server(host, port,{auto_reconnect: true}); - // Create db instance - var db = new Db(dbname, server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, db) { - numberOfServersToCheck = numberOfServersToCheck - 1; - if(db.serverConfig.isMasterDoc.ismaster) { - primary = {host:db.serverConfig.host, port:db.serverConfig.port}; - } else if(db.serverConfig.isMasterDoc.secondary) { - secondaries.push({host:db.serverConfig.host, port:db.serverConfig.port}); - } else if(db.serverConfig.isMasterDoc.arbiterOnly) { - arbiters.push({host:db.serverConfig.host, port:db.serverConfig.port}); - } - - // Close the db - db.close(); - // If we are done perform the callback - if(numberOfServersToCheck <= 0) { - callback(null, {primary:primary, secondaries:secondaries, arbiters:arbiters}); - } - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -// +----------------------+--------------------------------------------------+ -// | Connection type | Read Preference | -// +======================+================+================+================+ -// | |`PRIMARY` |`SECONDARY` |`SECONDARY_ONLY`| -// +----------------------+----------------+----------------+----------------+ -// |ReplicaSetConnection |Queries are sent|Queries are |Queries are | -// | |to the primary |distributed |never sent to | -// | |of the replica |among replica |the replica set | -// | |set. |set secondaries.|primary. An | -// | | |Queries are sent|exception is | -// | | |to the primary |raised if no | -// | | |if no |secondary is | -// | | |secondaries are |available. | -// | | |available. | | -// | | | | | -// +----------------------+----------------+----------------+----------------+ -exports['Connection to replicaset with primary read preference'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, readPreference:Server.READ_PRIMARY} - ); - - // Execute flag - var executedCorrectly = false; - - // Create db instance - var db = new Db('integration_test_', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, p_db) { - // Let's get the primary server and wrap the checkout Method to ensure it's the one called for read - var checkoutWriterMethod = p_db.serverConfig._state.master.checkoutWriter; - // Set up checkoutWriter to catch correct write request - p_db.serverConfig._state.master.checkoutWriter = function() { - executedCorrectly = true; - return checkoutWriterMethod.apply(this); - } - - // Grab the collection - db.collection("read_preference_replicaset_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - // Does not get called or we don't care - test.ok(executedCorrectly); - p_db.close(); - test.done(); - }); - }); - }); -} - -exports['Connection to replicaset with secondary read preference with no secondaries should return primary'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, readPreference:Server.READ_SECONDARY} - ); - - // Create db instance - var db = new Db('integration_test_', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, p_db) { - // Rip out secondaries forcing an attempt to read from the primary - p_db.serverConfig._state.secondaries = {}; - - // Let's get the primary server and wrap the checkout Method to ensure it's the one called for read - var checkoutWriterMethod = p_db.serverConfig._state.master.checkoutWriter; - // Set up checkoutWriter to catch correct write request - p_db.serverConfig._state.master.checkoutWriter = function() { - var r = checkoutWriterMethod.apply(p_db.serverConfig._state.master); - test.equal(servers.primary.host, r.socketOptions.host); - test.equal(servers.primary.port, r.socketOptions.port); - return r; - } - - // Grab the collection - p_db.collection("read_preference_replicaset_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - // Does not get called or we don't care - p_db.close(); - test.done(); - }); - }); - }); - }); -} - -exports['Connection to replicaset with secondary only read preference no secondaries should not return a connection'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, readPreference:Server.READ_SECONDARY_ONLY} - ); - - // Create db instance - var db = new Db('integration_test_', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, p_db) { - // Rip out secondaries forcing an attempt to read from the primary - p_db.serverConfig._state.secondaries = {}; - - // Grab the collection - p_db.collection("read_preference_replicaset_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.ok(err != null); - test.equal("no open connections", err.message); - // Does not get called or we don't care - p_db.close(); - test.done(); - }); - }); - }); - }); -} - -exports['Connection to replicaset with secondary only read preference should return secondary server'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, readPreference:Server.READ_SECONDARY_ONLY} - ); - - // Execute flag - var executedCorrectly = false; - - // Create db instance - var db = new Db('integration_test_', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, p_db) { - // Let's set up all the secondaries - var keys = Object.keys(p_db.serverConfig._state.secondaries); - - // Set up checkoutReaders - for(var i = 0; i < keys.length; i++) { - var checkoutReader = p_db.serverConfig._state.secondaries[keys[i]].checkoutReader; - p_db.serverConfig._state.secondaries[keys[i]].checkoutReader = function() { - executedCorrectly = true; - } - } - - // Grab the collection - p_db.collection("read_preference_replicaset_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - // Does not get called or we don't care - test.ok(executedCorrectly); - p_db.close(); - test.done(); - }); - }); - }); - }); -} - -exports['Connection to replicaset with secondary read preference should return secondary server'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, readPreference:Server.READ_SECONDARY_ONLY} - ); - - // Execute flag - var executedCorrectly = false; - - // Create db instance - var db = new Db('integration_test_', replSet, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, p_db) { - // Let's set up all the secondaries - var keys = Object.keys(p_db.serverConfig._state.secondaries); - - // Set up checkoutReaders - for(var i = 0; i < keys.length; i++) { - var checkoutReader = p_db.serverConfig._state.secondaries[keys[i]].checkoutReader; - p_db.serverConfig._state.secondaries[keys[i]].checkoutReader = function() { - executedCorrectly = true; - return checkoutReader.apply(this); - } - } - - // Grab the collection - p_db.collection("read_preference_replicaset_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - // Does not get called or we don't care - test.ok(executedCorrectly); - p_db.close(); - test.done(); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - diff --git a/node_modules/reg/node_modules/mongodb/test/replicaset/read_preferences_single_test.js b/node_modules/reg/node_modules/mongodb/test/replicaset/read_preferences_single_test.js deleted file mode 100644 index bc6dd93..0000000 --- a/node_modules/reg/node_modules/mongodb/test/replicaset/read_preferences_single_test.js +++ /dev/null @@ -1,362 +0,0 @@ -// Read Preference behaviour based on Python driver by A. Jesse Jiryu Davis -// https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/__init__.py -// +----------------------+--------------------------------------------------+ -// | Connection type | Read Preference | -// +======================+================+================+================+ -// | |`PRIMARY` |`SECONDARY` |`SECONDARY_ONLY`| -// +----------------------+----------------+----------------+----------------+ -// |Connection to a single|Queries are |Queries are |Same as | -// |host. |allowed if the |allowed if the |`SECONDARY` | -// | |connection is to|connection is to| | -// | |the replica set |the replica set | | -// | |primary. |primary or a | | -// | | |secondary. | | -// +----------------------+----------------+----------------+----------------+ -// |Connection to a |Queries are sent|Queries are |Same as | -// |mongos. |to the primary |distributed |`SECONDARY` | -// | |of a shard. |among shard | | -// | | |secondaries. | | -// | | |Queries are sent| | -// | | |to the primary | | -// | | |if no | | -// | | |secondaries are | | -// | | |available. | | -// | | | | | -// +----------------------+----------------+----------------+----------------+ -// |ReplicaSetConnection |Queries are sent|Queries are |Queries are | -// | |to the primary |distributed |never sent to | -// | |of the replica |among replica |the replica set | -// | |set. |set secondaries.|primary. An | -// | | |Queries are sent|exception is | -// | | |to the primary |raised if no | -// | | |if no |secondary is | -// | | |secondaries are |available. | -// | | |available. | | -// | | | | | -// +----------------------+----------------+----------------+----------------+ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -var identifyServers = function(rs, dbname, callback) { - // Total number of servers to query - var numberOfServersToCheck = Object.keys(rs.mongods).length; - - // Arbiters - var arbiters = []; - var secondaries = []; - var primary = null; - - // Let's establish what all servers so we can pick targets for our queries - var keys = Object.keys(rs.mongods); - for(var i = 0; i < keys.length; i++) { - var host = rs.mongods[keys[i]].host; - var port = rs.mongods[keys[i]].port; - - // Connect to the db and query the state - var server = new Server(host, port,{auto_reconnect: true}); - // Create db instance - var db = new Db(dbname, server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - // Connect to the db - db.open(function(err, db) { - numberOfServersToCheck = numberOfServersToCheck - 1; - if(db.serverConfig.isMasterDoc.ismaster) { - primary = {host:db.serverConfig.host, port:db.serverConfig.port}; - } else if(db.serverConfig.isMasterDoc.secondary) { - secondaries.push({host:db.serverConfig.host, port:db.serverConfig.port}); - } else if(db.serverConfig.isMasterDoc.arbiterOnly) { - arbiters.push({host:db.serverConfig.host, port:db.serverConfig.port}); - } - - // Close the db - db.close(); - // If we are done perform the callback - if(numberOfServersToCheck <= 0) { - callback(null, {primary:primary, secondaries:secondaries, arbiters:arbiters}); - } - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, secondary_count:2, passive_count:1, arbiter_count:1}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -// +----------------------+--------------------------------------------------+ -// | Connection type | Read Preference | -// +======================+================+================+================+ -// | |`PRIMARY` |`SECONDARY` |`SECONDARY_ONLY`| -// +----------------------+----------------+----------------+----------------+ -// |Connection to a single|Queries are |Queries are |Same as | -// |host. |allowed if the |allowed if the |`SECONDARY` | -// | |connection is to|connection is to| | -// | |the replica set |the replica set | | -// | |primary. |primary or a | | -// | | |secondary. | | -// +----------------------+----------------+----------------+----------------+ -exports['Connection to a arbiter host with primary preference should give error'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Let's grab an arbiter, connect and attempt a query - var host = servers.arbiters[0].host; - var port = servers.arbiters[0].port; - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true}); - // Create db instance - var db = new Db('integration_test_', server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab a collection - p_db.createCollection('read_preference_single_test_0', function(err, collection) { - test.ok(err instanceof Error); - test.equal('Cannot write to an arbiter', err.message); - p_db.close(); - test.done(); - }); - }); - }); -} - -exports['Connection to a single primary host with different read preferences'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Select a secondary server, but specify read_primary (should fail) - // Let's grab a secondary server - var host = servers.primary.host; - var port = servers.primary.port; - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_PRIMARY}); - // Create db instance - var db = new Db('integration_test_', server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - p_db.collection("read_preference_single_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.equal(null, err); - p_db.close(); - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_SECONDARY}); - // Create db instance - var db = new Db('integration_test_', server, {slave_ok:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - db.collection("read_preference_single_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(0, items.length); - p_db.close(); - - // test.done(); - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_SECONDARY_ONLY}); - // Create db instance - var db = new Db('integration_test_', server, {slave_ok:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - db.collection("read_preference_single_test_0", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.ok(err instanceof Error); - test.equal("Cannot read from primary when secondary only specified", err.message); - - p_db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -exports['Connection to a single secondary host with different read preferences'] = function(test) { - // Fetch all the identity servers - identifyServers(RS, 'integration_test_', function(err, servers) { - // Select a secondary server, but specify read_primary (should fail) - // Let's grab a secondary server - var host = servers.secondaries[0].host; - var port = servers.secondaries[0].port; - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_PRIMARY}); - // Create db instance - var db = new Db('integration_test_', server, {native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - p_db.collection("read_preference_single_test_1", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.ok(err instanceof Error); - test.equal("Read preference is primary and server is not master", err.message); - p_db.close(); - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_SECONDARY}); - // Create db instance - var db = new Db('integration_test_', server, {slave_ok:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - db.collection("read_preference_single_test_1", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(0, items.length); - p_db.close(); - - // Connect to the db - var server = new Server(host, port,{auto_reconnect: true, readPreference:Server.READ_SECONDARY_ONLY}); - // Create db instance - var db = new Db('integration_test_', server, {slave_ok:true, native_parser: (process.env['TEST_NATIVE'] != null)}); - db.open(function(err, p_db) { - // Grab the collection - db.collection("read_preference_single_test_1", function(err, collection) { - // Attempt to read (should fail due to the server not being a primary); - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(0, items.length); - - p_db.close(); - test.done(); - }); - }); - }); - }); - }); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - - diff --git a/node_modules/reg/node_modules/mongodb/test/replicaset/tags_test.js b/node_modules/reg/node_modules/mongodb/test/replicaset/tags_test.js deleted file mode 100644 index c78e138..0000000 --- a/node_modules/reg/node_modules/mongodb/test/replicaset/tags_test.js +++ /dev/null @@ -1,382 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - PingStrategy = require('../../lib/mongodb/connection/strategies/ping_strategy').PingStrategy, - StatisticsStrategy = require('../../lib/mongodb/connection/strategies/statistics_strategy').StatisticsStrategy, - Server = require('../../lib/mongodb').Server; - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - // Print any errors - db.on("error", function(err) { - console.log("============================= ensureConnection caught error") - console.dir(err) - if(err != null && err.stack != null) console.log(err.stack) - db.close(); - }) - - // Open the db - db.open(function(err, p_db) { - db.close(); - - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 3000); - } else { - return callback(null); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, passive_count:0, secondary_count:2, tags:[{"dc1":"ny"}, {"dc1":"ny"}, {"dc2":"sf"}]}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports['Should Correctly Connect With Default Replicaset And Insert Document For Tag Dc:NY'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Recreate collection on replicaset - p_db.createCollection('testsets', function(err, collection) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - - // Insert a dummy document - collection.insert({a:20}, {safe: {w:'majority'}}, function(err, r) { - // Should have no error - test.equal(null, err); - - // Do a read for the value - collection.findOne({a:20}, function(err, item) { - p_db.close(); - test.equal(20, item.a); - test.done(); - }) - }); - }); - }) -} - -exports['Should Honor setReadPreference primary'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference(Server.READ_PRIMARY); - // Open the database - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Checkout a reader and make sure it's the primary - var reader = replSet.checkoutReader(); - var readerAddress = reader.socketOptions['host'] + ":" + reader.socketOptions['port']; - // Locate server instance associated with this id - var serverInstance = replSet._state.addresses[readerAddress]; - // Check that it's the primary instance - test.equal(true, serverInstance.master); - // Check that it's in the list of primary servers - var primaryAddress = replSet._state.master.host + ":" + replSet._state.master.port; - test.equal(primaryAddress, readerAddress); - // End test and close db - p_db.close(); - test.done(); - }) -} - -exports['Should Honor setReadPreference secondary'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference(Server.READ_SECONDARY); - // Open the database - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Checkout a reader and make sure it's the primary - var reader = replSet.checkoutReader(); - var readerAddress = reader.socketOptions['host'] + ":" + reader.socketOptions['port']; - // Locate server instance associated with this id - var serverInstance = replSet._state.addresses[readerAddress]; - // Check that it's the primary instance - test.equal(false, serverInstance.master); - // Check that it's in the list of primary servers - test.ok(replSet._state.secondaries[readerAddress] != null); - // End test and close db - p_db.close(); - test.done(); - }) -} - -exports['Should correctly cleanup connection with tags'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference({'dc3':'pa', 'dc2':'sf', 'dc1':'ny'}); - // Open the database - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Checkout a reader and make sure it's the primary - var reader = replSet.checkoutWriter(); - var readerAddress = reader.socketOptions['host'] + ":" + reader.socketOptions['port']; - // Locate server instance associated with this id - var serverInstance = replSet._state.addresses[readerAddress]; - // Force cleanup of byTags - ReplSetServers._cleanupTags(serverInstance, replSet._state.byTags); - // Check cleanup successful - test.equal(1, replSet._state.byTags['dc1']['ny'].length); - test.equal(1, replSet._state.byTags['dc2']['sf'].length); - // End test and close db - p_db.close(); - test.done(); - }) -} - -exports['Should Honor setReadPreference tag'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference({'dc3':'pa', 'dc2':'sf', 'dc1':'ny'}); - // Open the database - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Checkout a reader and make sure it's the primary - var reader = replSet.checkoutReader(); - var readerAddress = reader.socketOptions['host'] + ":" + reader.socketOptions['port']; - // Locate server instance associated with this id - var serverInstance = replSet._state.addresses[readerAddress]; - test.deepEqual({ dc2: 'sf' }, serverInstance.tags) - p_db.close(); - test.done(); - }) -}, - -exports['Should Correctly Collect ping information from servers'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference({'dc3':'pa', 'dc2':'sf', 'dc1':'ny'}); - // Open the database - var db = new Db('integration_test_', replSet, {recordQueryStats:true}); - db.open(function(err, p_db) { - setTimeout(function() { - var keys = Object.keys(replSet._state.addresses); - for(var i = 0; i < keys.length; i++) { - var server = replSet._state.addresses[keys[i]]; - test.ok(server.queryStats.numDataValues >= 0); - test.ok(server.queryStats.mean >= 0); - test.ok(server.queryStats.variance >= 0); - test.ok(server.queryStats.standardDeviation >= 0); - } - - p_db.close(); - test.done(); - }, 5000) - }) -} - -exports['Should correctly pick a ping strategy for secondary'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {} - ); - - // Set read preference - replSet.setReadPreference(Server.READ_SECONDARY); - // Open the database - var db = new Db('integration_test_', replSet, {recordQueryStats:true}); - db.open(function(err, p_db) { - p_db.createCollection('testsets3', function(err, collection) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - - // Insert a bunch of documents - collection.insert([{a:20}, {b:30}, {c:40}, {d:50}], {safe: {w:'majority'}}, function(err, r) { - - // Select all documents - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - p_db.close(); - test.done(); - }); - }); - }); - }) -} - -exports['Should correctly pick a statistics strategy for secondary'] = function(test) { - // Replica configuration - var replSet = new ReplSetServers([ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {strategy:'statistical'} - ); - - // Ensure we have the right strategy - test.ok(replSet.strategyInstance instanceof StatisticsStrategy); - - // Set read preference - replSet.setReadPreference(Server.READ_SECONDARY); - // Open the database - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - p_db.createCollection('testsets2', function(err, collection) { - if(err != null) debug("shouldCorrectlyWaitForReplicationToServersOnInserts :: " + inspect(err)); - - // Insert a bunch of documents - collection.insert([{a:20}, {b:30}, {c:40}, {d:50}], {safe: {w:'majority'}}, function(err, r) { - - // Select all documents - collection.find().toArray(function(err, items) { - collection.find().toArray(function(err, items) { - collection.find().toArray(function(err, items) { - test.equal(null, err); - test.equal(4, items.length); - - // Total number of entries done - var totalNumberOfStrategyEntries = 0; - - // Check that we have correct strategy objects - var keys = Object.keys(replSet._state.secondaries); - for(var i = 0; i < keys.length; i++) { - var server = replSet._state.secondaries[keys[i]]; - totalNumberOfStrategyEntries += server.queryStats.numDataValues; - } - - p_db.close(); - test.equal(4, totalNumberOfStrategyEntries); - test.done(); - }); - }); - }); - }); - }); - }) -}, - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; diff --git a/node_modules/reg/node_modules/mongodb/test/replicaset/two_server_tests.js b/node_modules/reg/node_modules/mongodb/test/replicaset/two_server_tests.js deleted file mode 100644 index 8be0031..0000000 --- a/node_modules/reg/node_modules/mongodb/test/replicaset/two_server_tests.js +++ /dev/null @@ -1,162 +0,0 @@ -var noReplicasetStart = process.env['NO_REPLICASET_START'] != null ? true : false; - -var testCase = require('../../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - gleak = require('../../dev/tools/gleak'), - ReplicaSetManager = require('../tools/replica_set_manager').ReplicaSetManager, - Db = require('../../lib/mongodb').Db, - ReplSetServers = require('../../lib/mongodb').ReplSetServers, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -// Keep instance of ReplicaSetManager -var serversUp = false; -var retries = 120; -var RS = RS == null ? null : RS; - -var ensureConnection = function(test, numberOfTries, callback) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name} - ); - - if(numberOfTries <= 0) return callback(new Error("could not connect correctly"), null); - - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - db.close(); - if(err != null) { - // Wait for a sec and retry - setTimeout(function() { - numberOfTries = numberOfTries - 1; - ensureConnection(test, numberOfTries, callback); - }, 1000); - } else { - return callback(null, p_db); - } - }) -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - // Create instance of replicaset manager but only for the first call - if(!serversUp && !noReplicasetStart) { - serversUp = true; - RS = new ReplicaSetManager({retries:120, - arbiter_count:0, - secondary_count:1, - passive_count:0, - kill_node_wait_time:50000}); - RS.startSet(true, function(err, result) { - if(err != null) throw err; - // Finish setup - callback(); - }); - } else { - RS.restartKilledNodes(function(err, result) { - if(err != null) throw err; - callback(); - }) - } -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - numberOfTestsRun = numberOfTestsRun - 1; - if(numberOfTestsRun == 0) { - // Finished kill all instances - RS.killAll(function() { - callback(); - }) - } else { - callback(); - } -} - -exports.shouldCorrectlyExecuteSafeFindAndModify = function(test) { - // Replica configuration - var replSet = new ReplSetServers( [ - new Server( RS.host, RS.ports[1], { auto_reconnect: true } ), - new Server( RS.host, RS.ports[0], { auto_reconnect: true } ), - // new Server( RS.host, RS.ports[2], { auto_reconnect: true } ) - ], - {rs_name:RS.name, read_secondary:false} - ); - - // Insert some data - var db = new Db('integration_test_', replSet); - db.open(function(err, p_db) { - // Check if we got an error - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - - // Drop collection on replicaset - p_db.dropCollection('testsets', function(err, r) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Recreate collection on replicaset - p_db.createCollection('testsets', function(err, collection) { - if(err != null) debug("shouldWorkCorrectlyWithInserts :: " + inspect(err)); - // Insert a dummy document - collection.insert({a:20}, {safe: {w:1, wtimeout: 10000}}, function(err, r) { - // Execute a findAndModify - collection.findAndModify({'a':20}, [['a', 1]], {'$set':{'b':3}}, {'new':true, safe: {w:7, wtimeout: 10000}}, function(err, updated_doc) { - test.equal('timeout', err.err) - test.equal(true, err.wtimeout) - p_db.close(); - test.done(); - }); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; - - - - - - - - - - - - - - - - diff --git a/node_modules/reg/node_modules/mongodb/test/streaming_test.js b/node_modules/reg/node_modules/mongodb/test/streaming_test.js deleted file mode 100644 index a769ce1..0000000 --- a/node_modules/reg/node_modules/mongodb/test/streaming_test.js +++ /dev/null @@ -1,143 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var native_parser = (process.env['TEST_NATIVE'] != null); -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldStreamRecordsCallsDataTheRightNumberOfTimes = function(test) { - client.createCollection('test_stream_records', function(err, collection) { - test.ok(collection instanceof Collection); - collection.insert([{'a':1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}], {safe:true}, function(err, ids) { - var stream = collection.find({}, {'limit' : 3}).streamRecords(); - var callsToEnd = 0; - stream.on('end', function() { - test.done(); - }); - - var callsToData = 0; - stream.on('data',function(data){ - callsToData += 1; - test.ok(callsToData <= 3); - }); - }); - }); -} - -exports.shouldStreamRecordsCallsEndTheRightNumberOfTimes = function(test) { - client.createCollection('test_stream_records', function(err, collection) { - test.ok(collection instanceof Collection); - collection.insert([{'a':1}, {'b' : 2}, {'c' : 3}, {'d' : 4}, {'e' : 5}], {safe:true}, function(err, ids) { - collection.find({}, {'limit' : 3}, function(err, cursor) { - var stream = cursor.streamRecords(function(er,item) {}); - var callsToEnd = 0; - stream.on('end', function() { - callsToEnd += 1; - test.equal(1, callsToEnd); - setTimeout(function() { - // Let's close the db - if (callsToEnd == 1) { - test.done(); - } - }.bind(this), 1000); - }); - - stream.on('data',function(data){ /* nothing here */ }); - }); - }); - }); -} - -exports.shouldStreamDocumentsWithLimitForFetching = function(test) { - var docs = [] - - for(var i = 0; i < 3000; i++) { - docs.push({'a':i}) - } - - client.createCollection('test_streaming_function_with_limit_for_fetching', function(err, collection) { - test.ok(collection instanceof Collection); - - collection.insert(docs, {safe:true}, function(err, ids) { - collection.find({}, function(err, cursor) { - // Execute find on all the documents - var stream = cursor.streamRecords({fetchSize:1000}); - var callsToEnd = 0; - stream.on('end', function() { - test.done(); - }); - - var callsToData = 0; - stream.on('data',function(data){ - callsToData += 1; - test.ok(callsToData <= 3000); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file diff --git a/node_modules/reg/node_modules/mongodb/test/tools/keyfile.txt b/node_modules/reg/node_modules/mongodb/test/tools/keyfile.txt deleted file mode 100644 index f15d680..0000000 --- a/node_modules/reg/node_modules/mongodb/test/tools/keyfile.txt +++ /dev/null @@ -1 +0,0 @@ -THIS IS A SECRET KEYFILE FOR REPLICA SETS BWAHAHAHAH diff --git a/node_modules/reg/node_modules/mongodb/test/tools/replica_set_manager.js b/node_modules/reg/node_modules/mongodb/test/tools/replica_set_manager.js deleted file mode 100644 index 332c9f1..0000000 --- a/node_modules/reg/node_modules/mongodb/test/tools/replica_set_manager.js +++ /dev/null @@ -1,591 +0,0 @@ -var debug = require('util').debug, - inspect = require('util').inspect, - path = require('path'), - fs = require('fs'), - exec = require('child_process').exec, - spawn = require('child_process').spawn, - Connection = require('../../lib/mongodb').Connection, - Db = require('../../lib/mongodb').Db, - Server = require('../../lib/mongodb').Server, - Step = require("../../deps/step/lib/step"); - -var ReplicaSetManager = exports.ReplicaSetManager = function(options) { - options = options == null ? {} : options; - - this.startPort = options["start_port"] || 30000; - this.ports = []; - this.name = options["name"] != null ? options["name"] : "replica-set-foo"; - this.host = options["host"] != null ? options["host"] : "127.0.0.1"; - this.retries = options["retries"] != null ? options["retries"] : 60; - this.config = {"_id": this.name, "version": 1, "members": []}; - this.durable = options["durable"] != null ? options["durable"] : false; - this.auth = options['auth'] != null ? options['auth'] : false; - this.path = path.resolve("data"); - this.killNodeWaitTime = options['kill_node_wait_time'] != null ? options['kill_node_wait_time'] : 20000; - this.tags = options['tags'] != null ? options['tags'] : []; - this.ssl = options['ssl'] != null ? options['ssl'] : false; - - this.arbiterCount = options["arbiter_count"] != null ? options["arbiter_count"] : 2; - this.secondaryCount = options["secondary_count"] != null ? options["secondary_count"] : 1; - this.passiveCount = options["passive_count"] != null ? options["passive_count"] : 1; - this.primaryCount = options["primary_count"] != null ? options["primary_count"] : 1; - this.keyPath = [process.cwd(), "test", "tools", "keyfile.txt"].join("/"); - try { - fs.chmodSync(this.keyPath, 0600); - } catch(err) { - console.dir(err); - } - - this.count = this.primaryCount + this.passiveCount + this.arbiterCount + this.secondaryCount; - if(this.count > 7) { - throw new Error("Cannot create a replica set with #{node_count} nodes. 7 is the max."); - } - - // Keeps all the mongod instances - this.mongods = {}; -} - -ReplicaSetManager.prototype.secondaries = function(callback) { - return this.allHostPairsWithState(2, callback); -} - -ReplicaSetManager.prototype.arbiters = function(callback) { - return this.allHostPairsWithState(7, callback); -} - -ReplicaSetManager.prototype.primary = function(callback) { - return this.allHostPairsWithState(1, function(err, items) { - if(items.length == 0) { - return callback(null, null); - } else { - return callback(null, items[0]); - } - }); -} - -ReplicaSetManager.prototype.allHostPairsWithState = function(state, callback) { - this.ensureUp(function(err, status) { - if(err != null) return callback(err, null); - - var members = status["members"]; - - // Get the correct state memebers - var nodes = members.filter(function(value) { - return value["state"] == state; - }); - - // Filter out address of the server - var servers = nodes.map(function(item) { - return item["name"]; - }); - - // Map nodes - return callback(null, servers); - }) -} - -ReplicaSetManager.prototype.startSet = function(killall, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - killall = args.length ? args.shift() : true; - debug("** Starting a replica set with " + this.count + " nodes"); - - // Kill all existing mongod instances - exec(killall ? 'killall -9 mongod' : '', function(err, stdout, stderr) { - var n = 0; - var tagsIndex = 0; - - Step( - function startAllServers() { - var group = this.group(); - // Start primary instances - for(n = 0; n < (self.primaryCount + self.secondaryCount); n++) { - self.initNode(n, {tags:self.tags[tagsIndex] != null ? self.tags[tagsIndex++] : null}, group()); - } - - // Start passive instances - for(var i = 0; i < self.passiveCount; i++) { - self.initNode(n, {passive:true, priority:0, tags:self.tags[tagsIndex] != null ? self.tags[tagsIndex++] : null}, group()) - n = n + 1; - } - - // Start arbiter instances - for(var i = 0; i < self.arbiterCount; i++) { - self.initNode(n, {arbiterOnly:true, tags:self.tags[tagsIndex] != null ? self.tags[tagsIndex++] : null}, group()); - n = n + 1; - } - }, - - function finishUp(err, values) { - self.numberOfInitiateRetries = 0; - // Initiate - self.initiate(function(err, result) { - if(err != null) return callback(err, null); - self.ensureUpRetries = 0; - - // Ensure all the members are up - debug("** Ensuring members are up..."); - // Let's ensure everything is up - self.ensureUp(function(err, result) { - if(err != null) return callback(err, null); - // Return a correct result - callback(null, result); - }) - }); - } - ); - }) -} - -ReplicaSetManager.prototype.initiate = function(callback) { - var self = this; - var done = false; - // Get master connection - self.getConnection(function(err, connection) { - if(err != null) return callback(err, null); - // Set replica configuration - connection.admin().command({replSetInitiate:self.config}, function(err, result) { - // Close connection - connection.close(); - // If we have an error let's - if(err != null) { - // Retry a number of times - if(self.numberOfInitiateRetries < self.retries) { - setTimeout(function() { - self.numberOfInitiateRetries = self.numberOfInitiateRetries + 1; - self.initiate(callback); - }, 1000); - } - } else { - // Make sure we only do this once, even if some messages are late - if(!done) { - done = true; - self.numberOfInitiateRetries = 0; - callback(null, null); - } - } - }); - }); -} - -// Get absolute path -var getPath = function(self, name) { - return path.join(self.path, name); -} - -ReplicaSetManager.prototype.initNode = function(n, fields, callback) { - var self = this; - this.mongods[n] = this.mongods[n] == null ? {} : this.mongods[n]; - var port = this.startPort + n; - this.ports.push(port); - this.mongods[n]["ssl"] = this.ssl; - this.mongods[n]["host"] = this.host; - this.mongods[n]["port"] = port; - this.mongods[n]["db_path"] = getPath(this, "rs-" + port); - this.mongods[n]["log_path"] = getPath(this, "log-" + port); - this.up = false; - - // Set priority off server in config - var priority = typeof fields === 'object' ? fields.priority : null; - - // Add extra fields provided - for(var name in fields) { - this.mongods[n][name] = fields[name]; - } - - // Perform cleanup of directories - exec("rm -rf " + self.mongods[n]["db_path"], function(err, stdout, stderr) { - if(err != null) return callback(err, null); - - // Create directory - exec("mkdir -p " + self.mongods[n]["db_path"], function(err, stdout, stderr) { - if(err != null) return callback(err, null); - self.mongods[n]["start"] = self.startCmd(n); - - // console.log("----------------------------------------------------- node start command") - // console.log(self.mongods[n]["start"]) - - self.start(n, function() { - // Add instance to list of members - var member = {"_id": n, "host": self.host + ":" + self.mongods[n]["port"]}; - // Set it to arbiter if it's been passed - if(self.mongods[n]['arbiterOnly']) { - member['arbiterOnly'] = true; - } - // Set priority level if it's defined - if(priority != null) { - member['priority'] = priority; - } - - // Check if we have tags - if(self.mongods[n]['tags'] != null) { - member["tags"] = self.mongods[n]['tags']; - } - - // Push member to config - self.config["members"].push(member); - // Return - return callback(); - }); - }); - }); -} - -ReplicaSetManager.prototype.killAll = function(callback) { - exec('killall -9 mongod', function(err, stdout, stderr) { - return callback(); - }); -} - -ReplicaSetManager.prototype.kill = function(node, signal, options, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 1); - callback = args.pop(); - signal = args.length ? args.shift() : 2; - options = args.length ? args.shift() : {}; - // kill node wait time - var killNodeWaitTime = options.killNodeWaitTime == null ? self.killNodeWaitTime : options.killNodeWaitTime; - - debug("** Killing node with pid " + this.mongods[node]["pid"] + " at port " + this.mongods[node]['port']); - var command = "kill -" + signal + " " + this.mongods[node]["pid"]; - // Kill process - exec(command, - function (error, stdout, stderr) { - debug('stdout: ' + stdout); - debug('stderr: ' + stderr); - if (error != null) { - debug('exec error: ' + error); - } - - self.mongods[node]["up"] = false; - // Wait for 5 seconds to give the server time to die a proper death - setTimeout(callback, killNodeWaitTime); - }); -} - -ReplicaSetManager.prototype.killPrimary = function(signal, options, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - signal = args.length ? args.shift() : 2; - options = args.length ? args.shift() : {}; - var done = false; - - this.getNodeWithState(1, function(err, node) { - if(!done) { - // Ensure no double callbacks due to later scheduled connections returning - done = true; - if(err != null) return callback(err, null); - - // Kill process and return node reference - self.kill(node, signal, options, function() { - // Wait for a while before passing back - callback(null, node); - }) - } - }); -} - -ReplicaSetManager.prototype.killSecondary = function(callback) { - var self = this; - var done = false; - - this.getNodeWithState(2, function(err, node) { - if(!done) { - // Ensure no double callbacks due to later scheduled connections returning - done = true; - if(err != null) return callback(err, null); - // Kill process and return node reference - self.kill(node, function() { - callback(null, node); - }) - } - }); -} - -ReplicaSetManager.prototype.stepDownPrimary = function(callback) { - var self = this; - // Get the primary node - this.getNodeWithState(1, function(err, primary) { - // Return error - if(err) return callback(err, null); - if(primary == null) return callback(new Error("No primary found"), null); - // Get the connection for the primary - self.getConnection(primary, function(err, connection) { - // Return any errors - if(err) return callback(err, null); - // Execute stepdown process - connection.admin().command({"replSetStepDown": 90}); - // Return the callback - return callback(null, connection); - }); - }); -} - -ReplicaSetManager.prototype.getNodeFromPort = function(port, callback) { - var self = this; - var nodes = Object.keys(this.mongods).filter(function(key, index, array) { - return self.mongods[key]["port"] == port; - }); - // Return first node - callback(null, nodes.length > 0 ? nodes.shift() : null); -} - -ReplicaSetManager.prototype.getNodeWithState = function(state, callback) { - var self = this; - self.ensureUpRetries = 0; - self.ensureUp(function(err, status) { - if(err != null) return callback(err, null); - - var node = status["members"].filter(function(element, index, array) { - return element["state"] == state; - }).shift(); - - if(node != null) { - var hostPort = node["name"].split(":"); - var port = hostPort[1] != null ? parseInt(hostPort[1]) : 27017; - var key = Object.keys(self.mongods).filter(function(element, index, array) { - return self.mongods[element]["port"] == port; - }).shift(); - return callback(null, key); - } else { - return callback(null, false); - } - }); -} - -ReplicaSetManager.prototype.ensureUp = function(callback) { - var self = this; - var numberOfInitiateRetries = this.retries; - var done = false; - - // Actual function doing testing - var ensureUpFunction = function() { - if(!done) { - if(!self.up) process.stdout.write("."); - // Attemp to retrieve a connection - self.getConnection(function(err, connection) { - // Adjust the number of retries - numberOfInitiateRetries = numberOfInitiateRetries - 1 - // If have no more retries stop - if(numberOfInitiateRetries == 0) { - // Set that we are done - done = true; - // perform callback - return callback(new Error("Servers did not come up again"), null); - } - - // We have a connection, execute command and update server object - if(err == null && connection != null) { - // Check repl set get status - connection.admin().command({"replSetGetStatus": 1}, function(err, object) { - // Close connection - if(connection != null) connection.close(); - // Get documents - var documents = object.documents; - // Get status object - var status = documents[0]; - - // If no members set - if(status["members"] == null || err != null) { - // if we have a connection force close it - if(connection != null) connection.close(); - // Ensure we perform enough retries - if(self.ensureUpRetries >= self.retries) { - // Set that we are done - done = true; - // Return error - return callback(new Error("Operation Failure"), null); - } else { - // Execute function again - setTimeout(ensureUpFunction, 1000); - } - } else { - // Establish all health member - var healthyMembers = status.members.filter(function(element) { - return element["health"] == 1 && [1, 2, 7].indexOf(element["state"]) != -1 - }); - - var stateCheck = status["members"].filter(function(element, indexOf, array) { - return element["state"] == 1; - }); - - if(healthyMembers.length == status.members.length && stateCheck.length > 0) { - // Set that we are done - done = true; - // if we have a connection force close it - if(connection != null) connection.close(); - // process.stdout.write("all members up! \n\n"); - if(!self.up) process.stdout.write("all members up!\n\n") - self.up = true; - return callback(null, status); - } else { - // if we have a connection force close it - if(connection != null) connection.close(); - // Ensure we perform enough retries - if(self.ensureUpRetries >= self.retries) { - // Set that we are done - done = true; - // Return error - return callback(new Error("Operation Failure"), null); - } else { - // Execute function again - setTimeout(ensureUpFunction, 1000); - } - } - } - }); - } else if(err != null && connection != null) { - if(connection != null) connection.close(); - } - }); - } - } - - // Execute the first function call - ensureUpFunction(); -} - -// Restart -ReplicaSetManager.prototype.restartKilledNodes = function(callback) { - var self = this; - - var nodes = Object.keys(self.mongods).filter(function(key) { - return self.mongods[key]["up"] == false; - }); - - var numberOfNodes = nodes.length; - if(numberOfNodes == 0) return self.ensureUp(callback); - - // Restart all the number of nodes - for(var i = 0; i < numberOfNodes; i++) { - // Start the process - self.start(nodes[i], function(err, result) { - // Adjust the number of nodes we are starting - numberOfNodes = numberOfNodes - 1; - - if(numberOfNodes === 0) { - self.ensureUp(callback); - } - }); - } -} - -ReplicaSetManager.prototype.getConnection = function(node, callback) { - var self = this; - // Function done - var done = false; - // Number of retries - var numberOfRetries = self.retries; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - node = args.length ? args.shift() : null; - - if(node == null) { - var keys = Object.keys(this.mongods); - for(var i = 0; i < keys.length; i++) { - var key = keys[i]; - // Locate first db that's runing and is not an arbiter - if(this.mongods[keys[i]]["arbiterOnly"] == null && this.mongods[key]["up"]) { - node = keys[i]; - break; - } - } - } - - // Get the node - if(self.mongods[node] != null) { - var intervalId = setInterval(function() { - var connection = new Db("replicaset_test", new Server(self.host, self.mongods[node]["port"], {ssl:self.ssl})); - connection.open(function(err, db) { - if(err == null && !done) { - // Set done - done = true; - // Clear interval - clearInterval(intervalId); - // Callback as done - return callback(null, connection); - } else { - // Close the connection - if(connection != null) connection.close(); - // Adjust the number of retries - numberOfRetries = numberOfRetries - 1; - // If we have no more retries fail - if(numberOfRetries == 0) { - // Set done - done = true; - // Clear interval - clearInterval(intervalId); - // Callback as done - return callback(new Error("Timed out connecting to primary"), null); - } - } - }); - }, 1000); - } else { - callback(new Error("no primary node found to do stepDownPrimary"), null); - } -} - -// Fire up the mongodb instance -var start = ReplicaSetManager.prototype.start = function(node, callback) { - var self = this; - - // Start up mongod process - var mongodb = exec(self.mongods[node]["start"], - function (error, stdout, stderr) { - debug('stdout: ' + stdout); - debug('stderr: ' + stderr); - if (error != null) { - debug('exec error: ' + error); - } - }); - - // Wait for a half a second then save the pids - setTimeout(function() { - // Mark server as running - self.mongods[node]["up"] = true; - self.mongods[node]["pid"]= fs.readFileSync(path.join(self.mongods[node]["db_path"], "mongod.lock"), 'ascii').trim(); - // Callback - callback(); - }, 5000); -} - -ReplicaSetManager.prototype.restart = start; - -ReplicaSetManager.prototype.startCmd = function(n) { - // Create boot command - this.mongods[n]["start"] = "mongod --rest --noprealloc --smallfiles --replSet " + this.name + " --logpath '" + this.mongods[n]['log_path'] + "' " + - " --dbpath " + this.mongods[n]['db_path'] + " --port " + this.mongods[n]['port'] + " --fork"; - this.mongods[n]["start"] = this.durable ? this.mongods[n]["start"] + " --dur" : this.mongods[n]["start"]; - - if(this.auth) { - this.mongods[n]["start"] = this.auth ? this.mongods[n]["start"] + " --keyFile " + this.keyPath : this.mongods[n]["start"]; - } - - // If we have ssl defined set up with test certificate - if(this.ssl) { - var path = getPath(this, '../test/certificates'); - this.mongods[n]["start"] = this.mongods[n]["start"] + " --sslOnNormalPorts --sslPEMKeyFile=" + path + "/mycert.pem --sslPEMKeyPassword=10gen"; - } - - return this.mongods[n]["start"]; -} - - - - - - - - - - - - - diff --git a/node_modules/reg/node_modules/mongodb/test/tools/server_manager.js b/node_modules/reg/node_modules/mongodb/test/tools/server_manager.js deleted file mode 100644 index 23c6a61..0000000 --- a/node_modules/reg/node_modules/mongodb/test/tools/server_manager.js +++ /dev/null @@ -1,142 +0,0 @@ -var debug = require('util').debug, - inspect = require('util').inspect, - path = require('path'), - fs = require('fs'), - exec = require('child_process').exec, - spawn = require('child_process').spawn, - Connection = require('../../lib/mongodb').Connection, - Db = require('../../lib/mongodb').Db, - Server = require('../../lib/mongodb').Server; - -var ServerManager = exports.ServerManager = function(options) { - options = options == null ? {} : options; - // Basic unpack values - this.path = path.resolve("data"); - this.port = options["start_port"] != null ? options["start_port"] : 27017; - this.db_path = getPath(this, "data-" + this.port); - this.log_path = getPath(this, "log-" + this.port); - this.journal = options["journal"] != null ? options["journal"] : false; - this.auth = options['auth'] != null ? options['auth'] : false; - this.ssl = options['ssl'] != null ? options['ssl'] : false; - this.purgedirectories = options['purgedirectories'] != null ? options['purgedirectories'] : true; - - // Server status values - this.up = false; - this.pid = null; -} - -// Start up the server instance -ServerManager.prototype.start = function(killall, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - killall = args.length ? args.shift() : true; - // Create start command - var startCmd = generateStartCmd(this, {log_path: self.log_path, - db_path: self.db_path, port: self.port, journal: self.journal, auth:self.auth, ssl:self.ssl}); - - // console.log("----------------------------------------------------------------------- start") - // console.log(startCmd) - - exec(killall ? 'killall mongod' : '', function(err, stdout, stderr) { - if(self.purgedirectories) { - // Remove directory - exec("rm -rf " + self.db_path, function(err, stdout, stderr) { - if(err != null) return callback(err, null); - // Create directory - exec("mkdir -p " + self.db_path, function(err, stdout, stderr) { - if(err != null) return callback(err, null); - // Start up mongod process - var mongodb = exec(startCmd, - function (error, stdout, stderr) { - // console.log('stdout: ' + stdout); - // console.log('stderr: ' + stderr); - if (error != null) { - console.log('exec error: ' + error); - } - }); - - // Wait for a half a second then save the pids - setTimeout(function() { - // Mark server as running - self.up = true; - self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); - // Callback - callback(); - }, 500); - }); - }); - } else { - // Ensure we remove the lock file as we are not purging the directory - fs.unlinkSync(path.join(self.db_path, "mongod.lock")); - - // Start up mongod process - var mongodb = exec(startCmd, - function (error, stdout, stderr) { - if (error != null) { - console.log('exec error: ' + error); - } - }); - - // Wait for a half a second then save the pids - setTimeout(function() { - // Mark server as running - self.up = true; - self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); - // Callback - callback(); - }, 5000); - } - }); -} - -ServerManager.prototype.stop = function(signal, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - signal = args.length ? args.shift() : 2; - // Stop the server - var command = "kill -" + signal + " " + self.pid; - // Kill process - exec(command, - function (error, stdout, stderr) { - // console.log('stdout: ' + stdout); - // console.log('stderr: ' + stderr); - if (error !== null) { - console.log('exec error: ' + error); - } - - self.up = false; - // Wait for a second - setTimeout(callback, 1000); - }); -} - -ServerManager.prototype.killAll = function(callback) { - exec('killall mongod', function(err, stdout, stderr) { - callback(null, null); - }); -} - -// Get absolute path -var getPath = function(self, name) { - return path.join(self.path, name); -} - -// Generate start command -var generateStartCmd = function(self, options) { - // Create boot command - var startCmd = "mongod --noprealloc --logpath '" + options['log_path'] + "' " + - " --dbpath " + options['db_path'] + " --port " + options['port'] + " --fork"; - startCmd = options['journal'] ? startCmd + " --journal" : startCmd; - startCmd = options['auth'] ? startCmd + " --auth" : startCmd; - // If we have ssl defined set up with test certificate - if(options['ssl']) { - var path = getPath(self, '../test/certificates'); - startCmd = startCmd + " --sslOnNormalPorts --sslPEMKeyFile=" + path + "/mycert.pem --sslPEMKeyPassword=10gen"; - } - // Return start command - return startCmd; -} diff --git a/node_modules/reg/node_modules/mongodb/test/tools/sharding_manager.js b/node_modules/reg/node_modules/mongodb/test/tools/sharding_manager.js deleted file mode 100644 index 9d58a7a..0000000 --- a/node_modules/reg/node_modules/mongodb/test/tools/sharding_manager.js +++ /dev/null @@ -1,155 +0,0 @@ -var debug = require('util').debug, - inspect = require('util').inspect, - path = require('path'), - fs = require('fs'), - exec = require('child_process').exec, - spawn = require('child_process').spawn, - Connection = require('../../lib/mongodb').Connection, - Db = require('../../lib/mongodb').Db, - Server = require('../../lib/mongodb').Server; - -var ShardingManager = exports.ShardingManager = function(options) { - options = options == null ? {} : options; - // Basic unpack values - this.path = path.resolve("data"); - this.port = options["start_port"] != null ? options["start_port"] : 27017; - this.number_of_sharding_servers = options["number_of_sharding_servers"] != null ? options["number_of_sharding_servers"] : 2; - this.number_of_config_servers = options["number_of_config_servers"] != null ? options["number_of_config_servers"] : 1; - this.db_path = getPath(this, "data-" + this.port); - this.log_path = getPath(this, "log-" + this.port); - this.journal = options["journal"] != null ? options["journal"] : false; - this.auth = options['auth'] != null ? options['auth'] : false; - this.ssl = options['ssl'] != null ? options['ssl'] : false; - this.purgedirectories = options['purgedirectories'] != null ? options['purgedirectories'] : true; - - // Server status values - this.up = false; - this.pid = null; -} - -// Start up the server instance -ShardingManager.prototype.start = function(killall, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - killall = args.length ? args.shift() : true; - // Create start command - var startCmd = generateStartCmd(this, {log_path: self.log_path, - db_path: self.db_path, port: self.port, journal: self.journal, auth:self.auth, ssl:self.ssl}); - - // Purge function for the data directory - var purgeFunction = function() { - if(self.purgedirectories) { - // Remove directory - exec("rm -rf " + self.db_path, function(err, stdout, stderr) { - if(err != null) return callback(err, null); - // Create directory - exec("mkdir -p " + self.db_path, function(err, stdout, stderr) { - if(err != null) return callback(err, null); - // Start up mongod process - var mongodb = exec(startCmd, - function (error, stdout, stderr) { - // console.log('stdout: ' + stdout); - // console.log('stderr: ' + stderr); - if (error != null) { - console.log('exec error: ' + error); - } - }); - - // Wait for a half a second then save the pids - setTimeout(function() { - // Mark server as running - self.up = true; - self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); - // Callback - callback(); - }, 500); - }); - }); - } else { - // Ensure we remove the lock file as we are not purging the directory - fs.unlinkSync(path.join(self.db_path, "mongod.lock")); - - // Start up mongod process - var mongodb = exec(startCmd, - function (error, stdout, stderr) { - if (error != null) { - console.log('exec error: ' + error); - } - }); - - // Wait for a half a second then save the pids - setTimeout(function() { - // Mark server as running - self.up = true; - self.pid = fs.readFileSync(path.join(self.db_path, "mongod.lock"), 'ascii').trim(); - // Callback - callback(); - }, 5000); - } - } - - // If we specified kill all the instances do that then purge the directories - if(killall) { - this.killAll(function() { - purgeFunction(); - }); - } else { - purgeFunction(); - } -} - -ShardingManager.prototype.stop = function(signal, callback) { - var self = this; - // Unpack callback and variables - var args = Array.prototype.slice.call(arguments, 0); - callback = args.pop(); - signal = args.length ? args.shift() : 2; - // Stop the server - var command = "kill -" + signal + " " + self.pid; - // Kill process - exec(command, - function (error, stdout, stderr) { - // console.log('stdout: ' + stdout); - // console.log('stderr: ' + stderr); - if (error != null) { - console.log('exec error: ' + error); - } - - self.up = false; - // Wait for a second - setTimeout(callback, 1000); - }); -} - -ShardingManager.prototype.killAll = function(callback) { - // Kill all mongos instances - exec('killall mongos', function(err, stdout, stderr) { - // Kill all mongod instances - exec('killall mongod', function(err, stdout, stderr) { - callback(null, null); - }); - }); -} - -// Get absolute path -var getPath = function(self, name) { - return path.join(self.path, name); -} - -// Generate start command -var generateStartCmd = function(self, options) { - // Create boot command - var startCmd = "mongod --noprealloc --logpath '" + options['log_path'] + "' " + - " --dbpath " + options['db_path'] + " --port " + options['port'] + " --fork"; - startCmd = options['journal'] ? startCmd + " --journal" : startCmd; - startCmd = options['auth'] ? startCmd + " --auth" : startCmd; - // If we have ssl defined set up with test certificate - if(options['ssl']) { - var path = getPath(self, '../test/certificates'); - startCmd = startCmd + " --sslOnNormalPorts --sslPEMKeyFile=" + path + "/mycert.pem --sslPEMKeyPassword=10gen"; - } - // Return start command - return startCmd; -} diff --git a/node_modules/reg/node_modules/mongodb/test/unicode_test.js b/node_modules/reg/node_modules/mongodb/test/unicode_test.js deleted file mode 100644 index e253421..0000000 --- a/node_modules/reg/node_modules/mongodb/test/unicode_test.js +++ /dev/null @@ -1,185 +0,0 @@ -var mongodb = process.env['TEST_NATIVE'] != null ? require('../lib/mongodb').native() : require('../lib/mongodb').pure(); -var useSSL = process.env['USE_SSL'] != null ? true : false; - -var testCase = require('../deps/nodeunit').testCase, - debug = require('util').debug, - inspect = require('util').inspect, - nodeunit = require('../deps/nodeunit'), - gleak = require('../dev/tools/gleak'), - Db = mongodb.Db, - Cursor = mongodb.Cursor, - Collection = mongodb.Collection, - Server = mongodb.Server; - -var MONGODB = 'integration_tests'; -var client = null; - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.setUp = function(callback) { - var self = exports; - client = new Db(MONGODB, new Server("127.0.0.1", 27017, {auto_reconnect: true, poolSize: 4, ssl:useSSL}), {native_parser: (process.env['TEST_NATIVE'] != null)}); - client.open(function(err, db_p) { - if(numberOfTestsRun == (Object.keys(self).length)) { - // If first test drop the db - client.dropDatabase(function(err, done) { - callback(); - }); - } else { - return callback(); - } - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.tearDown = function(callback) { - var self = this; - numberOfTestsRun = numberOfTestsRun - 1; - // Close connection - client.close(); - callback(); -} - -exports.shouldCorrectlySaveUnicodeContainingDocument = function(test) { - var doc = {statuses_count: 1687 - , created_at: 'Mon Oct 22 14:55:08 +0000 2007' - , description: 'NodeJS hacker, Cofounder of Debuggable, CakePHP core alumnus' - , favourites_count: 6 - , profile_sidebar_fill_color: 'EADEAA' - , screen_name: 'felixge' - , status: - { created_at: 'Fri Mar 12 08:59:44 +0000 2010' - , in_reply_to_screen_name: null - , truncated: false - , in_reply_to_user_id: null - , source: 'Tweetie' - , favorited: false - , in_reply_to_status_id: null - , id: 10364119169 - , text: '#berlin #snow = #fail : (' - } - , contributors_enabled: false - , following: null - , geo_enabled: false - , time_zone: 'Eastern Time (US & Canada)' - , profile_sidebar_border_color: 'D9B17E' - , url: 'http://debuggable.com' - , verified: false - , location: 'Berlin' - , profile_text_color: '333333' - , notifications: null - , profile_background_image_url: 'http://s.twimg.com/a/1268354287/images/themes/theme8/bg.gif' - , protected: false - , profile_link_color: '9D582E' - , followers_count: 840 - , name: 'Felix Geisend\u00f6rfer' - , profile_background_tile: false - , id: 9599342 - , lang: 'en' - , utc_offset: -18000 - , friends_count: 450 - , profile_background_color: '8B542B' - , profile_image_url: 'http://a3.twimg.com/profile_images/107142257/passbild-square_normal.jpg' - }; - - client.createCollection('test_should_correctly_save_unicode_containing_document', function(err, collection) { - doc['_id'] = 'felixge'; - - collection.save(doc, {safe:true}, function(err, doc) { - collection.findOne(function(err, doc) { - test.equal('felixge', doc._id); - test.done(); - }); - }); - }); -} - -// Test unicode characters -exports.shouldCorrectlyInsertUnicodeCharacters = function(test) { - client.createCollection('unicode_test_collection', function(err, collection) { - var test_strings = ["ouooueauiOUOOUEAUI", "öüóőúéáűíÖÜÓŐÚÉÁŰÍ", "本荘由利地域に洪水警報"]; - collection.insert({id: 0, text: test_strings[0]}, {safe:true}, function(err, ids) { - collection.insert({id: 1, text: test_strings[1]}, {safe:true}, function(err, ids) { - collection.insert({id: 2, text: test_strings[2]}, {safe:true}, function(err, ids) { - collection.find(function(err, cursor) { - cursor.each(function(err, item) { - if(item != null) { - test.equal(test_strings[item.id], item.text); - } else { - test.done(); - } - }); - }); - }); - }); - }); - }); -} - -exports.shouldCreateObjectWithChineseObjectName = function(test) { - var object = {'客家话' : 'Hello'}; - - client.createCollection('create_object_with_chinese_object_name', function(err, r) { - client.collection('create_object_with_chinese_object_name', function(err, collection) { - - collection.insert(object, {safe:true}, function(err, result) { - collection.findOne(function(err, item) { - test.equal(object['客家话'], item['客家话']) - - collection.find().toArray(function(err, items) { - test.equal(object['客家话'], items[0]['客家话']) - test.done(); - }) - }) - }); - }) - }) -} - -exports.shouldCorrectlyHandleUT8KeyNames = function(test) { - client.createCollection('test_utf8_key_name', function(err, collection) { - collection.insert({'šđžčćŠĐŽČĆ':1}, {safe:true}, function(err, ids) { - // finished_test({test_utf8_key_name:'ok'}); - collection.find({}, {'fields': ['šđžčćŠĐŽČĆ']}, function(err, cursor) { - cursor.toArray(function(err, items) { - // console.log("---------------------------------------------------------------") - // console.dir(err) - // console.dir(items) - // - test.equal(1, items[0]['šđžčćŠĐŽČĆ']); - // Let's close the db - test.done(); - }); - }); - }); - }); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -exports.noGlobalsLeaked = function(test) { - var leaks = gleak.detectNew(); - test.equal(0, leaks.length, "global var leak detected: " + leaks.join(', ')); - test.done(); -} - -/** - * Retrieve the server information for the current - * instance of the db client - * - * @ignore - */ -var numberOfTestsRun = Object.keys(this).length - 2; \ No newline at end of file