<commit_before>var CMS = CMS ? CMS : {};

CMS.grid = function () {
    "use strict";

    var inputCursorPosition = 0,
        inputName,
        inputBuffer,
        filtering = false;

    var quickSwitch = function (data, gridId) {
        $('#' + gridId).html(data.body);
        $('#' + gridId + '-paginator').html(data.paginator);
        //$('.grid-anchor').html(data.body);
        //$('.paginator-anchor').html(data.paginator);
        initPicker();
    };

    var rememberCursor = function (object) {
        inputBuffer = object.val();
        inputCursorPosition = object[0].selectionStart;
        inputName = object.attr('name');
    };

    var initPicker = function () {
        $('.grid-picker').datetimepicker({ format: 'Y-m-d', allowBlank: true, scrollInput: false, scrollMonth: true, timepicker: false });
        $.datetimepicker.setLocale(request.locale);
    };

    var filter = function (field) {
        var filter = field.attr('name'),
            value = field.val();
        filtering = true;
        field.parent('div').parent('th').parent('tr').parent('thead').find('input.grid-picker').prop('disabled', true);
        $.ajax({
            url: window.location,
            type: 'POST',
            data: { filter: filter, value: value },
            success: function (data) {
                quickSwitch(data, field.closest('table').attr('id'));
                if (!inputName) {
                    filtering = false;
                    return;
                }
                var element = $('input[name=\'' + inputName + '\']');
                element.focus();
                element.val(inputBuffer);
                try {
                    element[0].setSelectionRange(inputCursorPosition, inputCursorPosition);
                } catch (e) { }
                inputName = null;
                inputBuffer = null;
                filtering = false;
                return true;
            }
        });
    };

    var initPaginator = function () {
        $('div.grid').on('click', ".page-link", function (event) {
            var filter = $(this).parent('li').parent('ul').data('name'),
                value = $(this).data('page'),
                gridId = $(this).parent('li').parent('ul').parent('div').parent('div.row').parent('div.grid').find('div.row > div > table.grid-anchor').attr('id');
            $.ajax({
                url: window.location,
                type: 'POST',
                data: { filter: filter, value: value },
                success: function (data) {
                    quickSwitch(data, gridId);
                }
            });
        });
    };

    var initGridFilter = function () {
        $('div.grid').on('keyup', ".grid-filter", function (event) {
            rememberCursor($(this));
        });

        $('div.grid').on('change', ".grid-range > input", function () {
            var from = $(this).parent('div.input-group').children('input.from').val();
            var to = $(this).parent('div.input-group').children('input.to').val();
            $(this).parent('div.input-group').parent('div.form-group').children('input.hidden').val(from + ';' + to);
            if (!filtering) {
                filter($(this).parent('div.input-group').parent('div.form-group').children('input.hidden'));
            }
        });

        $('div.grid').on('change', ".grid-filter", function () {
            if (!filtering) {
                filter($(this));
            }
        });

        $('div.grid').on('click', ".grid-filter", function () {
            rememberCursor($(this));
        });

        $('div.grid').on('focus', "a.order", function () {
            inputName = null;
        });

    };

    var initGridOrder = function () {
        //sortowanie grida
        $('div.grid').on('click', 'th > div.form-group > a.order', function () {
            var field = $(this).attr('href'),
                method = $(this).attr('data-method'),
                gridId = $(this).parent('div').parent('th').parent('tr').parent('thead').parent('table').attr('id');
            $.ajax({
                url: window.location,
                type: 'POST',
                data: { order: field, method: method },
                success: function (data) {
                    quickSwitch(data, gridId);
                }
            });
            return false;
        });
    };

    var initGridOperation = function () {
        //akcja na zmianie checkboxa
        $('div.grid').on('change', 'td > label.control-checkbox > input.checkbox', function () {
            var id = $(this).attr('id').split('-');
            $.ajax({
                url: window.location,
                type: 'POST',
                data: { id: id[1], name: id[0], value: $(this).val(), checked: $(this).is(':checked') }
            });
        });
    };

    initGridFilter();
    initGridOrder();
    initGridOperation();
    initPaginator();
    initPicker();
};

$(document).ready(function () {
    "use strict";
    CMS.grid();
});
<commit_msg>critical grid fix (sorting) + multiple grids on a single page support<commit_after>var CMS = CMS ? CMS : {};

CMS.grid = function () {
    "use strict";

    var inputCursorPosition = 0,
        inputName,
        inputBuffer,
        filtering = false;

    var quickSwitch = function (data, gridId) {
        $('#' + gridId).html(data.body);
        $('#' + gridId + '-paginator').html(data.paginator);
        initPicker();
    };

    var rememberCursor = function (object) {
        inputBuffer = object.val();
        inputCursorPosition = object[0].selectionStart;
        inputName = object.attr('name');
    };

    var initPicker = function () {
        $('.grid-picker').datetimepicker({ format: 'Y-m-d', allowBlank: true, scrollInput: false, scrollMonth: true, timepicker: false });
        $.datetimepicker.setLocale(request.locale);
    };

    var filter = function (field) {
        var filter = field.attr('name'),
            value = field.val();
        filtering = true;
        field.parent('div').parent('th').parent('tr').parent('thead').find('input.grid-picker').prop('disabled', true);
        $.ajax({
            url: window.location,
            type: 'POST',
            data: { filter: filter, value: value },
            success: function (data) {
                quickSwitch(data, field.closest('table').attr('id'));
                if (!inputName) {
                    filtering = false;
                    return;
                }
                var element = $('input[name=\'' + inputName + '\']');
                element.focus();
                element.val(inputBuffer);
                try {
                    element[0].setSelectionRange(inputCursorPosition, inputCursorPosition);
                } catch (e) { }
                inputName = null;
                inputBuffer = null;
                filtering = false;
                return true;
            }
        });
    };

    var initPaginator = function () {
        $('div.grid').on('click', ".page-link", function (event) {
            var filter = $(this).parent('li').parent('ul').data('name'),
                value = $(this).data('page'),
                gridId = $(this).parent('li').parent('ul').parent('div').parent('div.row').parent('div.grid').find('div.row > div > table.grid-anchor').attr('id');
            $.ajax({
                url: window.location,
                type: 'POST',
                data: { filter: filter, value: value },
                success: function (data) {
                    quickSwitch(data, gridId);
                }
            });
        });
    };

    var initGridFilter = function () {
        $('div.grid').on('keyup', ".grid-filter", function (event) {
            rememberCursor($(this));
        });

        $('div.grid').on('change', ".grid-range > input", function () {
            var from = $(this).parent('div.input-group').children('input.from').val();
            var to = $(this).parent('div.input-group').children('input.to').val();
            $(this).parent('div.input-group').parent('div.form-group').children('input.hidden').val(from + ';' + to);
            if (!filtering) {
                filter($(this).parent('div.input-group').parent('div.form-group').children('input.hidden'));
            }
        });

        $('div.grid').on('change', ".grid-filter", function () {
            if (!filtering) {
                filter($(this));
            }
        });

        $('div.grid').on('click', ".grid-filter", function () {
            rememberCursor($(this));
        });

        $('div.grid').on('focus', "a.order", function () {
            inputName = null;
        });

    };

    var initGridOrder = function () {
        //sortowanie grida
        $('div.grid').on('click', 'th > div.form-group > a.order', function () {
            var field = $(this).attr('href'),
                method = $(this).attr('data-method'),
                gridId = $(this).parent('div').parent('th').parent('tr').parent('thead').parent('table').attr('id');
            $.ajax({
                url: window.location,
                type: 'POST',
                data: { order: field, method: method },
                success: function (data) {
                    quickSwitch(data, gridId);
                }
            });
            return false;
        });
    };

    var initGridOperation = function () {
        //akcja na zmianie checkboxa
        $('div.grid').on('change', 'td > label.control-checkbox > input.checkbox', function () {
            var id = $(this).attr('id').split('-');
            $.ajax({
                url: window.location,
                type: 'POST',
                data: { id: id[1], name: id[0], value: $(this).val(), checked: $(this).is(':checked') }
            });
        });
    };

    initGridFilter();
    initGridOrder();
    initGridOperation();
    initPaginator();
    initPicker();
};

$(document).ready(function () {
    "use strict";
    CMS.grid();
});
<|endoftext|>


<commit_before>module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        modules: false,
        targets: {
          browsers: [
            '> 1%',
            'last 2 versions',
            'not ie <= 8',
          ],
        },
      },
    ],
  ],
  comments: false,
  env: {
    test: {
      presets: [
        '@babel/preset-env',
      ],
    },
  },
};
<commit_msg>fix(babel): enable proper code transpiling during test<commit_after>module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        modules: false,
        targets: {
          browsers: [
            '> 1%',
            'last 2 versions',
            'not ie <= 8',
          ],
        },
      },
    ],
  ],
  comments: false,
  env: {
    test: {
      presets: [
        [
          '@babel/preset-env',
          {
            targets: {
              node: 'current',
            },
          },
        ],
      ],
    },
  },
};
<|endoftext|>


