<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief test the collection interface
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");

// -----------------------------------------------------------------------------
// --SECTION--                                                collection methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: error handling
////////////////////////////////////////////////////////////////////////////////

function collectionSuiteErrorHandling () {
  var ERRORS = require("internal").errors;

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (underscore)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameUnderscore : function () {
      try {
        db._create("_illegal");
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (empty)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameEmpty : function () {
      try {
        db._create("");
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (number)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameNumber : function () {
      try {
        db._create("12345");
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (underscore) (short-cut)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameUnderscoreShortCut : function () {
      try {
        db["_illegal"];
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (empty) (short-cut)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameEmptyShortCut : function () {
      try {
        db[""];
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (number) (short-cut)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameNumberShortCut : function () {
      try {
        db["12345"];
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    }
  };
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: collection
////////////////////////////////////////////////////////////////////////////////

function collectionSuite () {
  var ERRORS = require("internal").errors;

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief read by name
////////////////////////////////////////////////////////////////////////////////

    testReadingByName : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var c2 = db._collection(cn);

      assertEqual(c1._id, c2._id);
      assertEqual(c1.name(), c2.name());
      assertEqual(c1.status(), c2.status());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief read by identifier
////////////////////////////////////////////////////////////////////////////////

    testReadingByIdentifier : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var c2 = db._collection(c1._id);

      assertEqual(c1._id, c2._id);
      assertEqual(c1.name(), c2.name());
      assertEqual(c1.status(), c2.status());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief read by name (short-cut)
////////////////////////////////////////////////////////////////////////////////

    testReadingByNameShortCut : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var c2 = db[cn];

      assertEqual(c1._id, c2._id);
      assertEqual(c1.name(), c2.name());
      assertEqual(c1.status(), c2.status());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief read all
////////////////////////////////////////////////////////////////////////////////

    testReadingAll : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var l = db._collections();

      assertNotEqual(0, l.length);

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief creating with defaults
////////////////////////////////////////////////////////////////////////////////

    testCreatingDefaults : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var p = c1.properties();

      assertEqual(false, p.waitForSync);

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief creating with properties
////////////////////////////////////////////////////////////////////////////////

    testCreatingProperties : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn, { waitForSync : true, journalSize : 1024 * 1024 });

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var p = c1.properties();

      assertEqual(true, p.waitForSync);

      if (p.journalSize < 1024 * 1024) {
        fail();
      }

      if (1024 * 1025 < p.journalSize) {
        fail();
      }

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief drop new-born
////////////////////////////////////////////////////////////////////////////////

    testDroppingNewBorn : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.drop();

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief drop loaded
////////////////////////////////////////////////////////////////////////////////

    testDroppingLoaded : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.drop();

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief drop unloaded
////////////////////////////////////////////////////////////////////////////////

    testDroppingUnloaded : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();
      c1.unload();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.drop();

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief figures
////////////////////////////////////////////////////////////////////////////////

    testFigures : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();

      var f = c1.figures();

      assertEqual(0, f.numberDatafiles);
      assertEqual(0, f.numberAlive);
      assertEqual(0, f.sizeAlive);
      assertEqual(0, f.numberDead);
      assertEqual(0, f.sizeDead);
      assertEqual(0, f.numberDeletion);

      var d1 = c1.save({ hallo : 1 });

      f = c1.figures();

      assertEqual(1, f.numberDatafiles);
      assertEqual(1, f.numberAlive);
      assertNotEqual(0, f.sizeAlive);
      assertEqual(0, f.numberDead);
      assertEqual(0, f.sizeDead);
      assertEqual(0, f.numberDeletion);

      var d2 = c1.save({ hallo : 2 });

      f = c1.figures();

      assertEqual(1, f.numberDatafiles);
      assertEqual(2, f.numberAlive);
      assertNotEqual(0, f.sizeAlive);
      assertEqual(0, f.numberDead);
      assertEqual(0, f.sizeDead);
      assertEqual(0, f.numberDeletion);

      c1.delete(d1);

      f = c1.figures();

      assertEqual(1, f.numberDatafiles);
      assertEqual(1, f.numberAlive);
      assertNotEqual(0, f.sizeAlive);
      assertEqual(1, f.numberDead);
      assertNotEqual(0, f.sizeDead);
      assertEqual(1, f.numberDeletion);

      c1.delete(d2);

      f = c1.figures();

      assertEqual(1, f.numberDatafiles);
      assertEqual(0, f.numberAlive);
      assertEqual(0, f.sizeAlive);
      assertEqual(2, f.numberDead);
      assertNotEqual(0, f.sizeDead);
      assertEqual(2, f.numberDeletion);

      db._drop(cn);
    }
  };
}

////////////////////////////////////////////////////////////////////////////////
// --SECTION--                                                   vocbase methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: collection
////////////////////////////////////////////////////////////////////////////////

function collectionDbSuite () {
  var ERRORS = require("internal").errors;

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief drop new-born (DB)
////////////////////////////////////////////////////////////////////////////////

    testDroppingNewBornDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._drop(cn);

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief drop loaded (DB)
////////////////////////////////////////////////////////////////////////////////

    testDroppingLoadedDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._drop(cn);

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief drop unloaded (DB)
////////////////////////////////////////////////////////////////////////////////

    testDroppingUnloadedDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();
      c1.unload();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._drop(cn);

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate new-born (DB)
////////////////////////////////////////////////////////////////////////////////

    testTruncatingNewBornDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._truncate(cn);

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate loaded (DB)
////////////////////////////////////////////////////////////////////////////////

    testTruncatingLoadedDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._truncate(cn);

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate unloaded (DB)
////////////////////////////////////////////////////////////////////////////////

    testTruncatingUnloadedDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();
      c1.unload();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._truncate(cn);

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate new-born (DB)
////////////////////////////////////////////////////////////////////////////////

    testTruncatingNewBorn : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.truncate();

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate loaded (DB)
////////////////////////////////////////////////////////////////////////////////

    testTruncatingLoaded : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.truncate();

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate unloaded (DB)
////////////////////////////////////////////////////////////////////////////////

    testTruncatingUnloaded : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();
      c1.unload();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.truncate();

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    }
  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(collectionSuiteErrorHandling);
jsunity.run(collectionSuite);
jsunity.run(collectionDbSuite);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:

<commit_msg>fixed names<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief test the collection interface
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2010-2012 triagens GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
///     http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

var jsunity = require("jsunity");

// -----------------------------------------------------------------------------
// --SECTION--                                                collection methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: error handling
////////////////////////////////////////////////////////////////////////////////

function collectionSuiteErrorHandling () {
  var ERRORS = require("internal").errors;

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (underscore)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameUnderscore : function () {
      try {
        db._create("_illegal");
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (empty)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameEmpty : function () {
      try {
        db._create("");
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (number)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameNumber : function () {
      try {
        db._create("12345");
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (underscore) (short-cut)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameUnderscoreShortCut : function () {
      try {
        db["_illegal"];
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (empty) (short-cut)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameEmptyShortCut : function () {
      try {
        db[""];
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief bad name (number) (short-cut)
////////////////////////////////////////////////////////////////////////////////

    testErrorHandlingBadNameNumberShortCut : function () {
      try {
        db["12345"];
      }
      catch (err) {
        assertEqual(ERRORS.ERROR_AVOCADO_ILLEGAL_NAME.code, err.errorNum);
      }
    }
  };
}

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: collection
////////////////////////////////////////////////////////////////////////////////

function collectionSuite () {
  var ERRORS = require("internal").errors;

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief read by name
////////////////////////////////////////////////////////////////////////////////

    testReadingByName : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var c2 = db._collection(cn);

      assertEqual(c1._id, c2._id);
      assertEqual(c1.name(), c2.name());
      assertEqual(c1.status(), c2.status());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief read by identifier
////////////////////////////////////////////////////////////////////////////////

    testReadingByIdentifier : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var c2 = db._collection(c1._id);

      assertEqual(c1._id, c2._id);
      assertEqual(c1.name(), c2.name());
      assertEqual(c1.status(), c2.status());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief read by name (short-cut)
////////////////////////////////////////////////////////////////////////////////

    testReadingByNameShortCut : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var c2 = db[cn];

      assertEqual(c1._id, c2._id);
      assertEqual(c1.name(), c2.name());
      assertEqual(c1.status(), c2.status());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief read all
////////////////////////////////////////////////////////////////////////////////

    testReadingAll : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var l = db._collections();

      assertNotEqual(0, l.length);

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief creating with defaults
////////////////////////////////////////////////////////////////////////////////

    testCreatingDefaults : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var p = c1.properties();

      assertEqual(false, p.waitForSync);

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief creating with properties
////////////////////////////////////////////////////////////////////////////////

    testCreatingProperties : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn, { waitForSync : true, journalSize : 1024 * 1024 });

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      var p = c1.properties();

      assertEqual(true, p.waitForSync);

      if (p.journalSize < 1024 * 1024) {
        fail();
      }

      if (1024 * 1025 < p.journalSize) {
        fail();
      }

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief drop new-born
////////////////////////////////////////////////////////////////////////////////

    testDroppingNewBorn : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.drop();

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief drop loaded
////////////////////////////////////////////////////////////////////////////////

    testDroppingLoaded : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.drop();

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief drop unloaded
////////////////////////////////////////////////////////////////////////////////

    testDroppingUnloaded : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();
      c1.unload();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.drop();

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate new-born
////////////////////////////////////////////////////////////////////////////////

    testTruncatingNewBorn : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.truncate();

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate loaded
////////////////////////////////////////////////////////////////////////////////

    testTruncatingLoaded : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.truncate();

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate unloaded
////////////////////////////////////////////////////////////////////////////////

    testTruncatingUnloaded : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();
      c1.unload();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      c1.truncate();

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief figures
////////////////////////////////////////////////////////////////////////////////

    testFigures : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();

      var f = c1.figures();

      assertEqual(0, f.numberDatafiles);
      assertEqual(0, f.numberAlive);
      assertEqual(0, f.sizeAlive);
      assertEqual(0, f.numberDead);
      assertEqual(0, f.sizeDead);
      assertEqual(0, f.numberDeletion);

      var d1 = c1.save({ hallo : 1 });

      f = c1.figures();

      assertEqual(1, f.numberDatafiles);
      assertEqual(1, f.numberAlive);
      assertNotEqual(0, f.sizeAlive);
      assertEqual(0, f.numberDead);
      assertEqual(0, f.sizeDead);
      assertEqual(0, f.numberDeletion);

      var d2 = c1.save({ hallo : 2 });

      f = c1.figures();

      assertEqual(1, f.numberDatafiles);
      assertEqual(2, f.numberAlive);
      assertNotEqual(0, f.sizeAlive);
      assertEqual(0, f.numberDead);
      assertEqual(0, f.sizeDead);
      assertEqual(0, f.numberDeletion);

      c1.delete(d1);

      f = c1.figures();

      assertEqual(1, f.numberDatafiles);
      assertEqual(1, f.numberAlive);
      assertNotEqual(0, f.sizeAlive);
      assertEqual(1, f.numberDead);
      assertNotEqual(0, f.sizeDead);
      assertEqual(1, f.numberDeletion);

      c1.delete(d2);

      f = c1.figures();

      assertEqual(1, f.numberDatafiles);
      assertEqual(0, f.numberAlive);
      assertEqual(0, f.sizeAlive);
      assertEqual(2, f.numberDead);
      assertNotEqual(0, f.sizeDead);
      assertEqual(2, f.numberDeletion);

      db._drop(cn);
    }
  };
}

////////////////////////////////////////////////////////////////////////////////
// --SECTION--                                                   vocbase methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief test suite: collection
////////////////////////////////////////////////////////////////////////////////

function collectionDbSuite () {
  var ERRORS = require("internal").errors;

  return {

////////////////////////////////////////////////////////////////////////////////
/// @brief drop new-born (DB)
////////////////////////////////////////////////////////////////////////////////

    testDroppingNewBornDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._drop(cn);

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief drop loaded (DB)
////////////////////////////////////////////////////////////////////////////////

    testDroppingLoadedDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._drop(cn);

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief drop unloaded (DB)
////////////////////////////////////////////////////////////////////////////////

    testDroppingUnloadedDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();
      c1.unload();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._drop(cn);

      assertEqual(AvocadoCollection.STATUS_DELETED, c1.status());

      var c2 = db._collection(cn);

      assertEqual(null, c2);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate new-born (DB)
////////////////////////////////////////////////////////////////////////////////

    testTruncatingNewBornDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._truncate(cn);

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate loaded (DB)
////////////////////////////////////////////////////////////////////////////////

    testTruncatingLoadedDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._truncate(cn);

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    },

////////////////////////////////////////////////////////////////////////////////
/// @brief truncate unloaded (DB)
////////////////////////////////////////////////////////////////////////////////

    testTruncatingUnloadedDB : function () {
      var cn = "example";

      db._drop(cn);
      var c1 = db._create(cn);

      c1.load();
      c1.unload();

      assertTypeOf("number", c1._id);
      assertEqual(cn, c1.name());
      assertTypeOf("number", c1.status());

      db._truncate(cn);

      assertEqual(AvocadoCollection.STATUS_LOADED, c1.status());
      assertEqual(0, c1.count());

      db._drop(cn);
    }
  };
}

// -----------------------------------------------------------------------------
// --SECTION--                                                              main
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief executes the test suites
////////////////////////////////////////////////////////////////////////////////

jsunity.run(collectionSuiteErrorHandling);
jsunity.run(collectionSuite);
jsunity.run(collectionDbSuite);

return jsunity.done();

// Local Variables:
// mode: outline-minor
// outline-regexp: "^\\(/// @brief\\|/// @addtogroup\\|// --SECTION--\\|/// @page\\|/// @}\\)"
// End:

<|endoftext|>


<commit_before>/*jslint unparam: true, browser: true, indent: 2 */

;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.section = {
    name: 'section',

    version : '4.0.0.alpha',

    settings : {
      deep_linking: true,
      one_up: false,
      callback: function (){}
    },

    init : function (scope, method, options) {
      this.scope = this.scope || scope;
      Foundation.inherit(this, 'throttle data_options');

      if (typeof method === 'object') {
        $.extend(true, this.settings, method);
      }

      if (typeof method != 'string') {
        this.set_active_from_hash();
        if (!this.settings.init) this.events();

        return this.settings.init;
      } else {
        return this[method].call(this, options);
      }
    },

    events : function () {
      var self = this;
      $(this.scope).on('click.fndtn.section', '[data-section] .title', function (e) {
        $.extend(true, self.settings, self.data_options($(this).closest('[data-section]')));
        self.toggle_active.call(this, e, self);
      });

      $(window).on('resize.fndtn.section', self.throttle(function () {
        self.resize.call(this);
      }, 75)).trigger('resize');

      this.settings.init = true;
    },

    toggle_active : function (e, self) {
      var $this = $(this),
          section = $this.closest('section, .section'),
          content = section.find('.content');

      if (!self.settings.deep_linking && content.length > 0) {
          e.preventDefault();
      }

      if (section.hasClass('active')) {
        if ($(this.scope).width() < 769) {
          section
            .removeClass('active')
            .attr('style', '');
        }
      } else {
        if ($(this.scope).width() > 768 || self.settings.one_up) {
          $this
            .closest('[data-section]')
            .find('section, .section')
            .removeClass('active')
            .attr('style', '');
        }
        section
          .css('padding-top', section.find('.title').height())
          .addClass('active');
      }

      self.settings.callback();
    },

    resize : function () {
      var sections = $('[data-section]');

        sections.each(function() {
          var active_section = $(this).find('section.active, .section.active');
          if (active_section.length > 1) {
            active_section
              .not(':first')
              .removeClass('active')
              .attr('style', '');
          } else if (active_section.length < 1) {
            var first = $(this).find('section, .section').first();
            first
              .addClass('active')
              .css('padding-top', first.find('.title').height());
          }
          Foundation.libs.section.position_titles($(this));
        });
    },

    set_active_from_hash : function () {
      var hash = window.location.hash.substring(1);

      if (hash.length > 0 && this.settings.deep_linking) {
        $(this.scope)
          .find('[data-section]')
          .find('.content[data-slug=' + hash + ']')
          .closest('section, .section')
          .addClass('active');
      }
    },

    position_titles : function (section, off) {
      var titles = section.find('.title'),
          previous_width = 0;

      if (typeof off === 'boolean') {
        titles.attr('style', '');
      } else {
        titles.each(function () {
          $(this).css('left', previous_width);
          previous_width += $(this).width();
        });
      }
    },

    off : function () {
      $(this.scope).off('.fndtn.section');
      $(window).off('.fndtn.section');
      this.settings.init = false;
    }
  };
}(Foundation.zj, this, this.document));
<commit_msg>Don't explode when location.hash == "#/123"<commit_after>/*jslint unparam: true, browser: true, indent: 2 */

;(function ($, window, document, undefined) {
  'use strict';

  Foundation.libs.section = {
    name: 'section',

    version : '4.0.0.alpha',

    settings : {
      deep_linking: true,
      one_up: false,
      callback: function (){}
    },

    init : function (scope, method, options) {
      this.scope = this.scope || scope;
      Foundation.inherit(this, 'throttle data_options');

      if (typeof method === 'object') {
        $.extend(true, this.settings, method);
      }

      if (typeof method != 'string') {
        this.set_active_from_hash();
        if (!this.settings.init) this.events();

        return this.settings.init;
      } else {
        return this[method].call(this, options);
      }
    },

    events : function () {
      var self = this;
      $(this.scope).on('click.fndtn.section', '[data-section] .title', function (e) {
        $.extend(true, self.settings, self.data_options($(this).closest('[data-section]')));
        self.toggle_active.call(this, e, self);
      });

      $(window).on('resize.fndtn.section', self.throttle(function () {
        self.resize.call(this);
      }, 75)).trigger('resize');

      this.settings.init = true;
    },

    toggle_active : function (e, self) {
      var $this = $(this),
          section = $this.closest('section, .section'),
          content = section.find('.content');

      if (!self.settings.deep_linking && content.length > 0) {
          e.preventDefault();
      }

      if (section.hasClass('active')) {
        if ($(this.scope).width() < 769) {
          section
            .removeClass('active')
            .attr('style', '');
        }
      } else {
        if ($(this.scope).width() > 768 || self.settings.one_up) {
          $this
            .closest('[data-section]')
            .find('section, .section')
            .removeClass('active')
            .attr('style', '');
        }
        section
          .css('padding-top', section.find('.title').height())
          .addClass('active');
      }

      self.settings.callback();
    },

    resize : function () {
      var sections = $('[data-section]');

        sections.each(function() {
          var active_section = $(this).find('section.active, .section.active');
          if (active_section.length > 1) {
            active_section
              .not(':first')
              .removeClass('active')
              .attr('style', '');
          } else if (active_section.length < 1) {
            var first = $(this).find('section, .section').first();
            first
              .addClass('active')
              .css('padding-top', first.find('.title').height());
          }
          Foundation.libs.section.position_titles($(this));
        });
    },

    set_active_from_hash : function () {
      var hash = window.location.hash.substring(1);

      if (hash.length > 0 && this.settings.deep_linking) {
        $(this.scope)
          .find('[data-section]')
          .find('.content[data-slug="' + hash + '"]')
          .closest('section, .section')
          .addClass('active');
      }
    },

    position_titles : function (section, off) {
      var titles = section.find('.title'),
          previous_width = 0;

      if (typeof off === 'boolean') {
        titles.attr('style', '');
      } else {
        titles.each(function () {
          $(this).css('left', previous_width);
          previous_width += $(this).width();
        });
      }
    },

    off : function () {
      $(this.scope).off('.fndtn.section');
      $(window).off('.fndtn.section');
      this.settings.init = false;
    }
  };
}(Foundation.zj, this, this.document));
<|endoftext|>


<commit_before>describe('hasVowels()', function() {
    it('should always return a boolean', function() {
        expect('example string'.hasVowels()).toEqual(jasmine.any(Boolean));
    });

    it('should return true if string has vowels', function() {
        expect('oreofe'.hasVowels()).toBe(true);
        expect(('AnDeLa').hasVowels()).toBe(true);
    });

    it('should return false if string has no vowels', function() {
        expect('why'.hasVowels()).toBe(false);
        expect(('twyndyllyngs').hasVowels()).toBe(false);
    });
});

describe('toUpper()', function() {
    it('should always return a string', function() {
        expect('example string'.toUpper()).toEqual(jasmine.any(String));
    });

    it('should return an upper case of the calling string', function() {
        expect('upper case'.toUpper()).toBe('UPPER CASE');
        expect('camelCase'.toUpper()).toBe('CAMELCASE');
        expect('MiXeD cAsE'.toUpper()).toBe('MIXED CASE');
    });
});

describe('toLower()', function() {
    it('should return a string', function() {
        expect('example string'.toLower()).toEqual(jasmine.any(String));
    });

    it('should return a lower case of the calling string', function() {
        expect('LOWER CASE'.toLower()).toBe('lower case');
        expect('PascalCaseD'.toLower()).toBe('pascalcased');
        expect('MiXeDcAsE'.toLower()).toBe('mixedcase');
    });
});

describe('ucFirst()', function() {
    it('should return a string', function() {
        expect(''.ucFirst()).toEqual(jasmine.any(String));
    });

    it('should convert first character to uppercase', function() {
        expect('oreofe'.ucFirst()).toBe('Oreofe');
        expect('Ralph'.ucFirst()).toBe('Ralph');
    });
});

describe('isQuestion()', function() {
    it('should always return a boolean', function() {
        expect('example string'.isQuestion()).toEqual(jasmine.any(Boolean));
    });

    it('should return true if string is a question', function() {
        expect('is a question?'.isQuestion()).toBe(true);
        expect('Is Another Question?'.isQuestion()).toBe(true);
    });

    it('should return false if string is not a question', function() {
        expect('is not a question'.isQuestion()).toBe(false);
        expect('Is not Another Question'.isQuestion()).toBe(false);
    });
});

describe('words()', function() {
    it('should always return a typeof object', function() {
        expect('this is an example string'.words())
            .toEqual(jasmine.any(Object));
    });

    it('should always return an array', function() {
        expect('this is an example string'.words() instanceof Array).toBe(true);
    });

    it('should return an array of words in the string', function() {
        expect('this is a string of words'.words()).toEqual(['this', 'is',
        'a', 'string', 'of', 'words']);
        expect('My name is Ore-ofe'.words())
            .toEqual(['My', 'name', 'is', 'Ore-ofe']);
    });

    it('should return empty array if no words are found', function() {
        expect(',./;[]=-'.words()).toEqual([]);
    });
});

describe('wordCount()', function(){
    it('should always return type Number', function(){
        expect('this string'.wordCount()).toEqual(jasmine.any(Number));
    });

    it('should return number of words in a string', function() {
        expect('this is a string of words'.wordCount()).toBe(6);
        expect('My name is Ore-ofe'.wordCount()).toBe(4);
    });

    it('should return 0 if string contains no word', function() {
        expect(',./;[]=-'.wordCount()).toBe(0);
    });
});

describe('toCurrency()', function() {
    it('should return a string', function() {
        expect('111111.00'.toCurrency()).toEqual(jasmine.any(String));
    });
});<commit_msg>Add spec to test toCurrency() returns formatted string<commit_after>describe('hasVowels()', function() {
    it('should always return a boolean', function() {
        expect('example string'.hasVowels()).toEqual(jasmine.any(Boolean));
    });

    it('should return true if string has vowels', function() {
        expect('oreofe'.hasVowels()).toBe(true);
        expect(('AnDeLa').hasVowels()).toBe(true);
    });

    it('should return false if string has no vowels', function() {
        expect('why'.hasVowels()).toBe(false);
        expect(('twyndyllyngs').hasVowels()).toBe(false);
    });
});

describe('toUpper()', function() {
    it('should always return a string', function() {
        expect('example string'.toUpper()).toEqual(jasmine.any(String));
    });

    it('should return an upper case of the calling string', function() {
        expect('upper case'.toUpper()).toBe('UPPER CASE');
        expect('camelCase'.toUpper()).toBe('CAMELCASE');
        expect('MiXeD cAsE'.toUpper()).toBe('MIXED CASE');
    });
});

describe('toLower()', function() {
    it('should return a string', function() {
        expect('example string'.toLower()).toEqual(jasmine.any(String));
    });

    it('should return a lower case of the calling string', function() {
        expect('LOWER CASE'.toLower()).toBe('lower case');
        expect('PascalCaseD'.toLower()).toBe('pascalcased');
        expect('MiXeDcAsE'.toLower()).toBe('mixedcase');
    });
});

describe('ucFirst()', function() {
    it('should return a string', function() {
        expect(''.ucFirst()).toEqual(jasmine.any(String));
    });

    it('should convert first character to uppercase', function() {
        expect('oreofe'.ucFirst()).toBe('Oreofe');
        expect('Ralph'.ucFirst()).toBe('Ralph');
    });
});

describe('isQuestion()', function() {
    it('should always return a boolean', function() {
        expect('example string'.isQuestion()).toEqual(jasmine.any(Boolean));
    });

    it('should return true if string is a question', function() {
        expect('is a question?'.isQuestion()).toBe(true);
        expect('Is Another Question?'.isQuestion()).toBe(true);
    });

    it('should return false if string is not a question', function() {
        expect('is not a question'.isQuestion()).toBe(false);
        expect('Is not Another Question'.isQuestion()).toBe(false);
    });
});

describe('words()', function() {
    it('should always return a typeof object', function() {
        expect('this is an example string'.words())
            .toEqual(jasmine.any(Object));
    });

    it('should always return an array', function() {
        expect('this is an example string'.words() instanceof Array).toBe(true);
    });

    it('should return an array of words in the string', function() {
        expect('this is a string of words'.words()).toEqual(['this', 'is',
        'a', 'string', 'of', 'words']);
        expect('My name is Ore-ofe'.words())
            .toEqual(['My', 'name', 'is', 'Ore-ofe']);
    });

    it('should return empty array if no words are found', function() {
        expect(',./;[]=-'.words()).toEqual([]);
    });
});

describe('wordCount()', function(){
    it('should always return type Number', function(){
        expect('this string'.wordCount()).toEqual(jasmine.any(Number));
    });

    it('should return number of words in a string', function() {
        expect('this is a string of words'.wordCount()).toBe(6);
        expect('My name is Ore-ofe'.wordCount()).toBe(4);
    });

    it('should return 0 if string contains no word', function() {
        expect(',./;[]=-'.wordCount()).toBe(0);
    });
});

describe('toCurrency()', function() {
    it('should return a string', function() {
        expect('111111.00'.toCurrency()).toEqual(jasmine.any(String));
    });

    it('should return a currency formatted string', function() {
        expect('111111.89'.toCurrency()).toBe('111,111.89');
        expect('2111111.89'.toCurrency()).toBe('2,111,111.89');
    });
});<|endoftext|>


<commit_before>'use strict'

// ----------------------------------------------------------------------------

const log = require ('ololog')
    , chai = require ('chai')
    , asTable = require ('as-table')
    , assert = chai.assert
    , testOHLCV = require ('ccxt/js/test/Exchange/test.ohlcv.js')
    , errors = require ('ccxt/js/base/errors.js')

/*  ------------------------------------------------------------------------ */

module.exports = async (exchange, symbol) => {

    // log (symbol.green, 'watching ohlcv...')

    const method = 'watchOHLCV'

    const skippedExchanges = [
        'dsx',
        'idex2', // rinkeby testnet, trades too rare
        'bitvavo',
    ]

    if (skippedExchanges.includes (exchange.id)) {
        log (exchange.id, method, 'test skipped')
        return
    }

    if (!exchange.has[method]) {
        log (exchange.id, 'does not support', method + '() method')
        return
    }

    const timeframe = Object.keys (exchange.timeframes)[0]

    let response = undefined

    let now = Date.now ()
    const ends = now + 15000

    while (now < ends) {

        try {

            response = await exchange[method] (symbol, timeframe)

            now = Date.now ()

            assert (response instanceof Array)

            // log (symbol.green, method, 'returned', Object.values (response).length.toString ().green, 'ohlcvs')
            for (let i = 0; i < response.length; i++) {
                const current = response[i]
                testOHLCV (exchange, current, symbol, now)
                if (i > 0) {
                    const previous = response[i - 1]
                    if (current[0] && previous[0]) {
                        assert (current[0] >= previous[0],
                            'OHLCV timestamp ordering is wrong at candle ' + i.toString () + ' ' + current[0].toString () + ' < ' + previous[0].toString ())
                    }
                }
            }

            response = response.map ((ohlcv) => [
                exchange.iso8601 (ohlcv[0]),
                ohlcv[1],
                ohlcv[2],
                ohlcv[3],
                ohlcv[4],
                ohlcv[5],
            ])

            if (response.length > 0) {
                log (exchange.iso8601 (now), exchange.id, timeframe, symbol, response.length, 'candles', JSON.stringify (response[response.length - 1]))
            }

        } catch (e) {

            log (e)

            if (!(e instanceof errors.NetworkError)) {
                throw e
            }

            now = Date.now ()
        }

        // console.log ('--------------------------------------------------------')
        // log.noLocate (asTable (response))
    }

    return response
}
<commit_msg>watch-methods<commit_after>'use strict'

// ----------------------------------------------------------------------------

const log = require ('ololog')
    , chai = require ('chai')
    , asTable = require ('as-table')
    , assert = chai.assert
    , testOHLCV = require ('ccxt/js/test/Exchange/test.ohlcv.js')
    , errors = require ('ccxt/js/base/errors.js')

/*  ------------------------------------------------------------------------ */

module.exports = async (exchange, symbol) => {

    // log (symbol.green, 'watching ohlcv...')

    const method = 'watchOHLCV'

    const skippedExchanges = [
        'dsx',
        'idex2', // rinkeby testnet, trades too rare
        'bitvavo',
    ]

    if (skippedExchanges.includes (exchange.id)) {
        log (exchange.id, method + '() test skipped')
        return
    }

    if (!exchange.has[method]) {
        log (exchange.id, 'does not support', method + '() method')
        return
    }

    const timeframe = Object.keys (exchange.timeframes)[0]

    let response = undefined

    let now = Date.now ()
    const ends = now + 15000

    while (now < ends) {

        try {

            response = await exchange[method] (symbol, timeframe)

            now = Date.now ()

            assert (response instanceof Array)

            // log (symbol.green, method, 'returned', Object.values (response).length.toString ().green, 'ohlcvs')
            for (let i = 0; i < response.length; i++) {
                const current = response[i]
                testOHLCV (exchange, current, symbol, now)
                if (i > 0) {
                    const previous = response[i - 1]
                    if (current[0] && previous[0]) {
                        assert (current[0] >= previous[0],
                            'OHLCV timestamp ordering is wrong at candle ' + i.toString () + ' ' + current[0].toString () + ' < ' + previous[0].toString ())
                    }
                }
            }

            response = response.map ((ohlcv) => [
                exchange.iso8601 (ohlcv[0]),
                ohlcv[1],
                ohlcv[2],
                ohlcv[3],
                ohlcv[4],
                ohlcv[5],
            ])

            if (response.length > 0) {
                log (exchange.iso8601 (now), exchange.id, timeframe, symbol, response.length, 'candles', JSON.stringify (response[response.length - 1]))
            }

        } catch (e) {

            log (e)

            if (!(e instanceof errors.NetworkError)) {
                throw e
            }

            now = Date.now ()
        }

        // console.log ('--------------------------------------------------------')
        // log.noLocate (asTable (response))
    }

    return response
}
<|endoftext|>


<commit_before>/*
  This view is also used by the Order Detail overlay. If you make any changes, please
  ensure they are compatible with both the Purchase and Order Detail flows.
*/

import $ from 'jquery';
import app from '../../../app';
import loadTemplate from '../../../utils/loadTemplate';
import { formatCurrency, integerToDecimal } from '../../../utils/currency';
import { getSocket } from '../../../utils/serverConnect';
import BaseVw from '../../baseVw';
import ConfirmWallet from './ConfirmWallet';
import qr from 'qr-encode';
import { clipboard, remote } from 'electron';
import { spend } from '../../../models/wallet/Spend';
import { openSimpleMessage } from '../../modals/SimpleMessage';

export default class extends BaseVw {
  constructor(options = {}) {
    if (typeof options.balanceRemaining !== 'number') {
      throw new Error('Please provide the balance remaining in BTC as a number.');
    }

    if (!options.paymentAddress) {
      throw new Error('Please provide the payment address.');
    }

    if (!options.orderId) {
      throw new Error('Please provide an orderId.');
    }

    if (typeof options.isModerated !== 'boolean') {
      throw new Error('Please provide a boolean indicating whether the order is moderated.');
    }

    super(options);
    this.options = options;
    this._balanceRemaining = options.balanceRemaining;
    this.paymentAddress = options.paymentAddress;
    this.orderId = options.orderId;
    this.isModerated = options.isModerated;

    this.boundOnDocClick = this.onDocumentClick.bind(this);
    $(document).on('click', this.boundOnDocClick);

    const serverSocket = getSocket();
    if (serverSocket) {
      this.listenTo(serverSocket, 'message', e => {
        // listen for a payment socket message, to react to payments from all sources
        if (e.jsonData.notification && e.jsonData.notification.type === 'payment') {
          if (e.jsonData.notification.orderId === this.orderId) {
            const amount = integerToDecimal(e.jsonData.notification.fundingTotal, true);
            if (amount >= this.balanceRemaining) {
              this.$confirmWalletConfirm.removeClass('processing');
              this.$confirmWallet.addClass('hide');
              this.trigger('walletPaymentComplete', e.jsonData.notification);
            } else {
              // Ensure the resulting balance has a maximum of 8 decimal places with not
              // trailing zeros.
              this.balanceRemaining = parseFloat((this.balanceRemaining - amount).toFixed(8));
            }
          }
        }
      });
    }
  }

  set balanceRemaining(amount) {
    if (amount !== this._balanceRemaining) {
      this._balanceRemaining = amount;
      this.confirmWallet.render();
      this.$amountDueLine.html(this.amountDueLine);
      this.$qrCodeImg.attr('src', this.qrDataUri);
    }
  }

  get balanceRemaining() {
    return this._balanceRemaining;
  }

  className() {
    return 'pending';
  }

  events() {
    return {
      'click .js-payFromWallet': 'clickPayFromWallet',
      'click .js-payFromAlt': 'clickPayFromAlt',
      'click .js-copyAmount': 'copyAmount',
      'click .js-copyAddress': 'copyAddress',
    };
  }

  onDocumentClick(e) {
    if (!($.contains(this.$confirmWallet[0], e.target))) {
      this.$confirmWallet.addClass('hide');
    }
  }

  clickPayFromWallet(e) {
    e.stopPropagation();
    this.$confirmWallet.removeClass('hide');
  }

  walletCancel() {
    this.$confirmWallet.addClass('hide');
  }

  walletConfirm() {
    this.$confirmWalletConfirm.addClass('processing');

    spend({
      address: this.paymentAddress,
      amount: this.balanceRemaining,
      currency: 'BTC',
    })
      .fail(jqXhr => {
        openSimpleMessage(app.polyglot.t('purchase.errors.paymentFailed'),
          jqXhr.responseJSON && jqXhr.responseJSON.reason || '');
        if (this.isRemoved()) return;
        this.$confirmWalletConfirm.removeClass('processing');
        this.$confirmWallet.addClass('hide');
      });
  }

  clickPayFromAlt() {
    const amount = this.balanceRemaining;
    const shapeshiftURL = `https://shapeshift.io/shifty.html?destination=${this.payURL}&output=BTC&apiKey=6e9fbc30b836f85d339b84f3b60cade3f946d2d49a14207d5546895ecca60233b47ec67304cdcfa06e019231a9d135a7965ae50de0a1e68d6ec01b8e57f2b812&amount=${amount}`;
    const shapeshiftWin = new remote.BrowserWindow({ width: 700, height: 500, frame: true });
    shapeshiftWin.loadURL(shapeshiftURL);
  }

  copyAmount() {
    clipboard.writeText(String(this.balanceRemaining));

    this.$copyAmount.addClass('active');
    if (this.hideCopyAmountTimer) {
      clearTimeout(this.hideCopyAmountTimer);
    }
    this.hideCopyAmountTimer = setTimeout(
      () => this.$copyAmount.removeClass('active'), 3000);
  }

  copyAddress() {
    clipboard.writeText(String(this.paymentAddress));

    this.$copyAddress.addClass('active');
    if (this.hideCopyAddressTimer) {
      clearTimeout(this.hideCopyAddressTimer);
    }
    this.hideCopyAddressTimer = setTimeout(
      () => this.$copyAddress.removeClass('active'), 3000);
  }

  get amountDueLine() {
    return app.polyglot.t('purchase.pendingSection.pay',
      { amountBTC: formatCurrency(this.balanceRemaining, 'BTC') });
  }

  get qrDataUri() {
    const btcURL = `bitcoin:${this.paymentAddress}?amount=${this.balanceRemaining}`;
    return qr(btcURL, { type: 8, size: 5, level: 'Q' });
  }

  get $confirmWallet() {
    return this._$confirmWallet ||
      (this._$confirmWallet = this.$('.js-confirmWallet'));
  }

  get $copyAmount() {
    return this._$copyAmount ||
      (this._$copyAmount = this.$('.js-copyAmount'));
  }

  get $copyAddress() {
    return this._$copyAddress ||
      (this._$copyAddress = this.$('.js-copyAddress'));
  }

  get $confirmWalletConfirm() {
    return this._$confirmWalletConfirm ||
      (this._$confirmWalletConfirm = this.$('.js-confirmWalletConfirm'));
  }

  get $amountDueLine() {
    return this._$amountDueLine ||
      (this._$amountDueLine = this.$('.js-amountDueLine'));
  }

  get $qrCodeImg() {
    return this._$qrCodeImg ||
      (this._$qrCodeImg = this.$('.js-qrCodeImg'));
  }

  remove() {
    $(document).off('click', this.boundOnDocClick);
    super.remove();
  }

  render() {
    const displayCurrency = app.settings.get('localCurrency');

    loadTemplate('modals/purchase/payment.html', (t) => {
      loadTemplate('walletIcon.svg', (walletIconTmpl) => {
        this.$el.html(t({
          displayCurrency,
          amountDueLine: this.amountDueLine,
          paymentAddress: this.paymentAddress,
          qrDataUri: this.qrDataUri,
          walletIconTmpl,
          isModerated: this.isModerated,
        }));
      });

      this._$confirmWallet = null;
      this._$copyAmount = null;
      this._$copyAddress = null;
      this._$confirmWalletConfirm = null;
      this._$amountDueLine = null;
      this._$qrCodeImg = null;

      // remove old view if any on render
      if (this.confirmWallet) this.confirmWallet.remove();
      // add the confirmWallet view
      this.confirmWallet = this.createChild(ConfirmWallet, {
        displayCurrency,
        amount: () => this.balanceRemaining,
      });
      this.listenTo(this.confirmWallet, 'walletCancel', () => this.walletCancel());
      this.listenTo(this.confirmWallet, 'walletConfirm', () => this.walletConfirm());
      this.$confirmWallet.append(this.confirmWallet.render().el);
    });

    return this;
  }
}
<commit_msg>Fix pay url.<commit_after>/*
  This view is also used by the Order Detail overlay. If you make any changes, please
  ensure they are compatible with both the Purchase and Order Detail flows.
*/

import $ from 'jquery';
import app from '../../../app';
import loadTemplate from '../../../utils/loadTemplate';
import { formatCurrency, integerToDecimal } from '../../../utils/currency';
import { getSocket } from '../../../utils/serverConnect';
import BaseVw from '../../baseVw';
import ConfirmWallet from './ConfirmWallet';
import qr from 'qr-encode';
import { clipboard, remote } from 'electron';
import { spend } from '../../../models/wallet/Spend';
import { openSimpleMessage } from '../../modals/SimpleMessage';

export default class extends BaseVw {
  constructor(options = {}) {
    if (typeof options.balanceRemaining !== 'number') {
      throw new Error('Please provide the balance remaining in BTC as a number.');
    }

    if (!options.paymentAddress) {
      throw new Error('Please provide the payment address.');
    }

    if (!options.orderId) {
      throw new Error('Please provide an orderId.');
    }

    if (typeof options.isModerated !== 'boolean') {
      throw new Error('Please provide a boolean indicating whether the order is moderated.');
    }

    super(options);
    this.options = options;
    this._balanceRemaining = options.balanceRemaining;
    this.paymentAddress = options.paymentAddress;
    this.orderId = options.orderId;
    this.isModerated = options.isModerated;

    this.boundOnDocClick = this.onDocumentClick.bind(this);
    $(document).on('click', this.boundOnDocClick);

    const serverSocket = getSocket();
    if (serverSocket) {
      this.listenTo(serverSocket, 'message', e => {
        // listen for a payment socket message, to react to payments from all sources
        if (e.jsonData.notification && e.jsonData.notification.type === 'payment') {
          if (e.jsonData.notification.orderId === this.orderId) {
            const amount = integerToDecimal(e.jsonData.notification.fundingTotal, true);
            if (amount >= this.balanceRemaining) {
              this.$confirmWalletConfirm.removeClass('processing');
              this.$confirmWallet.addClass('hide');
              this.trigger('walletPaymentComplete', e.jsonData.notification);
            } else {
              // Ensure the resulting balance has a maximum of 8 decimal places with not
              // trailing zeros.
              this.balanceRemaining = parseFloat((this.balanceRemaining - amount).toFixed(8));
            }
          }
        }
      });
    }
  }

  set balanceRemaining(amount) {
    if (amount !== this._balanceRemaining) {
      this._balanceRemaining = amount;
      this.confirmWallet.render();
      this.$amountDueLine.html(this.amountDueLine);
      this.$qrCodeImg.attr('src', this.qrDataUri);
    }
  }

  get balanceRemaining() {
    return this._balanceRemaining;
  }

  className() {
    return 'pending';
  }

  events() {
    return {
      'click .js-payFromWallet': 'clickPayFromWallet',
      'click .js-payFromAlt': 'clickPayFromAlt',
      'click .js-copyAmount': 'copyAmount',
      'click .js-copyAddress': 'copyAddress',
    };
  }

  onDocumentClick(e) {
    if (!($.contains(this.$confirmWallet[0], e.target))) {
      this.$confirmWallet.addClass('hide');
    }
  }

  clickPayFromWallet(e) {
    e.stopPropagation();
    this.$confirmWallet.removeClass('hide');
  }

  walletCancel() {
    this.$confirmWallet.addClass('hide');
  }

  walletConfirm() {
    this.$confirmWalletConfirm.addClass('processing');

    spend({
      address: this.paymentAddress,
      amount: this.balanceRemaining,
      currency: 'BTC',
    })
      .fail(jqXhr => {
        openSimpleMessage(app.polyglot.t('purchase.errors.paymentFailed'),
          jqXhr.responseJSON && jqXhr.responseJSON.reason || '');
        if (this.isRemoved()) return;
        this.$confirmWalletConfirm.removeClass('processing');
        this.$confirmWallet.addClass('hide');
      });
  }

  clickPayFromAlt() {
    const amount = this.balanceRemaining;
    const shapeshiftURL = `https://shapeshift.io/shifty.html?destination=${this.paymentAddress}&output=BTC&apiKey=6e9fbc30b836f85d339b84f3b60cade3f946d2d49a14207d5546895ecca60233b47ec67304cdcfa06e019231a9d135a7965ae50de0a1e68d6ec01b8e57f2b812&amount=${amount}`;
    const shapeshiftWin = new remote.BrowserWindow({ width: 700, height: 500, frame: true });
    shapeshiftWin.loadURL(shapeshiftURL);
  }

  copyAmount() {
    clipboard.writeText(String(this.balanceRemaining));

    this.$copyAmount.addClass('active');
    if (this.hideCopyAmountTimer) {
      clearTimeout(this.hideCopyAmountTimer);
    }
    this.hideCopyAmountTimer = setTimeout(
      () => this.$copyAmount.removeClass('active'), 3000);
  }

  copyAddress() {
    clipboard.writeText(String(this.paymentAddress));

    this.$copyAddress.addClass('active');
    if (this.hideCopyAddressTimer) {
      clearTimeout(this.hideCopyAddressTimer);
    }
    this.hideCopyAddressTimer = setTimeout(
      () => this.$copyAddress.removeClass('active'), 3000);
  }

  get amountDueLine() {
    return app.polyglot.t('purchase.pendingSection.pay',
      { amountBTC: formatCurrency(this.balanceRemaining, 'BTC') });
  }

  get qrDataUri() {
    const btcURL = `bitcoin:${this.paymentAddress}?amount=${this.balanceRemaining}`;
    return qr(btcURL, { type: 8, size: 5, level: 'Q' });
  }

  get $confirmWallet() {
    return this._$confirmWallet ||
      (this._$confirmWallet = this.$('.js-confirmWallet'));
  }

  get $copyAmount() {
    return this._$copyAmount ||
      (this._$copyAmount = this.$('.js-copyAmount'));
  }

  get $copyAddress() {
    return this._$copyAddress ||
      (this._$copyAddress = this.$('.js-copyAddress'));
  }

  get $confirmWalletConfirm() {
    return this._$confirmWalletConfirm ||
      (this._$confirmWalletConfirm = this.$('.js-confirmWalletConfirm'));
  }

  get $amountDueLine() {
    return this._$amountDueLine ||
      (this._$amountDueLine = this.$('.js-amountDueLine'));
  }

  get $qrCodeImg() {
    return this._$qrCodeImg ||
      (this._$qrCodeImg = this.$('.js-qrCodeImg'));
  }

  remove() {
    $(document).off('click', this.boundOnDocClick);
    super.remove();
  }

  render() {
    const displayCurrency = app.settings.get('localCurrency');

    loadTemplate('modals/purchase/payment.html', (t) => {
      loadTemplate('walletIcon.svg', (walletIconTmpl) => {
        this.$el.html(t({
          displayCurrency,
          amountDueLine: this.amountDueLine,
          paymentAddress: this.paymentAddress,
          qrDataUri: this.qrDataUri,
          walletIconTmpl,
          isModerated: this.isModerated,
        }));
      });

      this._$confirmWallet = null;
      this._$copyAmount = null;
      this._$copyAddress = null;
      this._$confirmWalletConfirm = null;
      this._$amountDueLine = null;
      this._$qrCodeImg = null;

      // remove old view if any on render
      if (this.confirmWallet) this.confirmWallet.remove();
      // add the confirmWallet view
      this.confirmWallet = this.createChild(ConfirmWallet, {
        displayCurrency,
        amount: () => this.balanceRemaining,
      });
      this.listenTo(this.confirmWallet, 'walletCancel', () => this.walletCancel());
      this.listenTo(this.confirmWallet, 'walletConfirm', () => this.walletConfirm());
      this.$confirmWallet.append(this.confirmWallet.render().el);
    });

    return this;
  }
}
<|endoftext|>


<commit_before>var knob = document.getElementById('knob');

knob.style.left = '35px';
knob.style.top = '50px';

var currentGear = 1;

var gears = {
    1: { left: 35, top: 50, neutral: 'left-neutral', pair: 2 },
    2: { left: 35, top: 200, neutral: 'left-neutral', pair: 1 },
    3: { left: 125, top: 50, neutral: 'center-neutral', pair: 4 },
    4: { left: 125, top: 200, neutral: 'center-neutral', pair: 3 },
    5: { left: 215, top: 50, neutral: 'right-neutral', pair: 'reverse' },
    reverse: { left: 215, top: 200, neutral: 'right-neutral', pair: 5 },
    'left-neutral': { left: 35, top: 125 },
    'center-neutral': { left: 125, top: 125 },
    'right-neutral': { left: 215, top: 125 },
}

var shift = function(gear) {
    if (currentGear === gear) { return; }

    if (currentGear == gears[gear]['pair']) {
        knob.style.top = gears[gear]['top'] + 'px';
    } else {
        knob.style.top = gears[gears[gear]['neutral']]['top'] + 'px';

        window.setTimeout(function() {
            knob.style.left = gears[gear]['left'] + 'px';

            window.setTimeout(function() {
                knob.style.top = gears[gear]['top'] + 'px';
            }, 600);
        }, 1000);
    }

    currentGear = gear;

    knob.classList = gears[gear]['class'];
}

document.onkeyup = function(e) {
    switch(e.which) {
        case 49:
            shift(1);
            break;
        case 50:
            shift(2);
            break;
        case 51:
            shift(3);
            break;
        case 52:
            shift(4);
            break;
        case 53:
            shift(5);
            break;
        case 82:
            shift('reverse');
            break;
    }
}<commit_msg>clean up old code<commit_after>var knob = document.getElementById('knob');

knob.style.left = '35px';
knob.style.top = '50px';

var currentGear = 1;

var gears = {
    1: { left: 35, top: 50, neutral: 'left-neutral', pair: 2 },
    2: { left: 35, top: 200, neutral: 'left-neutral', pair: 1 },
    3: { left: 125, top: 50, neutral: 'center-neutral', pair: 4 },
    4: { left: 125, top: 200, neutral: 'center-neutral', pair: 3 },
    5: { left: 215, top: 50, neutral: 'right-neutral', pair: 'reverse' },
    reverse: { left: 215, top: 200, neutral: 'right-neutral', pair: 5 },
    'left-neutral': { left: 35, top: 125 },
    'center-neutral': { left: 125, top: 125 },
    'right-neutral': { left: 215, top: 125 },
}

var shift = function(gear) {
    if (currentGear === gear) { return; }

    if (currentGear == gears[gear]['pair']) {
        knob.style.top = gears[gear]['top'] + 'px';
    } else {
        knob.style.top = gears[gears[gear]['neutral']]['top'] + 'px';

        window.setTimeout(function() {
            knob.style.left = gears[gear]['left'] + 'px';

            window.setTimeout(function() {
                knob.style.top = gears[gear]['top'] + 'px';
            }, 600);
        }, 1000);
    }

    currentGear = gear;
}

document.onkeyup = function(e) {
    switch(e.which) {
        case 49:
            shift(1);
            break;
        case 50:
            shift(2);
            break;
        case 51:
            shift(3);
            break;
        case 52:
            shift(4);
            break;
        case 53:
            shift(5);
            break;
        case 82:
            shift('reverse');
            break;
    }
}<|endoftext|>