<commit_before>module.exports = function(api) {
  var validEnv = ['development', 'test', 'production'];
  var currentEnv = api.env();
  var isDevelopmentEnv = api.env('development');
  var isProductionEnv = api.env('production');
  var isTestEnv = api.env('test');

  if (!validEnv.includes(currentEnv)) {
    throw new Error(
      'Please specify a valid `NODE_ENV` or ' +
      '`BABEL_ENV` environment variables. Valid values are "development", ' +
      '"test", and "production". Instead, received: ' +
      JSON.stringify(currentEnv) +
      '.'
    )
  }

  return {
    presets: [
      isTestEnv && [
        require('@babel/preset-env').default,
        {
          targets: {
            node: 'current'
          }
        }
      ],
      (isProductionEnv || isDevelopmentEnv) && [
        require('@babel/preset-env').default,
        {
          forceAllTransforms: true,
          useBuiltIns: 'entry',
          modules: false,
          exclude: ['transform-typeof-symbol']
        }
      ],
      require('@babel/preset-react')
    ].filter(Boolean),
    plugins: [
      require('babel-plugin-macros'),
      require('@babel/plugin-syntax-dynamic-import').default,
      isTestEnv && require('babel-plugin-dynamic-import-node'),
      require('@babel/plugin-transform-destructuring').default,
      require('@babel/plugin-proposal-class-properties').default,
      require('@babel/plugin-proposal-object-rest-spread').default,
      [
        require('@babel/plugin-transform-runtime').default,
        {
          helpers: false,
          regenerator: true
        }
      ],
      [
        require('@babel/plugin-transform-regenerator').default,
        {
          async: false
        }
      ]
    ].filter(Boolean)
  }
};
<commit_msg>js: Be explicit about using core-js2 with @babel/preset-env<commit_after>module.exports = function(api) {
  var validEnv = ['development', 'test', 'production'];
  var currentEnv = api.env();
  var isDevelopmentEnv = api.env('development');
  var isProductionEnv = api.env('production');
  var isTestEnv = api.env('test');

  if (!validEnv.includes(currentEnv)) {
    throw new Error(
      'Please specify a valid `NODE_ENV` or ' +
      '`BABEL_ENV` environment variables. Valid values are "development", ' +
      '"test", and "production". Instead, received: ' +
      JSON.stringify(currentEnv) +
      '.'
    )
  }

  return {
    presets: [
      isTestEnv && [
        require('@babel/preset-env').default,
        {
          targets: {
            node: 'current'
          }
        }
      ],
      (isProductionEnv || isDevelopmentEnv) && [
        require('@babel/preset-env').default,
        {
          forceAllTransforms: true,
          useBuiltIns: 'entry',
          corejs: 2,
          modules: false,
          exclude: ['transform-typeof-symbol']
        }
      ],
      require('@babel/preset-react')
    ].filter(Boolean),
    plugins: [
      require('babel-plugin-macros'),
      require('@babel/plugin-syntax-dynamic-import').default,
      isTestEnv && require('babel-plugin-dynamic-import-node'),
      require('@babel/plugin-transform-destructuring').default,
      require('@babel/plugin-proposal-class-properties').default,
      require('@babel/plugin-proposal-object-rest-spread').default,
      [
        require('@babel/plugin-transform-runtime').default,
        {
          helpers: false,
          regenerator: true
        }
      ],
      [
        require('@babel/plugin-transform-regenerator').default,
        {
          async: false
        }
      ]
    ].filter(Boolean)
  }
};
<|endoftext|>


<commit_before>/**
 * Unit test framework used with thaliTape.
 */

'use strict';

var util = require('util');
var TestFramework = require('./TestFramework');

var logger = console;

function UnitTestFramework(testConfig, _logger)
{
  if (_logger) {
    logger = _logger;
  }

  var configFile = './UnitTestConfig';
  var unitTestConfig = require(configFile);
  if (testConfig.userConfig) {
    unitTestConfig = testConfig.userConfig;
  }

  UnitTestFramework.super_.call(this, testConfig, unitTestConfig, _logger);

  // Track which platforms we expect to be running on
  var self = this;
  self.runningTests = Object.keys(self.requiredDevices).filter(
    function (platform) {
      logger.info(
        'Require %d %s devices',
        self.requiredDevices[platform] || 0, platform
      );
      return self.requiredDevices[platform];
    }
  );
}

util.inherits(UnitTestFramework, TestFramework);

+UnitTestFramework.prototype.abortRun =
  function (devices, platform, tests, results) {

    // Tests on all devices are aborted
    logger.info('Test run on %s aborted', platform);

    // Log test results from the server
    this.testReport(platform, tests, results);

    // Signal devices to quit
    devices.forEach(function (device) {
      device.socket.emit('aborted');
    });

    // We're done running for this platform
    this.runningTests = this.runningTests.filter(function (p) {
      return p !== platform;
    });

    // There may be other platforms still running
    if (this.runningTests.length === 0) {
      this.emit('completed');
    }
  };

UnitTestFramework.prototype.finishRun =
  function (devices, platform, tests, results) {

    // All devices have completed all their tests
    logger.info('Test run on %s complete', platform);

    // The whole point !! Log test results from the
    // server
    this.testReport(platform, tests, results);

    // Signal devices to quit
    devices.forEach(function (device) {
      device.socket.emit('complete');
    });

    // We're done running for this platform..
    this.runningTests = this.runningTests.filter(function (p) {
      return p !== platform;
    });

    // There may be other platforms still running
    if (this.runningTests.length === 0) {
      this.emit('completed');
    }
  };

UnitTestFramework.prototype.startTests = function (platform, tests) {

  var toComplete;
  var results = {};

  if (!tests) {
    if (this.devices[platform].length) {
      // Default to all tests named by first device
      tests = this.devices[platform][0].tests;
    } else {
      tests = [];
    }
  }

  // Copy arrays
  var _tests = tests.slice();
  var devices = this.devices[platform].slice();

  if (devices.length < 2) {
    logger.warn(
      'Aborting unit test run for %s. At least 2 devices needed, having %d device(s)',
      platform, this.devices[platform].length
    );
    this.abortRun(devices, platform, tests, results);
    return;
  }

  logger.info(
    'Starting unit test run on %d %s devices',
    this.devices[platform].length, platform
  );

  var self = this;
  function doTest(test, cb) {

    logger.info('Running on %s test: %s', platform, test);

    function emit(device, msg, data) {
      // Try to retry 120 times every second, because
      // it might be that the socket connection is temporarily
      // down while the retries are tried so this gives
      // the device 2 minutes to reconnect.
      var retries = 120;
      var retryInterval = 1000;
      var emitTimeout = null;

      var acknowledged = false;
      device.socket.once(util.format('%s_ok', msg), function () {
        acknowledged = true;
        if (emitTimeout !== null) {
          clearTimeout(emitTimeout);
        }
      });

      // Emit message every second until acknowledged
      function _emit() {
        if (!acknowledged) {
          if (data) {
            device.socket.emit(msg, data);
          } else {
            device.socket.emit(msg);
          }
          if (--retries > 0) {
            emitTimeout = setTimeout(_emit, retryInterval);
          } else {
            logger.debug('Too many emit retries to device: %s',
              device.deviceName);
          }
        }
      }
      setTimeout(_emit, 0);
    }

    var nextStageData = [];
    // Convenience: Move to next stage in test
    function doNext(stage, stageData) {
      if (stageData) {
        nextStageData.push({
          uuid: stageData.uuid,
          data: stageData.data
        });
      }
      // We need to have seen all devices report in before we
      // can proceed to the next stage
      if (--toComplete === 0) {
        toComplete = devices.length;
        devices.forEach(function (device) {
          // Tell each device to proceed to the next stage
          emit(
            device,
            stage + '_' + test,
            JSON.stringify(nextStageData)
          );
        });
        nextStageData = [];
      }
    }

    // Add event handlers for each stage of a single test
    // Test proceed in the order shown below
    toComplete = devices.length;
    devices.forEach(function (device) {

      function setResult(result) {
        results[result.test] = result.success &&
          (result.test in results ? results[result.test] :
            true);
      }

      // The device has completed setup for this test
      device.socket.once('setup_complete', function (result) {
        var parsedResult = JSON.parse(result);
        setResult(parsedResult);
        doNext('start_test', {
          uuid: device.uuid,
          data: parsedResult.data
        });
      });

      // The device has completed it's test
      device.socket.once('test_complete', function (result) {
        setResult(JSON.parse(result));
        doNext('teardown');
      });

      // The device has completed teardown for this test
      device.socket.once('teardown_complete', function (result) {
        var parsedResult = JSON.parse(result);
        setResult(parsedResult);
        if (--toComplete === 0) {
          if (!results[parsedResult.test]) {
            logger.warn(
              'Failed on %s test: %s', platform, test
            );
          }
          cb();
        }
      });

      // All server-side handlers for this test are now installed, let's go..
      emit(device, 'setup_' + test);
    });
  }

  function nextTest() {
    // Pop the completed test off the list
    // and move to next test
    tests.shift();
    if (tests.length) {
      process.nextTick(function () {
        doTest(tests[0], nextTest);
      });
    } else {
      // ALL DONE !!
      self.finishRun(devices, platform, _tests, results);
    }
  }

  toComplete = devices.length;

  devices.forEach(function (device) {
    // Wait for devices to signal they've scheduled their
    // test runs and then begin
    device.socket.once('schedule_complete', function () {
      if (tests.length) {
        if (--toComplete === 0) {
          doTest(tests[0], nextTest);
        }
      } else {
        logger.warn('Schedule complete with no tests to run');
        self.finishRun(devices, platform, _tests, results);
      }
    });

    // Tell devices to set tests up to run in the order we supply
    device.socket.emit('schedule', JSON.stringify(tests));
  });
};

UnitTestFramework.prototype.testReport = function (platform, tests, results) {

  logger.info('\n\n-== UNIT TEST RESULTS ==-');

  var passed = 0;
  for (var test in results) {
    passed += results[test];
  }
  var failed = tests.length - passed;

  logger.info('PLATFORM: %s', platform);
  logger.info('RESULT: %s', passed === tests.length ? 'PASS' : 'FAIL');
  logger.info('%d of %d tests completed',
    Object.keys(results).length, tests.length);
  logger.info('%d/%d passed (%d failures)',
    passed, tests.length, failed);

  if (failed > 0) {
    logger.info('\n\n--- Failed tests ---');
    for (test in results) {
      if (!results[test]) {
        logger.warn(test + ' - fail');
      }
    }
  }

  logger.info('\n\n-== END ==-');
};

module.exports = UnitTestFramework;
<commit_msg>Typo fix<commit_after>/**
 * Unit test framework used with thaliTape.
 */

'use strict';

var util = require('util');
var TestFramework = require('./TestFramework');

var logger = console;

function UnitTestFramework(testConfig, _logger)
{
  if (_logger) {
    logger = _logger;
  }

  var configFile = './UnitTestConfig';
  var unitTestConfig = require(configFile);
  if (testConfig.userConfig) {
    unitTestConfig = testConfig.userConfig;
  }

  UnitTestFramework.super_.call(this, testConfig, unitTestConfig, _logger);

  // Track which platforms we expect to be running on
  var self = this;
  self.runningTests = Object.keys(self.requiredDevices).filter(
    function (platform) {
      logger.info(
        'Require %d %s devices',
        self.requiredDevices[platform] || 0, platform
      );
      return self.requiredDevices[platform];
    }
  );
}

util.inherits(UnitTestFramework, TestFramework);

UnitTestFramework.prototype.abortRun =
  function (devices, platform, tests, results) {

    // Tests on all devices are aborted
    logger.info('Test run on %s aborted', platform);

    // Log test results from the server
    this.testReport(platform, tests, results);

    // Signal devices to quit
    devices.forEach(function (device) {
      device.socket.emit('aborted');
    });

    // We're done running for this platform
    this.runningTests = this.runningTests.filter(function (p) {
      return p !== platform;
    });

    // There may be other platforms still running
    if (this.runningTests.length === 0) {
      this.emit('completed');
    }
  };

UnitTestFramework.prototype.finishRun =
  function (devices, platform, tests, results) {

    // All devices have completed all their tests
    logger.info('Test run on %s complete', platform);

    // The whole point !! Log test results from the
    // server
    this.testReport(platform, tests, results);

    // Signal devices to quit
    devices.forEach(function (device) {
      device.socket.emit('complete');
    });

    // We're done running for this platform..
    this.runningTests = this.runningTests.filter(function (p) {
      return p !== platform;
    });

    // There may be other platforms still running
    if (this.runningTests.length === 0) {
      this.emit('completed');
    }
  };

UnitTestFramework.prototype.startTests = function (platform, tests) {

  var toComplete;
  var results = {};

  if (!tests) {
    if (this.devices[platform].length) {
      // Default to all tests named by first device
      tests = this.devices[platform][0].tests;
    } else {
      tests = [];
    }
  }

  // Copy arrays
  var _tests = tests.slice();
  var devices = this.devices[platform].slice();

  if (devices.length < 2) {
    logger.warn(
      'Aborting unit test run for %s. At least 2 devices needed, having %d device(s)',
      platform, this.devices[platform].length
    );
    this.abortRun(devices, platform, tests, results);
    return;
  }

  logger.info(
    'Starting unit test run on %d %s devices',
    this.devices[platform].length, platform
  );

  var self = this;
  function doTest(test, cb) {

    logger.info('Running on %s test: %s', platform, test);

    function emit(device, msg, data) {
      // Try to retry 120 times every second, because
      // it might be that the socket connection is temporarily
      // down while the retries are tried so this gives
      // the device 2 minutes to reconnect.
      var retries = 120;
      var retryInterval = 1000;
      var emitTimeout = null;

      var acknowledged = false;
      device.socket.once(util.format('%s_ok', msg), function () {
        acknowledged = true;
        if (emitTimeout !== null) {
          clearTimeout(emitTimeout);
        }
      });

      // Emit message every second until acknowledged
      function _emit() {
        if (!acknowledged) {
          if (data) {
            device.socket.emit(msg, data);
          } else {
            device.socket.emit(msg);
          }
          if (--retries > 0) {
            emitTimeout = setTimeout(_emit, retryInterval);
          } else {
            logger.debug('Too many emit retries to device: %s',
              device.deviceName);
          }
        }
      }
      setTimeout(_emit, 0);
    }

    var nextStageData = [];
    // Convenience: Move to next stage in test
    function doNext(stage, stageData) {
      if (stageData) {
        nextStageData.push({
          uuid: stageData.uuid,
          data: stageData.data
        });
      }
      // We need to have seen all devices report in before we
      // can proceed to the next stage
      if (--toComplete === 0) {
        toComplete = devices.length;
        devices.forEach(function (device) {
          // Tell each device to proceed to the next stage
          emit(
            device,
            stage + '_' + test,
            JSON.stringify(nextStageData)
          );
        });
        nextStageData = [];
      }
    }

    // Add event handlers for each stage of a single test
    // Test proceed in the order shown below
    toComplete = devices.length;
    devices.forEach(function (device) {

      function setResult(result) {
        results[result.test] = result.success &&
          (result.test in results ? results[result.test] :
            true);
      }

      // The device has completed setup for this test
      device.socket.once('setup_complete', function (result) {
        var parsedResult = JSON.parse(result);
        setResult(parsedResult);
        doNext('start_test', {
          uuid: device.uuid,
          data: parsedResult.data
        });
      });

      // The device has completed it's test
      device.socket.once('test_complete', function (result) {
        setResult(JSON.parse(result));
        doNext('teardown');
      });

      // The device has completed teardown for this test
      device.socket.once('teardown_complete', function (result) {
        var parsedResult = JSON.parse(result);
        setResult(parsedResult);
        if (--toComplete === 0) {
          if (!results[parsedResult.test]) {
            logger.warn(
              'Failed on %s test: %s', platform, test
            );
          }
          cb();
        }
      });

      // All server-side handlers for this test are now installed, let's go..
      emit(device, 'setup_' + test);
    });
  }

  function nextTest() {
    // Pop the completed test off the list
    // and move to next test
    tests.shift();
    if (tests.length) {
      process.nextTick(function () {
        doTest(tests[0], nextTest);
      });
    } else {
      // ALL DONE !!
      self.finishRun(devices, platform, _tests, results);
    }
  }

  toComplete = devices.length;

  devices.forEach(function (device) {
    // Wait for devices to signal they've scheduled their
    // test runs and then begin
    device.socket.once('schedule_complete', function () {
      if (tests.length) {
        if (--toComplete === 0) {
          doTest(tests[0], nextTest);
        }
      } else {
        logger.warn('Schedule complete with no tests to run');
        self.finishRun(devices, platform, _tests, results);
      }
    });

    // Tell devices to set tests up to run in the order we supply
    device.socket.emit('schedule', JSON.stringify(tests));
  });
};

UnitTestFramework.prototype.testReport = function (platform, tests, results) {

  logger.info('\n\n-== UNIT TEST RESULTS ==-');

  var passed = 0;
  for (var test in results) {
    passed += results[test];
  }
  var failed = tests.length - passed;

  logger.info('PLATFORM: %s', platform);
  logger.info('RESULT: %s', passed === tests.length ? 'PASS' : 'FAIL');
  logger.info('%d of %d tests completed',
    Object.keys(results).length, tests.length);
  logger.info('%d/%d passed (%d failures)',
    passed, tests.length, failed);

  if (failed > 0) {
    logger.info('\n\n--- Failed tests ---');
    for (test in results) {
      if (!results[test]) {
        logger.warn(test + ' - fail');
      }
    }
  }

  logger.info('\n\n-== END ==-');
};

module.exports = UnitTestFramework;
<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var largestString = function(words) {
  if (words && words.length > 1) {
    return words.reduce(function(x,y) {
      return Math.max(x,y.length);
    }, words[0].length);
  }
};

var eliminateSubstrings = function(words) {
  var rest = [];

  return rest;
};

describe('words smushing', function() {
  describe('largest string', function() {
    it('is not defined for 0 length arrays', function() {
      assert(!largestString([]));
    });

    it('returns the length of the longest string', function() {
      assert.equal(5, largestString(['a','b','bc','defgh']));
    });
  });

  describe('eliminate wholly contains substrings', function() {
    it('duplicates are eliminated', function() {
      assert.equal(1, eliminateSubstrings(['test','testing']).length);
    });
  });
});
<commit_msg>eliminate sub strings<commit_after>"use strict";

var assert = require('assert');

var largestString = function(words) {
  if (words && words.length > 1) {
    return words.reduce(function(x,y) {
      return Math.max(x,y.length);
    }, words[0].length);
  }
};

var eliminateSubstrings = function(words) {
  var rest = [];
  var n = words.length;

  for (var i=0;i<n;++i) {
    var subString = false;
    for (var j=0;j<n;++j) {
      if (i == j) {
        continue;
      }

      if (words[j].indexOf(words[i]) !== -1) {
        subString = true;
      }
    }

    if (!subString) {
      rest.push(words[i]);
    }
  }

  return rest;
};

describe('words smushing', function() {
  describe('largest string', function() {
    it('is not defined for 0 length arrays', function() {
      assert(!largestString([]));
    });

    it('returns the length of the longest string', function() {
      assert.equal(5, largestString(['a','b','bc','defgh']));
    });
  });

  describe('eliminate wholly contains substrings', function() {
    it('duplicates are eliminated', function() {
      assert.equal(1, eliminateSubstrings(['test','testing']).length);
    });
  });
});
<|endoftext|>


<commit_before>(function() {
  var Time = {
    MINUTES_IN_HOUR        : 60,
    MILLISECONDS_IN_MINUTE : 60000,

    OFFSETS : [300, 240, 300, 240, 300, 240, 300, 240, 300, 240, 300, 240,
               300, 240, 300, 240, 300, 240, 300, 240, 300, 240, 300],
    UNTILS  : [1268550000000, 1289109600000, 1299999600000, 1320559200000,
               1331449200000, 1352008800000, 1362898800000, 1383458400000,
               1394348400000, 1414908000000, 1425798000000, 1446357600000,
               1457852400000, 1478412000000, 1489302000000, 1509861600000,
               1520751600000, 1541311200000, 1552201200000, 1572760800000,
               1583650800000, 1604210400000, null],

    formatDate: function(date) {
      return new Intl.DateTimeFormat(undefined, {
        month : "long",
        day   : "numeric"
      }).format(date);
    },

    formatTime: function(time) {
      return new Intl.DateTimeFormat(undefined, {
        hour   : "numeric",
        minute : "numeric"
      }).format(time);
    },

    offset: function() {
      var target  = Date.now(),
          untils  = this.UNTILS,
          offsets = this.OFFSETS,
          offset,
          offsetNext,
          offsetPrev;

      for (var index = 0; index < untils.length - 1; index++) {
        offset     = offsets[index];
        offsetNext = offsets[index + 1];
        offsetPrev = offsets[index ? index - 1 : index];

        if (offset < offsetNext && false) {
          offset = offsetNext;
        } else if (offset > offsetPrev && true) {
          offset = offsetPrev;
        }

        if (target < untils[index] - (offset * this.MILLISECONDS_IN_MINUTE)) {
          return offsets[index] / this.MINUTES_IN_HOUR;
        }
      }

      return offsets[untils.length - 1] / this.MINUTES_IN_HOUR;
    }
  };

  var now      = new Date(),
      hours    = now.getUTCHours(),
      offset   = Time.offset(),
      slice    = Array.prototype.slice,
      sections = slice.call(document.querySelectorAll("section"));

  if (hours <= offset) {
    now.setUTCHours(hours - offset);
  }

  var year  = now.getUTCFullYear(),
      month = now.getUTCMonth() + 1,
      day   = now.getUTCDate();

  sections.forEach(function(section) {
    section.classList.remove("week");
  });

  sections
    .filter(function(section) {
      var parts = section.querySelector("h1 time").getAttribute("datetime").split("-");

      return parseInt(parts[0]) >= year &&
             parseInt(parts[1]) >= month &&
             parseInt(parts[2]) >= day;
    })
    .slice(0, 7).forEach(function(section, index) {
      if (window.Intl && window.Intl.DateTimeFormat) {
        var date = section.querySelector("h1 time");

        date.innerText = Time.formatDate(
          new Date(date.getAttribute("datetime"))
        );

        slice.call(section.querySelectorAll("th time")).forEach(function(time) {
          time.textContent = Time.formatTime(
            new Date(time.getAttribute("datetime"))
          );
        });
      }

      section.classList.add("week");
    });
})();
<commit_msg>Correct the internationalized date.<commit_after>(function() {
  var Time = {
    MINUTES_IN_HOUR        : 60,
    MILLISECONDS_IN_MINUTE : 60000,

    OFFSETS : [300, 240, 300, 240, 300, 240, 300, 240, 300, 240, 300, 240,
               300, 240, 300, 240, 300, 240, 300, 240, 300, 240, 300],
    UNTILS  : [1268550000000, 1289109600000, 1299999600000, 1320559200000,
               1331449200000, 1352008800000, 1362898800000, 1383458400000,
               1394348400000, 1414908000000, 1425798000000, 1446357600000,
               1457852400000, 1478412000000, 1489302000000, 1509861600000,
               1520751600000, 1541311200000, 1552201200000, 1572760800000,
               1583650800000, 1604210400000, null],

    formatDate: function(date) {
      return new Intl.DateTimeFormat(undefined, {
        month : "long",
        day   : "numeric"
      }).format(date);
    },

    formatTime: function(time) {
      return new Intl.DateTimeFormat(undefined, {
        hour   : "numeric",
        minute : "numeric"
      }).format(time);
    },

    offset: function() {
      var target  = Date.now(),
          untils  = this.UNTILS,
          offsets = this.OFFSETS,
          offset,
          offsetNext,
          offsetPrev;

      for (var index = 0; index < untils.length - 1; index++) {
        offset     = offsets[index];
        offsetNext = offsets[index + 1];
        offsetPrev = offsets[index ? index - 1 : index];

        if (offset < offsetNext && false) {
          offset = offsetNext;
        } else if (offset > offsetPrev && true) {
          offset = offsetPrev;
        }

        if (target < untils[index] - (offset * this.MILLISECONDS_IN_MINUTE)) {
          return offsets[index] / this.MINUTES_IN_HOUR;
        }
      }

      return offsets[untils.length - 1] / this.MINUTES_IN_HOUR;
    }
  };

  var now      = new Date(),
      hours    = now.getUTCHours(),
      offset   = Time.offset(),
      slice    = Array.prototype.slice,
      sections = slice.call(document.querySelectorAll("section"));

  if (hours <= offset) {
    now.setUTCHours(hours - offset);
  }

  var year  = now.getUTCFullYear(),
      month = now.getUTCMonth() + 1,
      day   = now.getUTCDate();

  sections.forEach(function(section) {
    section.classList.remove("week");
  });

  sections
    .filter(function(section) {
      var parts = section.querySelector("h1 time").getAttribute("datetime").split("-");

      return parseInt(parts[0]) >= year &&
             parseInt(parts[1]) >= month &&
             parseInt(parts[2]) >= day;
    })
    .slice(0, 7).forEach(function(section, index) {
      if (window.Intl && window.Intl.DateTimeFormat) {
        var date = new Date(now),
            time = section.querySelector("h1 time");

        date.setDate(date.getDate() + index);

        time.innerText = Time.formatDate(date);

        slice.call(section.querySelectorAll("th time")).forEach(function(time) {
          time.textContent = Time.formatTime(
            new Date(time.getAttribute("datetime"))
          );
        });
      }

      section.classList.add("week");
    });
})();
<|endoftext|>


<commit_before>(function($) {

  function arrayEach(arr, fn) {
    for(var i = 0; i < arr.length; i++) {
      fn(arr[i], i, arr);
    }
  }

  function arrayEvery(arr, fn) {
    for(var i = 0; i < arr.length; i++) {
      if(!fn(arr[i], i, arr)) {
        return false;
      }
    }
    return true;
  }

  function capitalize(str) {
    if (str.match(/^es\d$/)) {
      return str.toUpperCase();
    }
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  function commaSeparate(n) {
    return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }

  function getSplitPath() {
    var match = document.location.pathname.match(/(\w+)\/(\w+)\/([\w-]+)\.html$/);
    return [match[1], match[2], match[3]];
  }

  function getTestName() {
    var path = getSplitPath();
    var testName = capitalize(path[2]);
    var isExtended = path[0] === 'extended';
    var isMin = path[1] === 'min';
    if (isExtended || isMin) {
      var tokens = [];
      if (isExtended) {
        tokens.push('extended');
      }
      if (isMin) {
        tokens.push('minified');
      }
      testName += ' (' + tokens.join(' | ') + ')';
    }
    return testName;
  }

  function createHTML() {
    var testName = getTestName();
    var testLink = '' + testName + '';
    document.title = 'Sugar ' + testName;
    $(document.body).append([
      '
',
        '
' + testLink + '
',
        '
Running tests.
',
        '

',
        '

',
      '
'
    ].join(''));
  }

  function escapeHTML(str) {
    return str ? str.replace(/</g, '<').replace(/>/g, '>') : '';
  }

  function getFailureHTML(f) {
    var expected, actual, message = escapeHTML(f.message);
    if(f.warning) {
      return '
Warning: ' + message + '
';
    } else {
      var html = '
' + message;
      if (f.hasOwnProperty('expected') && f.hasOwnProperty('actual')) {
        expected = getStringified(f.expected);
        actual = getStringified(f.actual);
        html += ', expected: ' + escapeHTML(expected) + ' actual: ' + escapeHTML(actual);
      }
      html += '
';
      return html;
    }
  };

  function getStringified(p) {
    var str, arr, isArray = p && p.join, arrayHasUndefined;
    if (p && p.getTime && p.setHours) {
      return p.toString();
    }
    arrayHasUndefined = isArray && $.inArray(undefined, p) !== -1;
    if(p && p.length > 5000) return 'One BIG ass array of length ' + p.length;
    if(typeof p === 'function') return 'function';
    if(typeof p !== 'object') return String(p);
    str = isArray ? '[' : '{';
    arr = [];
    for(var key in p){
      if(!p.hasOwnProperty(key)) continue;
      if(p[key] === undefined) {
        arr.push(key + ': undefined');
      } else {
        var val = p[key];
        if (typeof val === 'string') {
          val = '"' + val + '"';
        }
        arr.push(key + ': ' + val);
      }
    }
    str += arr.join(',');
    str += isArray ? ']' : '}';
    return str;
  };

  function testsFinished(runtime, packages) {
    var testHtml = '', tipHtml = '';

    var totalTests = 0;
    var totalAssertions = 0;
    var totalFailed = 0;

    arrayEach(packages, function(p) {
      var li = '', tip = '', className = '';

      totalTests++;
      totalAssertions += p.assertions;
      totalFailed += p.failures.length;
      tip += '
' + p.name + (p.subname ? ' | ' + p.subname : '') + '
';
      if(p.failures.length > 0) {
        arrayEach(p.failures, function(f) {
          tip += getFailureHTML(f);
          if(f.warning) {
            totalFailed--;
          }

        });
        var warning = arrayEvery(p.failures, function(f){ return f.warning; });
        if(warning) {
          className += 'warning';
          li += '.';
        } else {
          className += 'fail';
          li += 'F';
          tip += '
Fail (' + commaSeparate(p.assertions) + ' assertions)
';
        }
      } else {
        className += 'pass';
        li += '.';
        tip += '
Pass (' + commaSeparate(p.assertions) + ' assertions)
';
      }

      tipHtml += '
'+ tip +'
'
      testHtml += '
'+ li +'
';
    });

    $('#stats').html([
      '' + totalFailed + ' ' + (totalFailed == 1 ? 'failure' : 'failures') + '',
      '' + totalTests + ' ' + (totalTests == 1 ? 'test' : 'tests') + '',
      '' + commaSeparate(totalAssertions) + ' ' + (totalAssertions == 1 ? 'assertion' : 'assertions') + '',
      'Completed in ' + runtime / 1000 + ' seconds'
    ].join(''));
    $('#tests').html(testHtml);
    $(document.body).addClass('finished').append(tipHtml);
    $('#tests [title]').tooltip({ color: 'black' });
  }

  $(document).ready(function() {
    createHTML();
  });

  window.testsFinished = testsFinished;

})(jQuery);
<commit_msg>suite-ui: don't stringify array keys<commit_after>(function($) {

  function arrayEach(arr, fn) {
    for(var i = 0; i < arr.length; i++) {
      fn(arr[i], i, arr);
    }
  }

  function arrayEvery(arr, fn) {
    for(var i = 0; i < arr.length; i++) {
      if(!fn(arr[i], i, arr)) {
        return false;
      }
    }
    return true;
  }

  function capitalize(str) {
    if (str.match(/^es\d$/)) {
      return str.toUpperCase();
    }
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  function commaSeparate(n) {
    return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }

  function getSplitPath() {
    var match = document.location.pathname.match(/(\w+)\/(\w+)\/([\w-]+)\.html$/);
    return [match[1], match[2], match[3]];
  }

  function getTestName() {
    var path = getSplitPath();
    var testName = capitalize(path[2]);
    var isExtended = path[0] === 'extended';
    var isMin = path[1] === 'min';
    if (isExtended || isMin) {
      var tokens = [];
      if (isExtended) {
        tokens.push('extended');
      }
      if (isMin) {
        tokens.push('minified');
      }
      testName += ' (' + tokens.join(' | ') + ')';
    }
    return testName;
  }

  function createHTML() {
    var testName = getTestName();
    var testLink = '' + testName + '';
    document.title = 'Sugar ' + testName;
    $(document.body).append([
      '
',
        '
' + testLink + '
',
        '
Running tests.
',
        '

',
        '

',
      '
'
    ].join(''));
  }

  function escapeHTML(str) {
    return str ? str.replace(/</g, '<').replace(/>/g, '>') : '';
  }

  function getFailureHTML(f) {
    var expected, actual, message = escapeHTML(f.message);
    if(f.warning) {
      return '
Warning: ' + message + '
';
    } else {
      var html = '
' + message;
      if (f.hasOwnProperty('expected') && f.hasOwnProperty('actual')) {
        expected = getStringified(f.expected);
        actual = getStringified(f.actual);
        html += ', expected: ' + escapeHTML(expected) + ' actual: ' + escapeHTML(actual);
      }
      html += '
';
      return html;
    }
  };

  function getStringified(p) {
    var str, arr, isArray = p && p.join, arrayHasUndefined;
    if (p && p.getTime && p.setHours) {
      return p.toString();
    }
    arrayHasUndefined = isArray && $.inArray(undefined, p) !== -1;
    if(p && p.length > 5000) return 'One BIG ass array of length ' + p.length;
    if(typeof p === 'function') return 'function';
    if(typeof p !== 'object') return String(p);
    str = isArray ? '[' : '{';
    arr = [];
    for(var key in p){
      if(!p.hasOwnProperty(key)) continue;
      if(p[key] === undefined) {
        arr.push(key + ': undefined');
      } else {
        var val = p[key];
        if (typeof val === 'string') {
          val = '"' + val + '"';
        }
        arr.push((isArray ? '' : key + ': ') + val);
      }
    }
    str += arr.join(',');
    str += isArray ? ']' : '}';
    return str;
  };

  function testsFinished(runtime, packages) {
    var testHtml = '', tipHtml = '';

    var totalTests = 0;
    var totalAssertions = 0;
    var totalFailed = 0;

    arrayEach(packages, function(p) {
      var li = '', tip = '', className = '';

      totalTests++;
      totalAssertions += p.assertions;
      totalFailed += p.failures.length;
      tip += '
' + p.name + (p.subname ? ' | ' + p.subname : '') + '
';
      if(p.failures.length > 0) {
        arrayEach(p.failures, function(f) {
          tip += getFailureHTML(f);
          if(f.warning) {
            totalFailed--;
          }

        });
        var warning = arrayEvery(p.failures, function(f){ return f.warning; });
        if(warning) {
          className += 'warning';
          li += '.';
        } else {
          className += 'fail';
          li += 'F';
          tip += '
Fail (' + commaSeparate(p.assertions) + ' assertions)
';
        }
      } else {
        className += 'pass';
        li += '.';
        tip += '
Pass (' + commaSeparate(p.assertions) + ' assertions)
';
      }

      tipHtml += '
'+ tip +'
'
      testHtml += '
'+ li +'
';
    });

    $('#stats').html([
      '' + totalFailed + ' ' + (totalFailed == 1 ? 'failure' : 'failures') + '',
      '' + totalTests + ' ' + (totalTests == 1 ? 'test' : 'tests') + '',
      '' + commaSeparate(totalAssertions) + ' ' + (totalAssertions == 1 ? 'assertion' : 'assertions') + '',
      'Completed in ' + runtime / 1000 + ' seconds'
    ].join(''));
    $('#tests').html(testHtml);
    $(document.body).addClass('finished').append(tipHtml);
    $('#tests [title]').tooltip({ color: 'black' });
  }

  $(document).ready(function() {
    createHTML();
  });

  window.testsFinished = testsFinished;

})(jQuery);
<|endoftext|>


<commit_before>/* global exports */
"use strict";

// module Data.DOM.Simple.Unsafe.Window

exports.unsafeDocument = function (win) {
  return function () {
    return win.document;
  };
};

exports.unsafeNavigator = function (win) {
  return function () {
    return win.navigator;
  };
};

exports.unsafeLocation = function (win) {
  return function () {
    return win.location;
  };
};

exports.unsafeGetLocation = function (loc) {
  return function () {
    return loc;
  };
};

exports.unsafeSetLocation = function (value) {
  return function (loc) {
    return function () {
      location.assign(value);
    };
  };
};

exports.unsafeGetSearchLocation = function (loc) {
  return function () {
    return loc.search;
  };
};

exports.unsafeSetTimeout = function (win) {
  return function (delay) {
    return function (func) {
      return function () {
        return win.setTimeout(func, delay);
      };
    };
  };
};

exports.unsafeSetInterval = function (win) {
  return function (delay) {
    return function (func) {
      return function () {
        return win.setInterval(func, delay);
      };
    };
  };
};

exports.unsafeClearTimeout = function (win) {
  return function (timeout) {
    return function () {
      win.clearTimeout(timeout);
    };
  };
};

exports.unsafeInnerWidth = function (win) {
  return function () {
    return win.innerWidth;
  };
};

exports.unsafeInnerHeight = function (win) {
  return function () {
    return win.innerHeight;
  };
};
<commit_msg>Fix bug caught by jshint<commit_after>/* global exports */
"use strict";

// module Data.DOM.Simple.Unsafe.Window

exports.unsafeDocument = function (win) {
  return function () {
    return win.document;
  };
};

exports.unsafeNavigator = function (win) {
  return function () {
    return win.navigator;
  };
};

exports.unsafeLocation = function (win) {
  return function () {
    return win.location;
  };
};

exports.unsafeGetLocation = function (loc) {
  return function () {
    return loc;
  };
};

exports.unsafeSetLocation = function (value) {
  return function (loc) {
    return function () {
      loc.assign(value);
    };
  };
};

exports.unsafeGetSearchLocation = function (loc) {
  return function () {
    return loc.search;
  };
};

exports.unsafeSetTimeout = function (win) {
  return function (delay) {
    return function (func) {
      return function () {
        return win.setTimeout(func, delay);
      };
    };
  };
};

exports.unsafeSetInterval = function (win) {
  return function (delay) {
    return function (func) {
      return function () {
        return win.setInterval(func, delay);
      };
    };
  };
};

exports.unsafeClearTimeout = function (win) {
  return function (timeout) {
    return function () {
      win.clearTimeout(timeout);
    };
  };
};

exports.unsafeInnerWidth = function (win) {
  return function () {
    return win.innerWidth;
  };
};

exports.unsafeInnerHeight = function (win) {
  return function () {
    return win.innerHeight;
  };
};
<|endoftext|>


<commit_before>loadPhastJS(['public/es6-promise.js', 'public/scripts-loader.js'], function (phast) {

    var ScriptsLoader = phast.ScriptsLoader,
        Promise = phast.ES6Promise;

    QUnit.module('ScriptsLoader', function () {

        QUnit.module('Utilities', function (hooks) {

            var utils, testDoc;

            hooks.beforeEach(function () {
                testDoc = document.implementation.createHTMLDocument();
                utils = new ScriptsLoader.Utilities(testDoc);
            });

            QUnit.test('Test restoreOriginals()', function (assert) {
                var originalSrc = 'the-original-src';
                var originalType = 'the-original-type';
                var s = testDoc.createElement('script');
                s.setAttribute('src', 'the-src');
                s.setAttribute('id', 'the-id');
                s.setAttribute('data-phast-original-src', originalSrc);
                s.setAttribute('data-phast-original-type', originalType);
                utils.restoreOriginals(s);

                assert.equal(s.getAttribute('src'), originalSrc, 'src is restored');
                assert.equal(s.getAttribute('type'), originalType, 'type is restored');
                assert.notOk(s.hasAttribute('data-phast-original-src'), 'phast src has been removed');
                assert.notOk(s.hasAttribute('data-phast-original-type'), 'phast type has been removed');
                assert.equal(s.getAttribute('id'), 'the-id', 'id is intact');
            });

            QUnit.test('Test executeString()', function (assert) {
                window.STRING_EXECUTED = false;
                var string = func2string(function  () { window.STRING_EXECUTED = true; });
                utils.executeString(string);
                assert.ok(window.STRING_EXECUTED, 'String was executed');
                delete window.STRING_EXECUTED;
            });

            QUnit.test('Test writeProtectAndExecuteString()', function (assert) {
                var s1 = testDoc.createElement('script');
                var s2 = testDoc.createElement('script');
                testDoc.body.appendChild(s1);
                testDoc.body.appendChild(s2);
                var func = function () {
                    document.write('
write works
');
                    document.writeln('
writeln works
');
                };
                var checkWrites = getWriteProtectChecker(assert);
                assert.timeout(100);
                var done = assert.async();

                utils = new ScriptsLoader.Utilities(document);
                utils.writeProtectAndExecuteString(s1, func2string(func))
                    .then(function () {
                        checkWrites();
                        var paragraphs = testDoc.getElementsByTagName('p');
                        assert.equal(paragraphs.length, 2, 'Paragraphs have been written');
                        assert.equal(paragraphs[0].innerHTML, 'write works', 'paragraph 0 is correct');
                        assert.equal(paragraphs[1].innerHTML, 'writeln works', 'paragraph 1 is correct');
                        assert.ok(s1 === paragraphs[0].previousSibling, 'paragraph 0 is in the correct position');
                        done();
                    });
            });

            QUnit.test('Test writeProtectAndExecuteString() restores write and writeln after exception', function (assert) {
                var s = testDoc.createElement('script');
                var checkWrites = getWriteProtectChecker(assert);
                assert.timeout(100);
                var done = assert.async();
                var script = 'throw "error";';

                utils = new ScriptsLoader.Utilities(document);
                utils.writeProtectAndExecuteString(s, script)
                    .finally(function () {
                        checkWrites();
                        done();
                    });
            });

            QUnit.test('Test replaceElement()', function (assert) {
                var s1 = testDoc.createElement('script');
                var s2 = testDoc.createElement('script');
                testDoc.body.appendChild(s1);
                Element.prototype.insertBefore = function () {};
                utils.replaceElement(s1, s2);
                delete Element.prototype.insertBefore;
                assert.equal(1, testDoc.body.children.length, 'There is only one body child');
                assert.ok(testDoc.body.children[0] === s2, 'Script has been replaced');
            });

            QUnit.test('Test writeProtectAndReplaceElement()', function (assert) {
                var s1 = testDoc.createElement('script');
                var s2 = testDoc.createElement('script');
                var checkWrite = getWriteProtectChecker(assert);
                assert.timeout(200);
                var done = assert.async();
                s1.setAttribute('id', 'writeProtectAndReplaceElementTestScriptToRemove')
                var writeFunc = function () {
                    document.write('

');
                };
                s2.setAttribute('src', 'data:text/javascript;base64,' + utoa(func2string(writeFunc)));
                s2.setAttribute('id', 'writeProtectAndReplaceElementReplacementScript');
                document.body.appendChild(s1);

                utils = new ScriptsLoader.Utilities(document);
                utils.writeProtectAndReplaceElement(s1, s2)
                    .finally(function () {
                        checkWrite();
                        var replaced = document.getElementById('writeProtectAndReplaceElementTestScriptToRemove');
                        var replacement = document.getElementById('writeProtectAndReplaceElementReplacementScript');
                        var written = document.getElementById('writtenline');

                        assert.ok(replaced === null, 'Target was replaced');
                        assert.ok(replacement === s2, 'Replacement is in place');
                        assert.ok(written, 'Written exists');
                        document.body.removeChild(replacement);
                        document.body.removeChild(written);
                        done();
                    });
            });

            function func2string(func) {
                return '(' + func.toString() + ')();';
            }

            function getWriteProtectChecker(assert) {
                var originalWrite = document.write;
                var originalWriteLn = document.writeln;
                return function () {
                    assert.ok(originalWrite === document.write, 'document.write has been restored');
                    assert.ok(originalWriteLn === document.writeln, 'document.writeln has been restored');
                }
            }

            function utoa(str) {
                return btoa(
                    encodeURIComponent(str).replace(
                        /%([0-9A-F]{2})/g,
                        function toSolidBytes(match, p1) {
                            return String.fromCharCode('0x' + p1);
                        }
                    )
                );
            }
        });

        QUnit.module('Scripts', function (hooks) {

            var Scripts = ScriptsLoader.Scripts;

            var successfulFetch = function (url) {
                utils._pushCall('fetch', url);
                return new Promise(function (resolve) {
                    resolve('contents-for-' + url);
                });
            };

            var failingFetch = function (url) {
                utils._pushCall('fetch', url);
                return new Promise(function (resolve, reject) {
                    reject('failure-for-' + url);
                });
            };

            var fallback = {

                init: function () {
                    utils._pushCall('fallbackInit');
                },

                execute: function () {
                    utils._pushCall('fallbackExecute');
                    return Promise.resolve('fallback-promise');
                }
            };

            var utils, element;
            hooks.beforeEach(function () {
                element  = document.createElement('script');
                utils = new UtilsMock();
            });

            QUnit.module('InlineScript', function (hooks) {

                var script;
                hooks.beforeEach(function () {
                    script = new Scripts.InlineScript(utils, element);
                    script.init();
                });

                QUnit.test('No init execution', assertNothingWasCalled);

                QUnit.test('Execute', function (assert) {
                    var done = getAsync(assert);
                    element.innerHTML = '


<commit_before>'use strict';

describe('Controller: MainCtrl', function () {

  // load the controller's module
  //beforeEach(module('moneyApp'));
  beforeEach(angular.mock.module('moneyApp'));

  var MainCtrl,
    scope,
    $httpBackend;

  // Initialize the controller and a mock scope
  beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
    $httpBackend = _$httpBackend_;
    $httpBackend.expectGET('/api/v1/moneybooks')
      .respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']);
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of moneybooks data to the scope', function () {
    console.log('[main] data....'+JSON.stringify(scope.moneyBooks));
    expect(scope.moneyBooks.$params.page).toBe(1);
    expect(scope.moneyBooks.$params.count).toBe(10);
  });

  it('should have a properly working MainCtrl controller', inject(function($rootScope, $controller, $httpBackend) {
    var searchTestAtr = 'cars';
    var response = $httpBackend.expectJSONP('/api/v1/moneybooks?q=' + searchTestAtr);
    response.respond(null);

    var $scope = $rootScope.$new();
    var ctrl = $controller('MainCtrl', {
      $scope : $scope,
      $routeParams : {
        q : searchTestAtr
      }
    });
  }));

  it('should have a properly working MainCtrl controller', inject(function($rootScope, $controller, $httpBackend) {
    var searchID = '1';
    var response = $httpBackend.expectJSONP('/api/v1/moneybooks/' + searchID);
    response.respond(null);

    var $scope = $rootScope.$new();
    var ctrl = $controller('MainCtrl', {
      $scope : $scope,
      $routeParams : {
        id : searchID
      }
    });
  }));
/*
  it('should have a MainCtrl controller', function() {
    expect(moneyApp.MainCtrl).not.to.equal(null);
  });

*/
/*
  // Initialize the controller and a mock scope
  beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
    $httpBackend = _$httpBackend_;
    $httpBackend.expectGET('/api/awesomeThings')
      .respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']);
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings).toBeUndefined();
    $httpBackend.flush();
    expect(scope.awesomeThings.length).toBe(4);
  });
*/
});
<commit_msg> 사용하여 angularjs controller 테스트<commit_after>'use strict';

describe('Controller: MainCtrl', function () {

  // load the controller's module
  //beforeEach(module('moneyApp'));
  beforeEach(angular.mock.module('moneyApp'));

  var MainCtrl,
    scope,
    $httpBackend;

  // Initialize the controller and a mock scope
  beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
    $httpBackend = _$httpBackend_;
    $httpBackend.expectGET('/api/v1/moneybooks/')
      .respond({"results":{"total_count":1,"page_count":1,"page_size":"10","data":[{"item":"item to delete","amount":1200,"date":"2014-04-24"}]}});
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));

  it('should have default parameters', function () {
    expect(scope.moneyBooks.$params.page).toBe(1);
    expect(scope.moneyBooks.$params.count).toBe(10);
  });

  it('should attach a list of data to the scope', inject(function($rootScope, $controller, $httpBackend) {
    scope.init();
    $httpBackend.flush();
    console.log('scope.data....'+JSON.stringify(scope.data));
    expect(scope.data.length).toBe(1);

  }));

  it('should suceed modifying moneybook', inject(function($rootScope, $controller, $httpBackend) {
    var searchID = '1';
    var data = {"id":searchID,"item":"item to modify","amount":1100,"date":"2014-05-07"};

    scope.init();
    $httpBackend.flush();

    $httpBackend.expectPUT('/api/v1/moneybooks/'+searchID, data)
      .respond(200, {"status":"ok"});

    $httpBackend.expectGET('/api/v1/moneybooks/')
      .respond({"results":{"total_count":1,"page_count":1,"page_size":"10","data":[{"item":"item to delete","amount":1200,"date":"2014-04-24"}]}});

    scope.update(data);
    $httpBackend.flush();
  }));

/*
  it('should have a MainCtrl controller', function() {
    expect(moneyApp.MainCtrl).not.to.equal(null);
  });
*/
/*
  // Initialize the controller and a mock scope
  beforeEach(inject(function (_$httpBackend_, $controller, $rootScope) {
    $httpBackend = _$httpBackend_;
    $httpBackend.expectGET('/api/awesomeThings')
      .respond(['HTML5 Boilerplate', 'AngularJS', 'Karma', 'Express']);
    scope = $rootScope.$new();
    MainCtrl = $controller('MainCtrl', {
      $scope: scope
    });
  }));

  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings).toBeUndefined();
    $httpBackend.flush();
    expect(scope.awesomeThings.length).toBe(4);
  });
*/
});
<|endoftext|>


<commit_before><commit_msg>Update image_provider.js<commit_after><|endoftext|>


<commit_before>/*jshint node:true, mocha:true */

/**
 * @author kecso / https://github.com/kecso
 */

var testFixture = require('../../../_globals');

describe.skip('merge - library', function () {
    'use strict';
    var projectName = 'mergeLibrary',
        projectId = testFixture.projectName2Id(projectName),
        Q = testFixture.Q,
        gmeConfig = testFixture.getGmeConfig(),
        logger = testFixture.logger.fork('apply.spec'),
        expect = testFixture.expect,
        merger = testFixture.requirejs('common/core/users/merge'),
        storage,
        context,
        gmeAuth;

    before(function (done) {
        testFixture.clearDBAndGetGMEAuth(gmeConfig, projectName)
            .then(function (gmeAuth__) {
                gmeAuth = gmeAuth__;
                storage = testFixture.getMemoryStorage(logger, gmeConfig, gmeAuth);
                return storage.openDatabase();
            })
            .then(function () {
                return testFixture.openContext(storage, gmeConfig, logger, {
                    projectName: projectName,
                    branchName: 'master',
                    createProject: true,
                    projectSeed: './test/common/core/users/merge/base.json'
                });
            })
            .then(function (result) {
                context = result;
                return Q.all([
                    Q.nfcall(context.project.createBranch, 'other', result.commitHash),
                    Q.nfcall(context.project.createBranch, 'empty', result.commitHash)
                ]);
            })
            .nodeify(done);
    });

    after(function (done) {
        storage.deleteProject({projectId: projectId})
            .then(function () {
                return Q.all([
                    storage.closeDatabase(),
                    gmeAuth.unload()
                ]);
            })
            .nodeify(done);
    });

    it('should go fine to apply empty patch', function (done) {
        merger.apply({
            project: context.project,
            logger: logger,
            gmeConfig: gmeConfig,
            patch: {},
            branchOrCommit: 'empty',
            noUpdate: true
        }).nodeify(done);
    });

    it('should fail to get diff from unknown branch', function (done) {
        merger.apply({
            project: context.project,
            logger: logger,
            gmeConfig: gmeConfig,
            patch: {},
            branchOrCommit: 'unknownBranch',
            noUpdate: true
        })
            .then(function (result) {
                done(new Error('missing error handling'));
            })
            .catch(function (err) {
                expect(err).not.to.equal(null);
                done();
            });
    });

    it('should fail to get diff from unknown commit', function (done) {
        merger.apply({
            project: context.project,
            logger: logger,
            gmeConfig: gmeConfig,
            patch: {},
            branchOrCommit: '#42424242424242',
            noUpdate: true
        })
            .then(function (result) {
                done(new Error('missing error handling'));
            })
            .catch(function (err) {
                expect(err).not.to.equal(null);
                done();
            });
    });

    it('should merge identical branches without change keeping the target', function (done) {
        merger.merge({
            project: context.project,
            logger: logger,
            gmeConfig: gmeConfig,
            myBranchOrCommit: 'empty',
            theirBranchOrCommit: 'empty',
            auto: true
        })
            .then(function (result) {
                expect(result).not.to.equal(null);
                expect(result.finalCommitHash).to.equal(context.commitHash);
                expect(result.updatedBranch).to.equal('empty');
                done();
            })
            .catch(done);
    });

    it('should merge identical commits without change keeping the target', function (done) {
        merger.merge({
            project: context.project,
            logger: logger,
            gmeConfig: gmeConfig,
            myBranchOrCommit: context.commitHash,
            theirBranchOrCommit: context.commitHash,
            auto: true
        })
            .then(function (result) {
                expect(result).not.to.equal(null);
                expect(result.finalCommitHash).to.equal(context.commitHash);
                expect(result.updatedBranch).to.equal(undefined);
                done();
            })
            .catch(done);
    });

    it('should return the conflict object if there is conflicting changes', function (done) {
        var masterContext,
            otherContext,
            masterPersisted,
            otherPersisted;

        Q.all([
            testFixture.openContext(storage, gmeConfig, logger, {
                projectName: projectName,
                branchName: 'master'
            }),
            testFixture.openContext(storage, gmeConfig, logger, {
                projectName: projectName,
                branchName: 'other'
            })
        ])
            .then(function (contexts) {
                expect(contexts).not.to.equal(null);
                expect(contexts).to.have.length(2);

                masterContext = contexts[0];
                otherContext = contexts[1];

                masterContext.core.setRegistry(masterContext.rootNode, 'something', 'masterValue');
                otherContext.core.setRegistry(otherContext.rootNode, 'something', 'otherValue');

                masterPersisted = masterContext.core.persist(masterContext.rootNode);
                otherPersisted = otherContext.core.persist(otherContext.rootNode);

                return Q.all([
                    masterContext.project.makeCommit(
                        'master',
                        [masterContext.commitHash],
                        masterContext.core.getHash(masterContext.rootNode),
                        masterPersisted.objects,
                        'master setting core registry'),
                    otherContext.project.makeCommit(
                        'other',
                        [otherContext.commitHash],
                        otherContext.core.getHash(otherContext.rootNode),
                        otherPersisted.objects,
                        'other setting core registry')
                ]);
            })
            .then(function (commitResults) {
                expect(commitResults).not.to.equal(null);
                expect(commitResults).to.have.length(2);

                return merger.merge({
                    project: context.project,
                    logger: logger,
                    gmeConfig: gmeConfig,
                    myBranchOrCommit: 'other',
                    theirBranchOrCommit: 'master',
                    auto: true
                });
            })
            .then(function (mergeResult) {
                expect(mergeResult).not.to.equal(null);
                expect(mergeResult).to.include.keys(['myCommitHash',
                    'theirCommitHash', 'baseCommitHash', 'diff', 'conflict']);
                expect(mergeResult.conflict.items).to.have.length(1);
                expect(mergeResult.conflict.items[0]).to.include.keys(['selected','mine','theirs']);
                expect(mergeResult.conflict.items[0].mine.path).to.equal('/reg/something');
                expect(mergeResult.conflict.items[0].theirs.path).to.equal('/reg/something');
                expect(mergeResult.conflict.items[0].mine.value).to.equal('otherValue');
                expect(mergeResult.conflict.items[0].theirs.value).to.equal('masterValue');
                done();
            })
            .catch(done);
    });

});<commit_msg>test: allowing some skipped tests<commit_after>/*jshint node:true, mocha:true */

/**
 * @author kecso / https://github.com/kecso
 */

var testFixture = require('../../../_globals');

describe('merge - library', function () {
    'use strict';
    var projectName = 'mergeLibrary',
        projectId = testFixture.projectName2Id(projectName),
        Q = testFixture.Q,
        gmeConfig = testFixture.getGmeConfig(),
        logger = testFixture.logger.fork('merger.spec'),
        expect = testFixture.expect,
        merger = testFixture.requirejs('common/core/users/merge'),
        storage,
        context,
        gmeAuth;

    before(function (done) {
        testFixture.clearDBAndGetGMEAuth(gmeConfig, projectName)
            .then(function (gmeAuth__) {
                gmeAuth = gmeAuth__;
                storage = testFixture.getMemoryStorage(logger, gmeConfig, gmeAuth);
                return storage.openDatabase();
            })
            .then(function(){
                return storage.deleteProject({projectId:projectId});
            })
            .then(function () {
                return testFixture.importProject(storage, {
                    projectName: projectName,
                    logger: logger.fork('import'),
                    gmeConfig: gmeConfig,
                    branchName: 'master',
                    userName: gmeConfig.authentication.guestAccount,
                    projectSeed: './test/common/core/users/merge/base.json'
                });
            })
            .then(function (result) {
                context = result;
                return Q.all([
                    Q.nfcall(context.project.createBranch, 'other', result.commitHash),
                    Q.nfcall(context.project.createBranch, 'empty', result.commitHash)
                ]);
            })
            .nodeify(done);
    });

    after(function (done) {
        storage.deleteProject({projectId: projectId})
            .then(function () {
                return Q.all([
                    storage.closeDatabase(),
                    gmeAuth.unload()
                ]);
            })
            .nodeify(done);
    });

    it('should go fine to apply empty patch', function (done) {
        merger.apply({
            project: context.project,
            logger: logger,
            gmeConfig: gmeConfig,
            patch: {},
            branchOrCommit: 'empty',
            noUpdate: true
        }).nodeify(done);
    });

    it('should fail to get diff from unknown branch', function (done) {
        merger.apply({
            project: context.project,
            logger: logger,
            gmeConfig: gmeConfig,
            patch: {},
            branchOrCommit: 'unknownBranch',
            noUpdate: true
        })
            .then(function (result) {
                done(new Error('missing error handling'));
            })
            .catch(function (err) {
                expect(err).not.to.equal(null);
                done();
            });
    });

    it('should fail to get diff from unknown commit', function (done) {
        merger.apply({
            project: context.project,
            logger: logger,
            gmeConfig: gmeConfig,
            patch: {},
            branchOrCommit: '#42424242424242',
            noUpdate: true
        })
            .then(function (result) {
                done(new Error('missing error handling'));
            })
            .catch(function (err) {
                expect(err).not.to.equal(null);
                done();
            });
    });

    it('should merge identical branches without change keeping the target', function (done) {
        merger.merge({
            project: context.project,
            logger: logger,
            gmeConfig: gmeConfig,
            myBranchOrCommit: 'empty',
            theirBranchOrCommit: 'empty',
            auto: true
        })
            .then(function (result) {
                expect(result).not.to.equal(null);
                expect(result.finalCommitHash).to.equal(context.commitHash);
                expect(result.updatedBranch).to.equal('empty');
                done();
            })
            .catch(done);
    });

    it('should merge identical commits without change keeping the target', function (done) {
        merger.merge({
            project: context.project,
            logger: logger,
            gmeConfig: gmeConfig,
            myBranchOrCommit: context.commitHash,
            theirBranchOrCommit: context.commitHash,
            auto: true
        })
            .then(function (result) {
                expect(result).not.to.equal(null);
                expect(result.finalCommitHash).to.equal(context.commitHash);
                expect(result.updatedBranch).to.equal(undefined);
                done();
            })
            .catch(done);
    });

    it.skip('should return the conflict object if there is conflicting changes', function (done) {
        var masterContext,
            otherContext,
            masterPersisted,
            otherPersisted;

        Q.all([
            testFixture.openContext(storage, gmeConfig, logger, {
                projectName: projectName,
                branchName: 'master'
            }),
            testFixture.openContext(storage, gmeConfig, logger, {
                projectName: projectName,
                branchName: 'other'
            })
        ])
            .then(function (contexts) {
                expect(contexts).not.to.equal(null);
                expect(contexts).to.have.length(2);

                masterContext = contexts[0];
                otherContext = contexts[1];

                masterContext.core.setRegistry(masterContext.rootNode, 'something', 'masterValue');
                otherContext.core.setRegistry(otherContext.rootNode, 'something', 'otherValue');

                masterPersisted = masterContext.core.persist(masterContext.rootNode);
                otherPersisted = otherContext.core.persist(otherContext.rootNode);

                return Q.all([
                    masterContext.project.makeCommit(
                        'master',
                        [masterContext.commitHash],
                        masterContext.core.getHash(masterContext.rootNode),
                        masterPersisted.objects,
                        'master setting core registry'),
                    otherContext.project.makeCommit(
                        'other',
                        [otherContext.commitHash],
                        otherContext.core.getHash(otherContext.rootNode),
                        otherPersisted.objects,
                        'other setting core registry')
                ]);
            })
            .then(function (commitResults) {
                expect(commitResults).not.to.equal(null);
                expect(commitResults).to.have.length(2);

                return merger.merge({
                    project: context.project,
                    logger: logger,
                    gmeConfig: gmeConfig,
                    myBranchOrCommit: 'other',
                    theirBranchOrCommit: 'master',
                    auto: true
                });
            })
            .then(function (mergeResult) {
                expect(mergeResult).not.to.equal(null);
                expect(mergeResult).to.include.keys(['myCommitHash',
                    'theirCommitHash', 'baseCommitHash', 'diff', 'conflict']);
                expect(mergeResult.conflict.items).to.have.length(1);
                expect(mergeResult.conflict.items[0]).to.include.keys(['selected','mine','theirs']);
                expect(mergeResult.conflict.items[0].mine.path).to.equal('/reg/something');
                expect(mergeResult.conflict.items[0].theirs.path).to.equal('/reg/something');
                expect(mergeResult.conflict.items[0].mine.value).to.equal('otherValue');
                expect(mergeResult.conflict.items[0].theirs.value).to.equal('masterValue');
                done();
            })
            .catch(done);
    });

});<|endoftext|>


<commit_before>/*
 melonJS initialization

 It is important for this block to be executed before any manipulation with graphics-related objects is happening,
 hence make sure to put all code that depends on object pool, inside 'it' or 'beforeAll' blocks for their respective
 'describe' blocks, e. g.:

   describe("Shape : me.Font", function () {
     var font;
     beforeAll(function () {
       font = new me.Font("Arial", 8, "white");
     });

 */

beforeAll(function (done) {
    console.log("Initializing melonJS");
    me.sys.stopOnAudioError = false;

    me.boot();

    // Initialize video
    if (!me.video.init(1024, 768, {wrapper: "screen", renderer : me.video.CANVAS})) {
        throw "me.video.init failed";
    }

    // dummy stage
    me.state.set(me.state.PLAY, new me.Stage());
    me.state.change(me.state.PLAY);

    // Hide the screen
    var scr = document.querySelector("#screen");
    if (scr) {
        scr.style.display = "none";
    }
    done();
});
<commit_msg>fix deprecation warning in the karmat test unit<commit_after>/*
 melonJS initialization

 It is important for this block to be executed before any manipulation with graphics-related objects is happening,
 hence make sure to put all code that depends on object pool, inside 'it' or 'beforeAll' blocks for their respective
 'describe' blocks, e. g.:

   describe("Shape : me.Font", function () {
     var font;
     beforeAll(function () {
       font = new me.Font("Arial", 8, "white");
     });

 */

beforeAll(function (done) {
    console.log("Initializing melonJS");
    me.sys.stopOnAudioError = false;

    me.boot();

    // Initialize video
    if (!me.video.init(1024, 768, {parent: "screen", renderer : me.video.CANVAS})) {
        throw "me.video.init failed";
    }

    // dummy stage
    me.state.set(me.state.PLAY, new me.Stage());
    me.state.change(me.state.PLAY);

    // Hide the screen
    var scr = document.querySelector("#screen");
    if (scr) {
        scr.style.display = "none";
    }
    done();
});
<|endoftext|>


<commit_before>'use strict';

const {assert} = require('chai');
const Unitage = require('../../src/index');

describe('src/index.js', function () {

    it('should be class', function () {
        let unit1 = new Unitage(428, 10, ['', 'k', 'm']);

        assert.strictEqual(unit1.value, 428);
        assert.strictEqual(unit1.step, 10);
        assert.deepEqual(unit1.units, ['', 'k', 'm']);
    });

    it('class creator', function () {
        let unit1 = Unitage(5551, 11, ['', 'p']);

        assert.strictEqual(unit1.value, 5551);
        assert.strictEqual(unit1.step, 11);
        assert.deepEqual(unit1.units, ['', 'p']);
    });

    describe('@tryMaxUnit', function () {

        it('default', function () {
            let unitage = Unitage(12345678, 10000, ['', 'w', 'y']);

            assert.strictEqual(unitage.number, 1234.5678);
            assert.strictEqual(unitage.unit, 'w');
        });

        it('default run again', function () {
            let unitage = Unitage(100000000, 10000, ['', 'w', 'y']);

            assert.strictEqual(unitage.number, 1);
            assert.strictEqual(unitage.unit, 'y');

            unitage.tryMaxUnit();

            assert.strictEqual(unitage.number, 1);
            assert.strictEqual(unitage.unit, 'y');
        });

        it('1024 unit', function () {
            let unitage = Unitage(1073741824, 1024, ['B', 'KB', 'MB', 'GB']);

            assert.strictEqual(unitage.number, 1);
            assert.strictEqual(unitage.unit, 'GB');
        });

        it('overflow unit', function () {
            let unitage = Unitage(1073741824, 1024, ['B', 'KB', 'MB']);

            assert.strictEqual(unitage.number, 1024);
            assert.strictEqual(unitage.unit, 'MB');
        });

        it('empty unit', function () {
            let unitage = Unitage(1073741824, 1024, []);

            assert.strictEqual(unitage.number, 1073741824);
            assert.strictEqual(unitage.unit, '');
        });

        it('specify unit', function () {
            let unitage = Unitage(123456789, 1000, ['', 'k', 'm', 'g']);

            unitage.tryMaxUnit('k');

            assert.strictEqual(unitage.number, 123456.789);
            assert.strictEqual(unitage.unit, 'k');
        });

        it('specify unknow unit', function () {
            let unitage = Unitage(123456789, 1000, ['', 'k', 'm', 'g']);

            unitage.tryMaxUnit('j');

            assert.strictEqual(unitage.number, 123.456789);
            assert.strictEqual(unitage.unit, 'm');
        });

        it('specify overflow unit', function () {
            let unitage = Unitage(123456789, 1000, ['', 'k', 'm', 'g']);

            unitage.tryMaxUnit('g');

            assert.strictEqual(unitage.number, 123.456789);
            assert.strictEqual(unitage.unit, 'm');
        });

        it('float number', function () {
            let unitage = Unitage(19, 13, ['', 'n']);

            unitage.tryMaxUnit('n');

            assert.strictEqual(unitage.number, 1.4615384615384615);
        });

    });

});
<commit_msg>test toString<commit_after>'use strict';

const {assert} = require('chai');
const Unitage = require('../../src/index');

describe('src/index.js', function () {

    it('should be class', function () {
        let unit1 = new Unitage(428, 10, ['', 'k', 'm']);

        assert.strictEqual(unit1.value, 428);
        assert.strictEqual(unit1.step, 10);
        assert.deepEqual(unit1.units, ['', 'k', 'm']);
    });

    it('class creator', function () {
        let unit1 = Unitage(5551, 11, ['', 'p']);

        assert.strictEqual(unit1.value, 5551);
        assert.strictEqual(unit1.step, 11);
        assert.deepEqual(unit1.units, ['', 'p']);
    });

    describe('#tryMaxUnit', function () {

        it('default', function () {
            let unitage = Unitage(12345678, 10000, ['', 'w', 'y']);

            assert.strictEqual(unitage.number, 1234.5678);
            assert.strictEqual(unitage.unit, 'w');
        });

        it('default run again', function () {
            let unitage = Unitage(100000000, 10000, ['', 'w', 'y']);

            assert.strictEqual(unitage.number, 1);
            assert.strictEqual(unitage.unit, 'y');

            unitage.tryMaxUnit();

            assert.strictEqual(unitage.number, 1);
            assert.strictEqual(unitage.unit, 'y');
        });

        it('1024 unit', function () {
            let unitage = Unitage(1073741824, 1024, ['B', 'KB', 'MB', 'GB']);

            assert.strictEqual(unitage.number, 1);
            assert.strictEqual(unitage.unit, 'GB');
        });

        it('overflow unit', function () {
            let unitage = Unitage(1073741824, 1024, ['B', 'KB', 'MB']);

            assert.strictEqual(unitage.number, 1024);
            assert.strictEqual(unitage.unit, 'MB');
        });

        it('empty unit', function () {
            let unitage = Unitage(1073741824, 1024, []);

            assert.strictEqual(unitage.number, 1073741824);
            assert.strictEqual(unitage.unit, '');
        });

        it('specify unit', function () {
            let unitage = Unitage(123456789, 1000, ['', 'k', 'm', 'g']);

            unitage.tryMaxUnit('k');

            assert.strictEqual(unitage.number, 123456.789);
            assert.strictEqual(unitage.unit, 'k');
        });

        it('specify unknow unit', function () {
            let unitage = Unitage(123456789, 1000, ['', 'k', 'm', 'g']);

            unitage.tryMaxUnit('j');

            assert.strictEqual(unitage.number, 123.456789);
            assert.strictEqual(unitage.unit, 'm');
        });

        it('specify overflow unit', function () {
            let unitage = Unitage(123456789, 1000, ['', 'k', 'm', 'g']);

            unitage.tryMaxUnit('g');

            assert.strictEqual(unitage.number, 123.456789);
            assert.strictEqual(unitage.unit, 'm');
        });

        it('float number', function () {
            let unitage = Unitage(19, 13, ['', 'n']);

            unitage.tryMaxUnit('n');

            assert.strictEqual(unitage.number, 1.4615384615384615);
        });

    });

    describe('#toString', function () {

        it('default', function () {
            let unitage = Unitage(1012, 1000, ['', 'k']);

            assert.strictEqual(unitage.toString(), '1.012k');
            assert.strictEqual(String(unitage), '1.012k');
        });

        it('empty units', function () {
            let unitage = Unitage(1012, 1, []);

            assert.strictEqual(unitage.toString(), '1012');
        });
    });

});
<|endoftext|>


<commit_before>import details from './details';
import DefineMap from 'can-define/map/map';
import DefineList from 'can-define/list/list';
import connect from 'can-connect';
import constructor from 'can-connect/constructor/constructor';
import map from 'can-connect/can/map/map';

// mixin model property
const ViewModel = DefineMap.extend(Object.assign({model: '*'}, details));

// a basic can-connect implementation
const MyModel = DefineMap.extend({id: 'number'});
const List = DefineList.extend({'#': MyModel});
MyModel.connection = connect([constructor, map], {
    getList () {
        return [];
    },
    getData () {
        return [];
    },
    get (id) {
        debugger;
        return {id};
    },
    Map: MyModel,
    List
});

let vm, obj;
beforeEach (() => {
    vm = new ViewModel({
        model: MyModel
    });
    obj = new DefineMap({
        id: 1
    });
});
afterEach (() => {
    vm = null;
});

test('detailsPromise get() setDetailsObject', () => {
    expect.assertions(1);

    vm.setDetailsObject = obj;
    return expect(vm.detailsPromise).resolves.toEqual(obj);
});

// test('detailsPromise get() detailsId', () => {

//     vm.detailsId = 1;
//     return vm.detailsPromise.then((data) => {
//         expect(data.id).toEqual(1);
//         return data;
//     });
// });

test('showDetails(obj)', () => {
    vm.showDetails(obj);
    expect(vm.detailsId).toEqual(1);
});

test('showDetailsFromEvent(args)', () => {
    vm.showDetailsFromEvent([{}, obj]);
    expect(vm.detailsId).toEqual(1);
});

test('clearDetails()', () => {

    vm.showDetails(obj);
    vm.clearDetails();

    expect(vm.detailsId).toEqual(null);
    expect(vm.detailsPromise).toEqual(null);
});<commit_msg>fix tests<commit_after>import details from './details';
import DefineMap from 'can-define/map/map';
import DefineList from 'can-define/list/list';
import connect from 'can-connect';
import constructor from 'can-connect/constructor/constructor';
import map from 'can-connect/can/map/map';

// mixin model property
const ViewModel = DefineMap.extend(Object.assign({model: '*'}, details));

// a basic can-connect implementation
const MyMap = DefineMap.extend({id: 'number'});
const List = DefineList.extend({'#': MyMap});
const model = connect([constructor, map], {
    getList () {
        return [];
    },
    getData () {
        return [];
    },
    get (id) {
        return {id};
    },
    Map: MyMap,
    List
});

let vm, obj;
beforeEach (() => {
    vm = new ViewModel({
        model: model
    });
    obj = new DefineMap({
        id: 1
    });
});
afterEach (() => {
    vm = null;
});

test('detailsPromise get() setDetailsObject', () => {
    expect.assertions(1);

    vm.setDetailsObject = obj;
    return expect(vm.detailsPromise).resolves.toEqual(obj);
});

// test('detailsPromise get() detailsId', () => {

//     vm.detailsId = 1;
//     return vm.detailsPromise.then((data) => {
//         expect(data.id).toEqual(1);
//         return data;
//     });
// });

test('showDetails(obj)', () => {
    vm.showDetails(obj);
    expect(vm.detailsId).toEqual(1);
});

test('showDetailsFromEvent(args)', () => {
    vm.showDetailsFromEvent([{}, obj]);
    expect(vm.detailsId).toEqual(1);
});

test('clearDetails()', () => {

    vm.showDetails(obj);
    vm.clearDetails();

    expect(vm.detailsId).toEqual(null);
    expect(vm.detailsPromise).toEqual(null);
});<|endoftext|>