<commit_before>/*
* @Author: cuiyongjian
* @Date:   2016-04-07 23:08:00
* @Last Modified by:   cuiyongjian
* @Last Modified time: 2016-04-19 16:59:17
*/

var http = require('http');
var config = require('../config');
var Q = require('q');
var debug = require('debug')('resourceMeter:meter');

var pget = function (host, port) {
    var desPort = port || config.port;
    var url = 'http://' + host + ':' + desPort + '/api';
    var deferred = Q.defer();
    var req = http.get(url, function (res) {
        var chunks = [];
        debug('发起了get请求');
        debug(url);
        if (res.statusCode !== 200) {
            deferred.resolve(null);
        }
        else {
            res.on('data', function (d) {
                chunks.push(d);
            });
            res.on('end', function (d) {
                debug('拿到了get数据');
                debug(d);
                debug(chunks);
                var rel = Buffer.concat(chunks);
                try {
                    rel = JSON.parse(rel.toString());
                }
                catch (err) {
                    throw err;
                }
                if (rel instance of Object === false) {
                    rel = {host: host, weight: 0};
                }
                else {
                    rel.host = host;
                    debug(rel);
                }
                return deferred.resolve(rel);
            });
        }
    });
    req.on('error', function () {
        deferred.resolve({host: host, weight: 0});
    });
    return deferred.promise;
}

module.exports = function (input, port) {
    var deferred = Q.defer();
    var pros = [];
    for (var i = 0, len = input.length; i < len; i++) {
        var type = typeof input[i];
        var host;
        if (type === 'string') {
            host = input[i];
        }
        else {
            host = input[i].value;
        }
        pros.push(pget(host, port));
    }
    Q.all(pros).then(function (result) {
        debug('要对结果进行计算了，来看看：');
        var maxVcore = 0, maxMem = 0;
        // 算出节点中最大配置的vcore和mem，放入节点信息中，供physicalWeight算法使用。
        result.forEach(function (item) {
            if(item.memery && (item.memery.total > maxMem)) {
                maxMem = item.memery.total;
            }
            if (item.cpu && (item.cpu.vcores > maxVcore)) {
                maxVcore = item.cpu.vcores;
            }
        });
        result.forEach(function (item) {
            item.maxVcore = maxVcore;
            item.maxMem = maxMem;
        });
        debug('更新了集群节点的信息：', result);
        result = calWeight(result); // 对结果计算权重，结果不排序
        if (config.killzero) {
            // 剔除
            result = result.filter(function (item) {
                return item.weight !== 0;
            });
        }
        deferred.resolve(result);
    });
    return deferred.promise;
};

// infos格式为如下元素的数组：
// { host: 'xx.xxx.xx.xx', cpu: { vcores: 1, mhz: 2300, loadavg: 0.673828125, usage: '40%' }, memery: { total: 500380, used: 457592, free: 42788, shared: 148, buffers: 10524, cached: 148200, actualFree: 201512, percentUsed: 59.73, comparePercentUsed: '91.45' } }
function calWeight(infos) {
    debug('开始计算calWeight');
    infos = infos.map(function (item) {
        if (item.weight === 0) {
            // 这是请求失败的
            return {value: item.host, weight: 0};
        }
        var runtimeLoadValue = runtimeLoad(item);
        var runtimeWeightValue = runtimeWeight(runtimeLoadValue);
        debug('runtimeWeight计算完毕：', runtimeWeightValue);
        var physicalWeightValue = physicalWeight(item);
        var finalWeightValue = finalWeight(runtimeWeightValue, physicalWeightValue);
        return {value: item.host, weight: finalWeightValue};
    });
    debug('calWeight执行完成了', infos);
    return infos;
}

function finalWeight(runtimeV, physicalV) {
    debug('finalWeight计算开始，两个参数：', runtimeV, physicalV);
    var result = Math.round((runtimeV*3 + physicalV*1)/4);
    debug('finalWeightValue计算结束，结果：' + result);
    return result;
}

function runtimeLoad(item) {
    debug('来，runtimeLoad。 进来的值:', item);
    // 数值越大，负载越重
    var sumW = 0;
    var loadAvgW = 2, cpuUsageW = 1, memUsageW = 1, diskUsageW = 1;
    var loadAvgPercentage = 0, cpuUsagePercentage = 0, memUsagePercentage = 0
    , diskUsagePercentage = 0;
    if (config.cpu && item.cpu) {
        if (item.cpu.loadavg) {
            sumW += loadAvgW;
            loadAvgPercentage = processCPULoadAvg(item.cpu.loadavg);
        }
        if (item.cpu.usage) {
            sumW += cpuUsageW;
            cpuUsagePercentage = item.cpu.usage;
        }
    }
    if (config.memery && item.memery) {
        if (item.memery.percentUsed) {
            sumW += memUsageW;
            memUsagePercentage = item.memery.percentUsed;
        }
    }
    if (config.disk && item.disk.available && item.disk.total) {
        sumW += diskUsageW;
        // 磁盘的total是字节单位， memery的total是KB单位。。。
        diskUsagePercentage = (1 - (item.disk.available/item.disk.total))*100;
    }
    debug('runtimeLoad计算时的几个参数：' , sumW, loadAvgPercentage, cpuUsagePercentage, memUsagePercentage);
    var result = (loadAvgPercentage*loadAvgW + cpuUsagePercentage*cpuUsageW + memUsagePercentage*memUsageW + diskUsagePercentage*diskUsageW) / sumW;
    debug('runtimeLoad结果：', result);
    return result;
}

function runtimeWeight(loadValue) {
    // 数值越大，节点资源越空闲
    // 将资源负载 [0%-100%] 化为 [10-0]的权重值。 公式为： y=-0.1x+10
    return Math.round(((-0.1 * loadValue) + 10));
}

function physicalWeight(item) {
    debug('physicalWeightValue计算开始：');
    // 数值越大，节点配置越高，资源越好
    var sumW = 0;
    var vcoresW = 3, memW = 2, gpuW = 2;
    var vcoreValue = 0, memValue = 0, gpuValue = 0;
    var maxVcoreValue = 32, maxMemValue = 32, maxGpuValue = 1;
    if (config.cpu && item.cpu) {
        if (item.cpu.vcores) {
            vcoreValue = item.cpu.vcores;
            sumW += vcoresW;
        }
    }
    if (config.memery && item.memery) {
        if (item.memery.total) {
            // 这里内存的total是KB为单位
            memValue = item.memery.total;
            sumW += memW;
        }
    }
    if (config.gpu && item.gpu) {
        // 最简单的算法，有gpu，则gpu权重比就是0.8
        gpuValue = 1;
        sumW += gpuW;
    }
    else {
        gpuValue = 0.8;
        sumW += gpuW;
    }
    debug('physicalWeightValue的cpu信息：', vcoreValue, item.maxVcore,vcoresW);
    debug('physicalWeightValue的内存信息：', memValue,item.maxMem,memW);
    debug('physicalWeightValue的gpu信息', gpuValue,gpuW);
    debug('subW', sumW);
    var result = ((vcoreValue/item.maxVcore*vcoresW + memValue/item.maxMem*memW + gpuValue/1*gpuW)/sumW) * 10;
    result = Math.round(result);
    debug('result', result);
    return result > 10 ? 10 : result;
}

// 处理loadAvg数值为百分比
var processCPULoadAvg = function (value) {
    // 根据loadAvg实际效应，在[0-1]的时候变化影响较大，大于1的时候基本上处于高负载状态。
    if (value > 0 && value <=1) {
        // 映射为 [0%-80%]，公式 y = 80x
        return 80*value;

    }
    else if (value > 1) {
        if (value > 5) {
            return 100;
        }
        // 映射为 [80% - 100%]， 公式 y = 5x + 75
        return ((5 * value) + 75);
    }
    else {
        throw Error('loadAvg数值有误！');
    }
}

<commit_msg>fix instance<commit_after>/*
* @Author: cuiyongjian
* @Date:   2016-04-07 23:08:00
* @Last Modified by:   cuiyongjian
* @Last Modified time: 2016-04-19 16:59:59
*/

var http = require('http');
var config = require('../config');
var Q = require('q');
var debug = require('debug')('resourceMeter:meter');

var pget = function (host, port) {
    var desPort = port || config.port;
    var url = 'http://' + host + ':' + desPort + '/api';
    var deferred = Q.defer();
    var req = http.get(url, function (res) {
        var chunks = [];
        debug('发起了get请求');
        debug(url);
        if (res.statusCode !== 200) {
            deferred.resolve(null);
        }
        else {
            res.on('data', function (d) {
                chunks.push(d);
            });
            res.on('end', function (d) {
                debug('拿到了get数据');
                debug(d);
                debug(chunks);
                var rel = Buffer.concat(chunks);
                try {
                    rel = JSON.parse(rel.toString());
                }
                catch (err) {
                    throw err;
                }
                if (rel instanceof Object === false) {
                    rel = {host: host, weight: 0};
                }
                else {
                    rel.host = host;
                    debug(rel);
                }
                return deferred.resolve(rel);
            });
        }
    });
    req.on('error', function () {
        deferred.resolve({host: host, weight: 0});
    });
    return deferred.promise;
}

module.exports = function (input, port) {
    var deferred = Q.defer();
    var pros = [];
    for (var i = 0, len = input.length; i < len; i++) {
        var type = typeof input[i];
        var host;
        if (type === 'string') {
            host = input[i];
        }
        else {
            host = input[i].value;
        }
        pros.push(pget(host, port));
    }
    Q.all(pros).then(function (result) {
        debug('要对结果进行计算了，来看看：');
        var maxVcore = 0, maxMem = 0;
        // 算出节点中最大配置的vcore和mem，放入节点信息中，供physicalWeight算法使用。
        result.forEach(function (item) {
            if(item.memery && (item.memery.total > maxMem)) {
                maxMem = item.memery.total;
            }
            if (item.cpu && (item.cpu.vcores > maxVcore)) {
                maxVcore = item.cpu.vcores;
            }
        });
        result.forEach(function (item) {
            item.maxVcore = maxVcore;
            item.maxMem = maxMem;
        });
        debug('更新了集群节点的信息：', result);
        result = calWeight(result); // 对结果计算权重，结果不排序
        if (config.killzero) {
            // 剔除
            result = result.filter(function (item) {
                return item.weight !== 0;
            });
        }
        deferred.resolve(result);
    });
    return deferred.promise;
};

// infos格式为如下元素的数组：
// { host: 'xx.xxx.xx.xx', cpu: { vcores: 1, mhz: 2300, loadavg: 0.673828125, usage: '40%' }, memery: { total: 500380, used: 457592, free: 42788, shared: 148, buffers: 10524, cached: 148200, actualFree: 201512, percentUsed: 59.73, comparePercentUsed: '91.45' } }
function calWeight(infos) {
    debug('开始计算calWeight');
    infos = infos.map(function (item) {
        if (item.weight === 0) {
            // 这是请求失败的
            return {value: item.host, weight: 0};
        }
        var runtimeLoadValue = runtimeLoad(item);
        var runtimeWeightValue = runtimeWeight(runtimeLoadValue);
        debug('runtimeWeight计算完毕：', runtimeWeightValue);
        var physicalWeightValue = physicalWeight(item);
        var finalWeightValue = finalWeight(runtimeWeightValue, physicalWeightValue);
        return {value: item.host, weight: finalWeightValue};
    });
    debug('calWeight执行完成了', infos);
    return infos;
}

function finalWeight(runtimeV, physicalV) {
    debug('finalWeight计算开始，两个参数：', runtimeV, physicalV);
    var result = Math.round((runtimeV*3 + physicalV*1)/4);
    debug('finalWeightValue计算结束，结果：' + result);
    return result;
}

function runtimeLoad(item) {
    debug('来，runtimeLoad。 进来的值:', item);
    // 数值越大，负载越重
    var sumW = 0;
    var loadAvgW = 2, cpuUsageW = 1, memUsageW = 1, diskUsageW = 1;
    var loadAvgPercentage = 0, cpuUsagePercentage = 0, memUsagePercentage = 0
    , diskUsagePercentage = 0;
    if (config.cpu && item.cpu) {
        if (item.cpu.loadavg) {
            sumW += loadAvgW;
            loadAvgPercentage = processCPULoadAvg(item.cpu.loadavg);
        }
        if (item.cpu.usage) {
            sumW += cpuUsageW;
            cpuUsagePercentage = item.cpu.usage;
        }
    }
    if (config.memery && item.memery) {
        if (item.memery.percentUsed) {
            sumW += memUsageW;
            memUsagePercentage = item.memery.percentUsed;
        }
    }
    if (config.disk && item.disk.available && item.disk.total) {
        sumW += diskUsageW;
        // 磁盘的total是字节单位， memery的total是KB单位。。。
        diskUsagePercentage = (1 - (item.disk.available/item.disk.total))*100;
    }
    debug('runtimeLoad计算时的几个参数：' , sumW, loadAvgPercentage, cpuUsagePercentage, memUsagePercentage);
    var result = (loadAvgPercentage*loadAvgW + cpuUsagePercentage*cpuUsageW + memUsagePercentage*memUsageW + diskUsagePercentage*diskUsageW) / sumW;
    debug('runtimeLoad结果：', result);
    return result;
}

function runtimeWeight(loadValue) {
    // 数值越大，节点资源越空闲
    // 将资源负载 [0%-100%] 化为 [10-0]的权重值。 公式为： y=-0.1x+10
    return Math.round(((-0.1 * loadValue) + 10));
}

function physicalWeight(item) {
    debug('physicalWeightValue计算开始：');
    // 数值越大，节点配置越高，资源越好
    var sumW = 0;
    var vcoresW = 3, memW = 2, gpuW = 2;
    var vcoreValue = 0, memValue = 0, gpuValue = 0;
    var maxVcoreValue = 32, maxMemValue = 32, maxGpuValue = 1;
    if (config.cpu && item.cpu) {
        if (item.cpu.vcores) {
            vcoreValue = item.cpu.vcores;
            sumW += vcoresW;
        }
    }
    if (config.memery && item.memery) {
        if (item.memery.total) {
            // 这里内存的total是KB为单位
            memValue = item.memery.total;
            sumW += memW;
        }
    }
    if (config.gpu && item.gpu) {
        // 最简单的算法，有gpu，则gpu权重比就是0.8
        gpuValue = 1;
        sumW += gpuW;
    }
    else {
        gpuValue = 0.8;
        sumW += gpuW;
    }
    debug('physicalWeightValue的cpu信息：', vcoreValue, item.maxVcore,vcoresW);
    debug('physicalWeightValue的内存信息：', memValue,item.maxMem,memW);
    debug('physicalWeightValue的gpu信息', gpuValue,gpuW);
    debug('subW', sumW);
    var result = ((vcoreValue/item.maxVcore*vcoresW + memValue/item.maxMem*memW + gpuValue/1*gpuW)/sumW) * 10;
    result = Math.round(result);
    debug('result', result);
    return result > 10 ? 10 : result;
}

// 处理loadAvg数值为百分比
var processCPULoadAvg = function (value) {
    // 根据loadAvg实际效应，在[0-1]的时候变化影响较大，大于1的时候基本上处于高负载状态。
    if (value > 0 && value <=1) {
        // 映射为 [0%-80%]，公式 y = 80x
        return 80*value;

    }
    else if (value > 1) {
        if (value > 5) {
            return 100;
        }
        // 映射为 [80% - 100%]， 公式 y = 5x + 75
        return ((5 * value) + 75);
    }
    else {
        throw Error('loadAvg数值有误！');
    }
}

<|endoftext|>


<commit_before>var test = require('tape');

var Spec = require('./lib/amf/spec.js');
var Stream = require('./lib/io/stream.js');
var InputStream = require('./lib/io/input.js');
var OutputStream = require('./lib/io/output.js');
var AMF = require('./lib/amf/amf.js');

test('undefined', function(t) {
  t.plan(1);

  t.equal(AMF.deserialize(AMF.serialize()), undefined);
});

test('null', function(t) {
  t.plan(1);

  t.equal(AMF.deserialize(AMF.serialize(null)), null);
});

test('false', function(t) {
  t.plan(1);

  t.equal(AMF.deserialize(AMF.serialize(false)), false);
});

test('true', function(t) {
  t.plan(1);

  t.equal(AMF.deserialize(AMF.serialize(true)), true);
});

test('int', function(t) {

  var samples = [5, 100, -100, Spec.MIN_INT, Spec.MAX_INT, -109876983];
  t.plan(samples.length + 1);

  for(var i in samples) {
    var sample = samples[i];
    t.equal(AMF.deserialize(AMF.serialize(sample, true, Spec.AMF3_INT)), sample);
  }

  t.throws(function() {
    AMF.serialize(Spec.MAX_INT + 1, true, Spec.AMF3_INT);
  }, RangeError, 'should throw RangeError')

});

test('double', function(t) {
  t.plan(7);

  var samples = [-10, 0.3767574, Spec.MIN_INT, Spec.MAX_INT, Math.PI, Number.MAX_VALUE, Number.MIN_VALUE, 102.145];
  t.plan(samples.length);

  for(var i in samples) {
    var sample = samples[i];
    t.equal(AMF.deserialize(AMF.serialize(sample, true, Spec.AMF3_DOUBLE)), sample);
  }
});<commit_msg>Testing IE8<commit_after>var test = require('tape');

var Spec = require('./lib/amf/spec.js');
var Stream = require('./lib/io/stream.js');
var InputStream = require('./lib/io/input.js');
var OutputStream = require('./lib/io/output.js');
var AMF = require('./lib/amf/amf.js');

console.log(">>>> Serialized double: ", AMF.serialize(1.5, true, Spec.AMF3_DOUBLE));
console.log(">>>> Deserialized double: ", AMF.deserialize(AMF.serialize(1.5, true, Spec.AMF3_DOUBLE), Spec.AMF3_DOUBLE));

test('undefined', function(t) {
  t.plan(1);

  t.equal(AMF.deserialize(AMF.serialize()), undefined);
});

test('null', function(t) {
  t.plan(1);

  t.equal(AMF.deserialize(AMF.serialize(null)), null);
});

test('false', function(t) {
  t.plan(1);

  t.equal(AMF.deserialize(AMF.serialize(false)), false);
});

test('true', function(t) {
  t.plan(1);

  t.equal(AMF.deserialize(AMF.serialize(true)), true);
});

test('int', function(t) {

  var samples = [5, 100, -100, Spec.MIN_INT, Spec.MAX_INT, -109876983];
  t.plan(samples.length + 1);

  for(var i in samples) {
    var sample = samples[i];
    t.equal(AMF.deserialize(AMF.serialize(sample, true, Spec.AMF3_INT)), sample);
  }

  t.throws(function() {
    AMF.serialize(Spec.MAX_INT + 1, true, Spec.AMF3_INT);
  }, RangeError, 'should throw RangeError')

});

test('double', function(t) {
  t.plan(7);

  var samples = [-10, 0.3767574, Spec.MIN_INT, Spec.MAX_INT, Math.PI, Number.MAX_VALUE, Number.MIN_VALUE, 102.145];
  t.plan(samples.length);

  for(var i in samples) {
    var sample = samples[i];
    t.equal(AMF.deserialize(AMF.serialize(sample, true, Spec.AMF3_DOUBLE)), sample);
  }
});<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-12-3 21:15:52<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>'use strict'
var test = require('tape')
var iosIcons = require('./')

test('returns all icons in array', function (t) {
  t.plan(2)
  var icons = iosIcons()
  t.ok(Array.isArray(icons), 'returned an array')
  t.equal(icons.length, 15, '15 icons returned')
})

test('returns icon for size 60 as Number', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 60})
  t.ok(icon.name === 'icon-60.png', 'icon name correct')
  t.ok(icon.width === 60, 'icon width correct')
})

test('returns icon for size 60 as String', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '60'})
  t.ok(icon.name === 'icon-60.png', 'icon name correct')
  t.ok(icon.width === 60, 'icon width correct')
})

test('returns icon for size 120', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 120})
  t.ok(icon.name === 'icon-60@2x.png', 'icon name correct')
  t.ok(icon.width === 120, 'icon width correct')
})

test('returns icon for size 60@2x', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '60@2x'})
  t.ok(icon.name === 'icon-60@2x.png', 'icon name correct')
  t.ok(icon.width === 120, 'icon width correct')
})

test('returns icon for size 60@3x', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '60@3x'})
  t.ok(icon.name === 'icon-60@3x.png', 'icon name correct')
  t.ok(icon.width === 180, 'icon width correct')
})

test('returns icon for empty string with width 57', function (t) {
  t.plan(2)
  var icon = iosIcons({size: ''})
  t.ok(icon.name === 'icon.png', 'icon name correct')
  t.ok(icon.width === 57, 'icon width correct')
})

test('returns icon for size 57 as Number', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 57})
  t.ok(icon.name === 'icon.png', 'icon name correct')
  t.ok(icon.width === 57, 'icon width correct')
})

test('returns icon for size 57 as String', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '57'})
  t.ok(icon.name === 'icon.png', 'icon name correct')
  t.ok(icon.width === 57, 'icon width correct')
})

test('returns icon for @2x', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '@2x'})
  t.ok(icon.name === 'icon@2x.png', 'icon name correct')
  t.ok(icon.width === 114, 'icon width correct')
})

test('returns icon for size 114 as Number', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 114})
  t.ok(icon.name === 'icon@2x.png', 'icon name correct')
  t.ok(icon.width === 114, 'icon width correct')
})

test('returns icon for size 114 as String', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '114'})
  t.ok(icon.name === 'icon@2x.png', 'icon name correct')
  t.ok(icon.width === 114, 'icon width correct')
})

test('returns null for size 123', function (t) {
  t.plan(1)
  var icon = iosIcons({size: 123})
  t.ok(icon === null)
})

test('returns icon for size 29 as small', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 29})
  t.ok(icon.name === 'icon-small.png', 'icon name correct')
  t.ok(icon.width === 29, 'icon width correct')
})

test('returns icon for size 58 as small@2x', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 58})
  t.ok(icon.name === 'icon-small@2x.png', 'icon name correct')
  t.ok(icon.width === 58, 'icon width correct')
})

test('returns icon for file name icon-small@2x.png', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 'icon-small@2x.png'})
  t.ok(icon.name === 'icon-small@2x.png', 'icon name correct')
  t.ok(icon.width === 58, 'icon width correct')
})

test('returns icon for file name icon.png', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 'icon.png'})
  t.ok(icon.name === 'icon.png', 'icon name correct')
  t.ok(icon.width === 57, 'icon width correct')
})
<commit_msg>test: abbreviated flags<commit_after>'use strict'
var test = require('tape')
var iosIcons = require('./')
var exec = require('child_process').exec

test('returns all icons in array', function (t) {
  t.plan(2)
  var icons = iosIcons()
  t.ok(Array.isArray(icons), 'returned an array')
  t.equal(icons.length, 15, '15 icons returned')
})

test('returns icon for size 60 as Number', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 60})
  t.ok(icon.name === 'icon-60.png', 'icon name correct')
  t.ok(icon.width === 60, 'icon width correct')
})

test('returns icon for size 60 as String', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '60'})
  t.ok(icon.name === 'icon-60.png', 'icon name correct')
  t.ok(icon.width === 60, 'icon width correct')
})

test('returns icon for size 120', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 120})
  t.ok(icon.name === 'icon-60@2x.png', 'icon name correct')
  t.ok(icon.width === 120, 'icon width correct')
})

test('returns icon for size 60@2x', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '60@2x'})
  t.ok(icon.name === 'icon-60@2x.png', 'icon name correct')
  t.ok(icon.width === 120, 'icon width correct')
})

test('returns icon for size 60@3x', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '60@3x'})
  t.ok(icon.name === 'icon-60@3x.png', 'icon name correct')
  t.ok(icon.width === 180, 'icon width correct')
})

test('returns icon for empty string with width 57', function (t) {
  t.plan(2)
  var icon = iosIcons({size: ''})
  t.ok(icon.name === 'icon.png', 'icon name correct')
  t.ok(icon.width === 57, 'icon width correct')
})

test('returns icon for size 57 as Number', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 57})
  t.ok(icon.name === 'icon.png', 'icon name correct')
  t.ok(icon.width === 57, 'icon width correct')
})

test('returns icon for size 57 as String', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '57'})
  t.ok(icon.name === 'icon.png', 'icon name correct')
  t.ok(icon.width === 57, 'icon width correct')
})

test('returns icon for @2x', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '@2x'})
  t.ok(icon.name === 'icon@2x.png', 'icon name correct')
  t.ok(icon.width === 114, 'icon width correct')
})

test('returns icon for size 114 as Number', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 114})
  t.ok(icon.name === 'icon@2x.png', 'icon name correct')
  t.ok(icon.width === 114, 'icon width correct')
})

test('returns icon for size 114 as String', function (t) {
  t.plan(2)
  var icon = iosIcons({size: '114'})
  t.ok(icon.name === 'icon@2x.png', 'icon name correct')
  t.ok(icon.width === 114, 'icon width correct')
})

test('returns null for size 123', function (t) {
  t.plan(1)
  var icon = iosIcons({size: 123})
  t.ok(icon === null)
})

test('returns icon for size 29 as small', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 29})
  t.ok(icon.name === 'icon-small.png', 'icon name correct')
  t.ok(icon.width === 29, 'icon width correct')
})

test('returns icon for size 58 as small@2x', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 58})
  t.ok(icon.name === 'icon-small@2x.png', 'icon name correct')
  t.ok(icon.width === 58, 'icon width correct')
})

test('returns icon for file name icon-small@2x.png', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 'icon-small@2x.png'})
  t.ok(icon.name === 'icon-small@2x.png', 'icon name correct')
  t.ok(icon.width === 58, 'icon width correct')
})

test('returns icon for file name icon.png', function (t) {
  t.plan(2)
  var icon = iosIcons({size: 'icon.png'})
  t.ok(icon.name === 'icon.png', 'icon name correct')
  t.ok(icon.width === 57, 'icon width correct')
})

test('cli returns all images as csv', function (t) {
  t.plan(1)
  var expected = [
    'icon-60@3x.png,180',
    'icon-60.png,60',
    'icon-60@2x.png,120',
    'icon-76.png,76',
    'icon-76@2x.png,152',
    'icon-40.png,40',
    'icon-40@2x.png,80',
    'icon.png,57',
    'icon@2x.png,114',
    'icon-72.png,72',
    'icon-72@2x.png,144',
    'icon-small.png,29',
    'icon-small@2x.png,58',
    'icon-50.png,50',
    'icon-50@2x.png,100\n'
  ].join('\n')
  exec('./bin/ios-icons.js', function (error, stdout, stderr) {
    var err = error || stderr
    if (err) {
      return t.fail('calling cli produced an error: ' + err)
    }
    t.equal(stdout, expected, 'cli returned expected output')
  })
})

test('cli returns image with specified size as csv', function (t) {
  t.plan(1)
  var expected = 'icon-60@3x.png,180\n'
  exec('./bin/ios-icons.js --size 180', function (error, stdout, stderr) {
    var err = error || stderr
    if (err) {
      return t.fail('calling cli produced an error: ' + err)
    }
    t.equal(stdout, expected, 'cli returned expected output')
  })
})

test('cli returns image with specified size as csv with abbreviated flags', function (t) {
  t.plan(3)
  var expected = 'Default~iphone.png,320,480\n'
  exec('./bin/ios-icons.js --siz 180', function (error, stdout, stderr) {
    var err = error || stderr
    if (err) {
      return t.fail('calling cli produced an error: ' + err)
    }
    t.equal(stdout, expected, 'cli returned expected output')
  })
  exec('./bin/ios-icons.js --si 180', function (error, stdout, stderr) {
    var err = error || stderr
    if (err) {
      return t.fail('calling cli produced an error: ' + err)
    }
    t.equal(stdout, expected, 'cli returned expected output')
  })
  exec('./bin/ios-icons.js --s 180', function (error, stdout, stderr) {
    var err = error || stderr
    if (err) {
      return t.fail('calling cli produced an error: ' + err)
    }
    t.equal(stdout, expected, 'cli returned expected output')
  })
})

test('cli returns correct image for size "60@3x" as json', function (t) {
  t.plan(1)
  var expected = '{"name":"icon-60@3x.png","width":180}\n'
  exec('./bin/ios-icons.js --size 60@3x --format json', function (error, stdout, stderr) {
    var err = error || stderr
    if (err) {
      return t.fail('calling cli produced an error: ' + err)
    }
    t.equal(stdout, expected, 'cli returned expected output')
  })
})

test('cli returns correct image for size "60@3x" as json w/ abbreviated flags', function (t) {
  t.plan(1)
  var expected = '{"name":"icon-60@3x.png","width":180}\n'
  exec('./bin/ios-icons.js --s 60@3x --for json', function (error, stdout, stderr) {
    var err = error || stderr
    if (err) {
      return t.fail('calling cli produced an error: ' + err)
    }
    t.equal(stdout, expected, 'cli returned expected output')
  })
})
<|endoftext|>


<commit_before>import test from 'ava';
import isIp from 'is-ip';
import fn from './';

test('main', t => {
	t.true(isIp.v4(fn()));
	t.end();
});

test('IPv4', t => {
	t.true(isIp.v4(fn.v4()));
	t.end();
});

test('IPv6', t => {
	t.true(isIp.v6(fn.v6()));
	t.end();
});
<commit_msg>update tests for latest AVA version<commit_after>import test from 'ava';
import isIp from 'is-ip';
import m from './';

test('main', t => {
	t.true(isIp.v4(m()));
});

test('IPv4', t => {
	t.true(isIp.v4(m.v4()));
});

test('IPv6', t => {
	t.true(isIp.v6(m.v6()));
});
<|endoftext|>


<commit_before>/*!
 * mocha
 * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var path = require('path')
  , utils = require('./utils')
  , join = path.join
  , cwd = process.cwd();

/**
 * Expose `Mocha`.
 */

exports = module.exports = Mocha;

/**
 * Expose internals.
 */

exports.utils = utils;
exports.interfaces = require('./interfaces');
exports.reporters = require('./reporters');
exports.Runnable = require('./runnable');
exports.Context = require('./context');
exports.Runner = require('./runner');
exports.Suite = require('./suite');
exports.Hook = require('./hook');
exports.Test = require('./test');

/**
 * Return image `name` path.
 *
 * @param {String} name
 * @return {String}
 * @api private
 */

function image(name) {
  return __dirname + '/../images/' + name + '.png';
}

/**
 * Setup mocha with `options`.
 *
 * Options:
 *
 *   - `ui` name "bdd", "tdd", "exports" etc
 *   - `reporter` reporter instance, defaults to `mocha.reporters.spec`
 *   - `globals` array of accepted globals
 *   - `timeout` timeout in milliseconds
 *   - `bail` bail on the first test failure
 *   - `slow` milliseconds to wait before considering a test slow
 *   - `ignoreLeaks` ignore global leaks
 *   - `grep` string or regexp to filter tests with
 *
 * @param {Object} options
 * @api public
 */

function Mocha(options) {
  module.paths.push(cwd, join(cwd, 'node_modules'));
  options = options || {};
  this.files = [];
  this.options = options;
  this.grep(options.grep);
  this.suite = new exports.Suite('', new exports.Context);
  this.ui(options.ui);
  this.bail(options.bail);
  this.reporter(options.reporter);
  if (null != options.timeout) this.timeout(options.timeout);
  this.useColors(options.useColors)
  if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts);
  if (options.slow) this.slow(options.slow);

  this.suite.on('pre-require', function (context) {
    exports.afterEach = context.afterEach || context.teardown;
    exports.after = context.after || context.suiteTeardown;
    exports.beforeEach = context.beforeEach || context.setup;
    exports.before = context.before || context.suiteSetup;
    exports.describe = context.describe || context.suite;
    exports.it = context.it || context.test;
    exports.setup = context.setup || context.beforeEach;
    exports.suiteSetup = context.suiteSetup || context.before;
    exports.suiteTeardown = context.suiteTeardown || context.after;
    exports.suite = context.suite || context.describe;
    exports.teardown = context.teardown || context.afterEach;
    exports.test = context.test || context.it;
  });
}

/**
 * Enable or disable bailing on the first failure.
 *
 * @param {Boolean} [bail]
 * @api public
 */

Mocha.prototype.bail = function(bail){
  if (0 == arguments.length) bail = true;
  this.suite.bail(bail);
  return this;
};

/**
 * Add test `file`.
 *
 * @param {String} file
 * @api public
 */

Mocha.prototype.addFile = function(file){
  this.files.push(file);
  return this;
};

/**
 * Set reporter to `reporter`, defaults to "spec".
 *
 * @param {String|Function} reporter name or constructor
 * @api public
 */

Mocha.prototype.reporter = function(reporter){
  if ('function' == typeof reporter) {
    this._reporter = reporter;
  } else {
    reporter = reporter || 'spec';
    var _reporter;
    try { _reporter = require('./reporters/' + reporter); } catch (err) {};
    if (!_reporter) try { _reporter = require(reporter); } catch (err) {};
    if (!_reporter && reporter === 'teamcity')
      console.warn('The Teamcity reporter was moved to a package named ' +
        'mocha-teamcity-reporter ' +
        '(https://npmjs.org/package/mocha-teamcity-reporter).');
    if (!_reporter) throw new Error('invalid reporter "' + reporter + '"');
    this._reporter = _reporter;
  }
  return this;
};

/**
 * Set test UI `name`, defaults to "bdd".
 *
 * @param {String} bdd
 * @api public
 */

Mocha.prototype.ui = function(name){
  name = name || 'bdd';
  this._ui = exports.interfaces[name];
  if (!this._ui) try { this._ui = require(name); } catch (err) {};
  if (!this._ui) throw new Error('invalid interface "' + name + '"');
  this._ui = this._ui(this.suite);
  return this;
};

/**
 * Load registered files.
 *
 * @api private
 */

Mocha.prototype.loadFiles = function(fn){
  var self = this;
  var suite = this.suite;
  var pending = this.files.length;
  this.files.forEach(function(file){
    file = path.resolve(file);
    suite.emit('pre-require', global, file, self);
    suite.emit('require', require(file), file, self);
    suite.emit('post-require', global, file, self);
    --pending || (fn && fn());
  });
};

/**
 * Enable growl support.
 *
 * @api private
 */

Mocha.prototype._growl = function(runner, reporter) {
  var notify = require('growl');

  runner.on('end', function(){
    var stats = reporter.stats;
    if (stats.failures) {
      var msg = stats.failures + ' of ' + runner.total + ' tests failed';
      notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
    } else {
      notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
          name: 'mocha'
        , title: 'Passed'
        , image: image('ok')
      });
    }
  });
};

/**
 * Add regexp to grep, if `re` is a string it is escaped.
 *
 * @param {RegExp|String} re
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.grep = function(re){
  this.options.grep = 'string' == typeof re
    ? new RegExp(utils.escapeRegexp(re))
    : re;
  return this;
};

/**
 * Invert `.grep()` matches.
 *
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.invert = function(){
  this.options.invert = true;
  return this;
};

/**
 * Ignore global leaks.
 *
 * @param {Boolean} ignore
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.ignoreLeaks = function(ignore){
  this.options.ignoreLeaks = !!ignore;
  return this;
};

/**
 * Enable global leak checking.
 *
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.checkLeaks = function(){
  this.options.ignoreLeaks = false;
  return this;
};

/**
 * Enable growl support.
 *
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.growl = function(){
  this.options.growl = true;
  return this;
};

/**
 * Ignore `globals` array or string.
 *
 * @param {Array|String} globals
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.globals = function(globals){
  this.options.globals = (this.options.globals || []).concat(globals);
  return this;
};

/**
 * Emit color output.
 *
 * @param {Boolean} colors
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.useColors = function(colors){
  this.options.useColors = arguments.length && colors != undefined
    ? colors
    : true;
  return this;
};

/**
 * Use inline diffs rather than +/-.
 *
 * @param {Boolean} inlineDiffs
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.useInlineDiffs = function(inlineDiffs) {
  this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined
  ? inlineDiffs
  : false;
  return this;
};

/**
 * Set the timeout in milliseconds.
 *
 * @param {Number} timeout
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.timeout = function(timeout){
  this.suite.timeout(timeout);
  return this;
};

/**
 * Set slowness threshold in milliseconds.
 *
 * @param {Number} slow
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.slow = function(slow){
  this.suite.slow(slow);
  return this;
};

/**
 * Enable timeouts.
 *
 * @param {Boolean} enabled
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.enableTimeouts = function(enabled) {
  this.suite.enableTimeouts(arguments.length && enabled !== undefined
    ? enabled
    : true);
  return this
};

/**
 * Makes all tests async (accepting a callback)
 *
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.asyncOnly = function(){
  this.options.asyncOnly = true;
  return this;
};

/**
 * Run tests and invoke `fn()` when complete.
 *
 * @param {Function} fn
 * @return {Runner}
 * @api public
 */

Mocha.prototype.run = function(fn){
  if (this.files.length) this.loadFiles();
  var suite = this.suite;
  var options = this.options;
  options.files = this.files;
  var runner = new exports.Runner(suite);
  var reporter = new this._reporter(runner, options);
  runner.ignoreLeaks = false !== options.ignoreLeaks;
  runner.asyncOnly = options.asyncOnly;
  if (options.grep) runner.grep(options.grep, options.invert);
  if (options.globals) runner.globals(options.globals);
  if (options.growl) this._growl(runner, reporter);
  exports.reporters.Base.useColors = options.useColors;
  exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
  return runner.run(fn);
};
<commit_msg>Cleanup #1267<commit_after>/*!
 * mocha
 * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var path = require('path')
  , utils = require('./utils')
  , join = path.join
  , cwd = process.cwd();

/**
 * Add node_modules directory to use local modules for ui and reporters.
 */

module.paths.push(cwd, join(cwd, 'node_modules'));

/**
 * Expose `Mocha`.
 */

exports = module.exports = Mocha;

/**
 * Expose internals.
 */

exports.utils = utils;
exports.interfaces = require('./interfaces');
exports.reporters = require('./reporters');
exports.Runnable = require('./runnable');
exports.Context = require('./context');
exports.Runner = require('./runner');
exports.Suite = require('./suite');
exports.Hook = require('./hook');
exports.Test = require('./test');

/**
 * Return image `name` path.
 *
 * @param {String} name
 * @return {String}
 * @api private
 */

function image(name) {
  return __dirname + '/../images/' + name + '.png';
}

/**
 * Setup mocha with `options`.
 *
 * Options:
 *
 *   - `ui` name "bdd", "tdd", "exports" etc
 *   - `reporter` reporter instance, defaults to `mocha.reporters.spec`
 *   - `globals` array of accepted globals
 *   - `timeout` timeout in milliseconds
 *   - `bail` bail on the first test failure
 *   - `slow` milliseconds to wait before considering a test slow
 *   - `ignoreLeaks` ignore global leaks
 *   - `grep` string or regexp to filter tests with
 *
 * @param {Object} options
 * @api public
 */

function Mocha(options) {
  options = options || {};
  this.files = [];
  this.options = options;
  this.grep(options.grep);
  this.suite = new exports.Suite('', new exports.Context);
  this.ui(options.ui);
  this.bail(options.bail);
  this.reporter(options.reporter);
  if (null != options.timeout) this.timeout(options.timeout);
  this.useColors(options.useColors)
  if (options.enableTimeouts !== null) this.enableTimeouts(options.enableTimeouts);
  if (options.slow) this.slow(options.slow);

  this.suite.on('pre-require', function (context) {
    exports.afterEach = context.afterEach || context.teardown;
    exports.after = context.after || context.suiteTeardown;
    exports.beforeEach = context.beforeEach || context.setup;
    exports.before = context.before || context.suiteSetup;
    exports.describe = context.describe || context.suite;
    exports.it = context.it || context.test;
    exports.setup = context.setup || context.beforeEach;
    exports.suiteSetup = context.suiteSetup || context.before;
    exports.suiteTeardown = context.suiteTeardown || context.after;
    exports.suite = context.suite || context.describe;
    exports.teardown = context.teardown || context.afterEach;
    exports.test = context.test || context.it;
  });
}

/**
 * Enable or disable bailing on the first failure.
 *
 * @param {Boolean} [bail]
 * @api public
 */

Mocha.prototype.bail = function(bail){
  if (0 == arguments.length) bail = true;
  this.suite.bail(bail);
  return this;
};

/**
 * Add test `file`.
 *
 * @param {String} file
 * @api public
 */

Mocha.prototype.addFile = function(file){
  this.files.push(file);
  return this;
};

/**
 * Set reporter to `reporter`, defaults to "spec".
 *
 * @param {String|Function} reporter name or constructor
 * @api public
 */

Mocha.prototype.reporter = function(reporter){
  if ('function' == typeof reporter) {
    this._reporter = reporter;
  } else {
    reporter = reporter || 'spec';
    var _reporter;
    try { _reporter = require('./reporters/' + reporter); } catch (err) {};
    if (!_reporter) try { _reporter = require(reporter); } catch (err) {};
    if (!_reporter && reporter === 'teamcity')
      console.warn('The Teamcity reporter was moved to a package named ' +
        'mocha-teamcity-reporter ' +
        '(https://npmjs.org/package/mocha-teamcity-reporter).');
    if (!_reporter) throw new Error('invalid reporter "' + reporter + '"');
    this._reporter = _reporter;
  }
  return this;
};

/**
 * Set test UI `name`, defaults to "bdd".
 *
 * @param {String} bdd
 * @api public
 */

Mocha.prototype.ui = function(name){
  name = name || 'bdd';
  this._ui = exports.interfaces[name];
  if (!this._ui) try { this._ui = require(name); } catch (err) {};
  if (!this._ui) throw new Error('invalid interface "' + name + '"');
  this._ui = this._ui(this.suite);
  return this;
};

/**
 * Load registered files.
 *
 * @api private
 */

Mocha.prototype.loadFiles = function(fn){
  var self = this;
  var suite = this.suite;
  var pending = this.files.length;
  this.files.forEach(function(file){
    file = path.resolve(file);
    suite.emit('pre-require', global, file, self);
    suite.emit('require', require(file), file, self);
    suite.emit('post-require', global, file, self);
    --pending || (fn && fn());
  });
};

/**
 * Enable growl support.
 *
 * @api private
 */

Mocha.prototype._growl = function(runner, reporter) {
  var notify = require('growl');

  runner.on('end', function(){
    var stats = reporter.stats;
    if (stats.failures) {
      var msg = stats.failures + ' of ' + runner.total + ' tests failed';
      notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
    } else {
      notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
          name: 'mocha'
        , title: 'Passed'
        , image: image('ok')
      });
    }
  });
};

/**
 * Add regexp to grep, if `re` is a string it is escaped.
 *
 * @param {RegExp|String} re
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.grep = function(re){
  this.options.grep = 'string' == typeof re
    ? new RegExp(utils.escapeRegexp(re))
    : re;
  return this;
};

/**
 * Invert `.grep()` matches.
 *
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.invert = function(){
  this.options.invert = true;
  return this;
};

/**
 * Ignore global leaks.
 *
 * @param {Boolean} ignore
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.ignoreLeaks = function(ignore){
  this.options.ignoreLeaks = !!ignore;
  return this;
};

/**
 * Enable global leak checking.
 *
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.checkLeaks = function(){
  this.options.ignoreLeaks = false;
  return this;
};

/**
 * Enable growl support.
 *
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.growl = function(){
  this.options.growl = true;
  return this;
};

/**
 * Ignore `globals` array or string.
 *
 * @param {Array|String} globals
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.globals = function(globals){
  this.options.globals = (this.options.globals || []).concat(globals);
  return this;
};

/**
 * Emit color output.
 *
 * @param {Boolean} colors
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.useColors = function(colors){
  this.options.useColors = arguments.length && colors != undefined
    ? colors
    : true;
  return this;
};

/**
 * Use inline diffs rather than +/-.
 *
 * @param {Boolean} inlineDiffs
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.useInlineDiffs = function(inlineDiffs) {
  this.options.useInlineDiffs = arguments.length && inlineDiffs != undefined
  ? inlineDiffs
  : false;
  return this;
};

/**
 * Set the timeout in milliseconds.
 *
 * @param {Number} timeout
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.timeout = function(timeout){
  this.suite.timeout(timeout);
  return this;
};

/**
 * Set slowness threshold in milliseconds.
 *
 * @param {Number} slow
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.slow = function(slow){
  this.suite.slow(slow);
  return this;
};

/**
 * Enable timeouts.
 *
 * @param {Boolean} enabled
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.enableTimeouts = function(enabled) {
  this.suite.enableTimeouts(arguments.length && enabled !== undefined
    ? enabled
    : true);
  return this
};

/**
 * Makes all tests async (accepting a callback)
 *
 * @return {Mocha}
 * @api public
 */

Mocha.prototype.asyncOnly = function(){
  this.options.asyncOnly = true;
  return this;
};

/**
 * Run tests and invoke `fn()` when complete.
 *
 * @param {Function} fn
 * @return {Runner}
 * @api public
 */

Mocha.prototype.run = function(fn){
  if (this.files.length) this.loadFiles();
  var suite = this.suite;
  var options = this.options;
  options.files = this.files;
  var runner = new exports.Runner(suite);
  var reporter = new this._reporter(runner, options);
  runner.ignoreLeaks = false !== options.ignoreLeaks;
  runner.asyncOnly = options.asyncOnly;
  if (options.grep) runner.grep(options.grep, options.invert);
  if (options.globals) runner.globals(options.globals);
  if (options.growl) this._growl(runner, reporter);
  exports.reporters.Base.useColors = options.useColors;
  exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
  return runner.run(fn);
};
<|endoftext|>


<commit_before>/*
Name:           pastecapi - test.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-pastecapi
Feedback:       https://github.com/fvdm/nodejs-pastecapi/issues
License:        Unlicense (Public Domain, see LICENSE file)
                (https://github.com/fvdm/nodejs-pastecapi/raw/develop/LICENSE)
*/

const fs = require ('fs');
const dotest = require ('dotest');
const app = require ('./');
const path = require ('path');
const dir = path.dirname (module.filename);

const endpoint = process.env.PASTEC_ENDPOINT || 'http://localhost:4212';
const indexid = process.env.PASTEC_INDEXID || null;
const authkey = process.env.PASTEC_AUTHKEY || null;
const timeout = process.env.PASTEC_TIMEOUT || 5000;

const pastec = app ({
  endpoint,
  indexid,
  authkey,
  timeout
});

// Tests
dotest.add ('Module', function (test) {
  test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'module', pastec)
    .isFunction ('fail', '.ping', pastec && pastec.ping)
    .isFunction ('fail', '.writeIndex', pastec && pastec.writeIndex)
    .isFunction ('fail', '.clearIndex', pastec && pastec.clearIndex)
    .isFunction ('fail', '.loadIndex', pastec && pastec.loadIndex)
    .isFunction ('fail', '.searchIndex', pastec && pastec.searchIndex)
    .isFunction ('fail', '.addImage', pastec && pastec.addImage)
    .isFunction ('fail', '.deleteImage', pastec && pastec.deleteImage)
    .done ();
});

dotest.add ('Method ping', function (test) {
  pastec.ping (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'PONG')
      .done ();
  });
});

dotest.add ('Method writeIndex', function (test) {
  pastec.writeIndex ('./sampleIndex.dat', function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'INDEX_WRITTEN')
      .done ();
  });
});

dotest.add ('Method clearIndex', function (test) {
  pastec.clearIndex (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'INDEX_CLEARED')
      .done ();
  });
});

dotest.add ('Method loadIndex', function (test) {
  pastec.loadIndex ('./sampleIndex.dat', function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'INDEX_LOADED')
      .done ();
  });
});

dotest.add ('Method addImage - filename', function (test) {
  pastec.addImage (path.join (dir, 'imageSample.jpg'), 999999999999999, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'IMAGE_ADDED')
      .done ();
  });
});

dotest.add ('Method addImage - buffer', function (test) {
  fs.readFile (path.join (dir, 'imageSample.jpg'), function (errFile, file) {
    test (errFile);

    pastec.addImage (file, 999999999999999, function (err, data) {
      test (err)
        .isObject ('fail', 'data', data)
        .isExactly ('warn', 'data.type', data && data.type, 'IMAGE_ADDED')
        .done ();
    });
  });
});

dotest.add ('Method addImage - error', function (test) {
  pastec.addImage ('', 999999999999999, function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .info (err.message)
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Method searchIndex - filename', function (test) {
  pastec.searchIndex (path.join (dir, 'imageSample.jpg'), function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'SEARCH_RESULTS')
      .done ();
  });
});

dotest.add ('Method searchIndex - buffer', function (test) {
  fs.readFile (path.join (dir, 'imageSample.jpg'), function (errFile, file) {
    test (errFile);

    pastec.searchIndex (file, function (err, data) {
      test (err)
        .isObject ('fail', 'data', data)
        .isExactly ('warn', 'data.type', data && data.type, 'SEARCH_RESULTS')
        .done ();
    });
  });
});

dotest.add ('Method searchIndex - error', function (test) {
  pastec.searchIndex ('', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .info (err.message)
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Method deleteImage', function (test) {
  pastec.deleteImage (999999999999999, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'IMAGE_REMOVED')
      .done ();
  });
});

dotest.add ('Error: invalid authkey', function (test) {
  const tmp = app (endpoint, timeout);

  tmp.writeIndex ('./sampleIndex.dat', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'invalid authkey')
      .isExactly ('fail', 'err.error', err && err.error, 'AUTHENTIFICATION_ERROR')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Error: request failed', function (test) {
  const tmp = app (endpoint, authkey, 1);

  tmp.writeIndex ('./sampleIndex.dat', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'request failed')
      .isError ('fail', 'err.error', err && err.error)
      .isExactly ('fail', 'err.error.code', err && err.error && err.error.code, 'TIMEOUT')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

// Start the tests
dotest.run ();
<commit_msg>Test(fix): warn about invalid authkey response<commit_after>/*
Name:           pastecapi - test.js
Author:         Franklin van de Meent (https://frankl.in)
Source & docs:  https://github.com/fvdm/nodejs-pastecapi
Feedback:       https://github.com/fvdm/nodejs-pastecapi/issues
License:        Unlicense (Public Domain, see LICENSE file)
                (https://github.com/fvdm/nodejs-pastecapi/raw/develop/LICENSE)
*/

const fs = require ('fs');
const dotest = require ('dotest');
const app = require ('./');
const path = require ('path');
const dir = path.dirname (module.filename);

const endpoint = process.env.PASTEC_ENDPOINT || 'http://localhost:4212';
const indexid = process.env.PASTEC_INDEXID || null;
const authkey = process.env.PASTEC_AUTHKEY || null;
const timeout = process.env.PASTEC_TIMEOUT || 5000;

const pastec = app ({
  endpoint,
  indexid,
  authkey,
  timeout
});

// Tests
dotest.add ('Module', function (test) {
  test ()
    .isFunction ('fail', 'exports', app)
    .isObject ('fail', 'module', pastec)
    .isFunction ('fail', '.ping', pastec && pastec.ping)
    .isFunction ('fail', '.writeIndex', pastec && pastec.writeIndex)
    .isFunction ('fail', '.clearIndex', pastec && pastec.clearIndex)
    .isFunction ('fail', '.loadIndex', pastec && pastec.loadIndex)
    .isFunction ('fail', '.searchIndex', pastec && pastec.searchIndex)
    .isFunction ('fail', '.addImage', pastec && pastec.addImage)
    .isFunction ('fail', '.deleteImage', pastec && pastec.deleteImage)
    .done ();
});

dotest.add ('Method ping', function (test) {
  pastec.ping (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'PONG')
      .done ();
  });
});

dotest.add ('Method writeIndex', function (test) {
  pastec.writeIndex ('./sampleIndex.dat', function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'INDEX_WRITTEN')
      .done ();
  });
});

dotest.add ('Method clearIndex', function (test) {
  pastec.clearIndex (function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'INDEX_CLEARED')
      .done ();
  });
});

dotest.add ('Method loadIndex', function (test) {
  pastec.loadIndex ('./sampleIndex.dat', function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'INDEX_LOADED')
      .done ();
  });
});

dotest.add ('Method addImage - filename', function (test) {
  pastec.addImage (path.join (dir, 'imageSample.jpg'), 999999999999999, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'IMAGE_ADDED')
      .done ();
  });
});

dotest.add ('Method addImage - buffer', function (test) {
  fs.readFile (path.join (dir, 'imageSample.jpg'), function (errFile, file) {
    test (errFile);

    pastec.addImage (file, 999999999999999, function (err, data) {
      test (err)
        .isObject ('fail', 'data', data)
        .isExactly ('warn', 'data.type', data && data.type, 'IMAGE_ADDED')
        .done ();
    });
  });
});

dotest.add ('Method addImage - error', function (test) {
  pastec.addImage ('', 999999999999999, function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .info (err.message)
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Method searchIndex - filename', function (test) {
  pastec.searchIndex (path.join (dir, 'imageSample.jpg'), function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'SEARCH_RESULTS')
      .done ();
  });
});

dotest.add ('Method searchIndex - buffer', function (test) {
  fs.readFile (path.join (dir, 'imageSample.jpg'), function (errFile, file) {
    test (errFile);

    pastec.searchIndex (file, function (err, data) {
      test (err)
        .isObject ('fail', 'data', data)
        .isExactly ('warn', 'data.type', data && data.type, 'SEARCH_RESULTS')
        .done ();
    });
  });
});

dotest.add ('Method searchIndex - error', function (test) {
  pastec.searchIndex ('', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .info (err.message)
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Method deleteImage', function (test) {
  pastec.deleteImage (999999999999999, function (err, data) {
    test (err)
      .isObject ('fail', 'data', data)
      .isExactly ('warn', 'data.type', data && data.type, 'IMAGE_REMOVED')
      .done ();
  });
});

dotest.add ('Error: invalid authkey', function (test) {
  const tmp = app (endpoint, timeout);

  tmp.writeIndex ('./sampleIndex.dat', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'invalid authkey')
      .isExactly ('warn', 'err.error', err && err.error, 'AUTHENTIFICATION_ERROR')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

dotest.add ('Error: request failed', function (test) {
  const tmp = app (endpoint, authkey, 1);

  tmp.writeIndex ('./sampleIndex.dat', function (err, data) {
    test ()
      .isError ('fail', 'err', err)
      .isExactly ('fail', 'err.message', err && err.message, 'request failed')
      .isError ('fail', 'err.error', err && err.error)
      .isExactly ('fail', 'err.error.code', err && err.error && err.error.code, 'TIMEOUT')
      .isUndefined ('fail', 'data', data)
      .done ();
  });
});

// Start the tests
dotest.run ();
<|endoftext|>


<commit_before>var assert = require('assert');
var five = require('./');

assert.equal(5, five(), 'Five should give you five');
assert.notEqual(6, five(), 'Five should not give you not five');

assert.equal('The Law of Fives states simply that: All things happen in fives, or are divisible by or are multiples of five, or are somehow directly or indirectly appropriate to 5. The Law of Fives is never wrong.', five.law(), 'The Law of Fives should never be wrong');

assert.equal(five.convertTo(5), 5);
assert.equal(five.convertTo(3), 3);
assert.equal(five.convertTo(665456), 665456);

assert.equal('⁵', five.upHigh(), 'An up high five should be a superscripted 5');
assert.equal('₅', five.downLow(), 'A down low five should be a subscripted 5');
assert.equal('V', five.roman(), 'A roman five should be a V');

assert.equal('خمسة', five.arabic(), 'A arabic five should be خمسة');
assert.equal('beş', five.azerbaijani(), 'A azerbaijani five should be beş');
assert.equal('bost', five.basque(), 'A basque five should be bost');
assert.equal('пяць', five.belarusian(), 'A belarusian five should be пяць');
assert.equal('pet', five.bosnian(), 'A bosnian five should be pet');
assert.equal('пет', five.bulgarian(), 'A bulgarian five should be пет');
assert.equal('cinc', five.catalan(), 'A catalan five should be cinc');
assert.equal('五', five.chinese(), 'A chinese five should be 五');
assert.equal('wǔ', five.chinese('pinyin'), 'A chinese five in Pīnyīn should be wǔ');
assert.equal('伍', five.chinese('financial'), 'A chinese five in financial contexts should be 伍');
assert.equal('tahlapi', five.choctaw(), 'A choctaw five should be tahlapi');
assert.equal('pet', five.croatian(), 'A croatian five should be pet');
assert.equal('pět', five.czech(), 'A czech five should be pět');
assert.equal('mek', five.dothraki(), 'A dothraki five should be mek');
assert.equal('hen', five.dovah(), 'A dovah five should be hen');
assert.equal('vijf', five.dutch(), 'A dutch five should be vijf');
assert.equal('lempe', five.elvish(), 'A elvish five should be lempe');
assert.equal('five', five.english(), 'A english five should be five');
assert.equal('kvin', five.esperanto(), 'An esperanto five should be kvin');
assert.equal('viis', five.estonian(), 'An estonian five should be viis');
assert.equal('viisi', five.finnish(), 'A finnish five should be viisi');
assert.equal('cinq', five.french(), 'A french five should be cinq');
assert.equal('fünf', five.german(), 'A german five should be fünf');
assert.equal('πέντε', five.greek(), 'A greek five should be πέντε');
assert.equal('חמש', five.hebrew(), 'A hebrew five should be חמש');
assert.equal('पांच', five.hindi(), 'A hindi five should be पांच');
assert.equal('öt', five.hungarian(), 'A hungarian five should be öt');
assert.equal('fimm', five.icelandic(), 'An icelandic five should be fimm');
assert.equal('lima', five.indonesian(), 'A indonesian five should be lima');
assert.equal('cúig', five.irish(), 'A irish five should be cúig');
assert.equal('cinque', five.italian(), 'A italian five should be cinque');
assert.equal('五', five.japanese(), 'A japanese five should be 五');
assert.equal('ಐದು', five.kannada(), 'A kannada five should be ಐದು');
assert.equal('vagh', five.klingon(), 'A klingon five should be vagh');
assert.equal('오', five.korean(), 'A korean five should be 오');
assert.equal('quinque', five.latin(), 'A latin five should be quinque');
assert.equal('pieci', five.latvian(), 'A latvian five should be pieci');
assert.equal('penki', five.lithuanian(), 'A lithuanian five should be penki');
assert.equal('ħamsa', five.maltese(), ' A maltese five should be ħamsa');
assert.equal('таван', five.mongolian(), 'A mongolian five should be таван');
assert.equal('पाँच', five.nepali(), 'A nepali five should be पाँच');
assert.equal('fem', five.norwegian(), 'A norwegian five should be fem');
assert.equal('پنج', five.persian(), 'A persian five should be پنج');
assert.equal('ivefay', five.piglatin(), 'A piglatin five should be ivefay');
assert.equal('pięć', five.polish(), 'A polish five should be pięć');
assert.equal('cinco', five.portuguese(), 'A portuguese five should be cinco');
assert.equal('ਪੰਜ', five.punjabi(), 'A punjabi five should be ਪੰਜ');
assert.equal('cinci', five.romanian(), 'A romanian five should be cinci');
assert.equal('пять', five.russian(), 'A russian five should be пять');
assert.equal('pet', five.serbian(), 'A serbian five should be pet');
assert.equal('පහ', five.sinhala(), 'A sinhala five should be පහ');
assert.equal('päť', five.slovakian(), 'A slovakian five should be päť');
assert.equal('pet', five.slovenian(), 'A slovenian five should be pet');
assert.equal('cinco', five.spanish(), 'A spanish five should be cinco');
assert.equal('fem', five.swedish(), 'A swedish five should be fem');
assert.equal('ஐந்து', five.tamil(), 'A tamil five should be ஐந்து');
assert.equal('ఐదు', five.telugu(), 'A telugu five should be ఐదు');
assert.equal('ห้า', five.thai(), 'A thai five should be ห้า');
assert.equal('beş', five.turkish(), 'A turkish five should be beş');
assert.equal('п’ять', five.ukrainian(), 'A ukrainian five should be п’ять');

assert.equal('.....', five.morseCode(), 'A five in morse code should be .....');
assert.equal('10', five.base(5), 'A quinary five should be 10');
assert.equal('11', five.base(4), 'An quaternary five should be 11')
assert.equal('101', five.binary(), 'A binary five should be 101');
assert.equal('5', five.octal(), 'An octal five should be 5');
assert.equal('5', five.hex(), 'An hexadecimal five should be 5');

assert.equal('30056e1cab7a61d256fc8edd970d14f5', five.mdFive(), 'md5 checksum of "five" should be 30056e1cab7a61d256fc8edd970d14f5');
assert.equal('1.618033988749895', five.golden(), 'A golden five is Phive');

assert.equal('-5', five.negative(), 'A negative five should be -5');
assert.equal('FIVE', five.loud(), 'A loud five should be FIVE');
assert.equal('IVEFAY', five.loud('piglatin'), 'A loud five in Pig Latin should be IVEFAY');
assert.equal('ПЯТЬ', five.loud('russian'), 'A loud five in Russian should be ПЯТЬ');
assert.equal('S', five.smooth(), 'A smooth five should be S');

assert.equal('🕔', five.oclock(), 'A unicode symbol for five o\'clock should be U+1F554');
assert.equal('🍺', five.oclockSomewhere(), 'A unicode symbol for \'It\'s five o\'clock somewhere\' should be U+1F37A');
assert.equal('🍔', five.guys(), 'A unicode symbol for Five Guys should be U+1F354');

assert.equal('o/', five.high(), 'A High five should be o/');

var now = new Date().valueOf();
var slowFive = five.tooSlow();
var finishes = new Date().valueOf();

assert.equal(5, slowFive, 'A too slow five should still be five');
assert.ok((finishes - now) > 500, 'A too slow five should take longer than 500 milliseconds to be returned, blocking execution and generally being a bad idea');

assert.equal(JSON.stringify(['Jackie','Tito','Jermaine','Marlon','Michael']), JSON.stringify(five.jackson()), 'A Jackson five should be the five members of the 70\'s pop family group the Jackson 5');

assert.equal(JSON.stringify(['Juwan Howard','Ray Jackson','Jimmy King','Jalen Rose','Chris Webber']), JSON.stringify(five.fab()), 'A fab five should be the 1991-1993 Michigan Mens Basketball Team');

assert.equal(JSON.stringify(['Sean Conlon', 'Ritchie Neville', 'Scott Robinson', 'Jason \'J\' Brown', 'Abz Love']), JSON.stringify(five.members()), 'A five five should be the 90\'s boy band 5ive');

assert.equal(JSON.stringify(['5ive', 'Invincible', 'Kingsize']), JSON.stringify(five.discography()), 'A five discography should be the studio albums released by the 90\'s boy band 5ive');

assert.equal(JSON.stringify(['Slam Dunk (Da Funk)', 'When the Lights Go Out', 'Got the Feelin\'', 'Everybody Get Up', 'It\'s the Things You Do', 'Until the Time Is Through', 'If Ya Gettin\' Down', 'Keep On Movin\'', 'Don\'t Wanna Let You Go', 'We Will Rock You', 'Let\'s Dance', 'Closer to Me', 'Rock the Party', 'I Wish It Could Be Christmas Everyday']), JSON.stringify(five.singles()), 'A five singles should be the singles released by the 90\'s boy band 5ive');

assert.equal(JSON.stringify(['Tigress','Viper','Crane','Monkey','Mantis']), JSON.stringify(five.furious()), 'A Furious five should be the five fictional members of the ninja group Furious Five from the movie Kung-Fu Panda');

assert.equal(five.luniz(), 'I Got 5 on It', 'A Luniz five should be the song title of their most famous hit');

assert.equal(five.funk(), '5 bad boys with the power to rock you', 'A funked five should be a group of bad boys with the power to rock you');

assert.equal(true, five.isFive(five()));
assert.equal(false, five.isFive(10));

assert.equal(JSON.stringify([5, 5]), JSON.stringify(five.filter([5, true, 5])));
assert.equal(JSON.stringify([5, 5, 5]), JSON.stringify(five.map([1, 2, 3])));
assert.equal(5, five.reduce([1, 2, 3]));

assert.equal('£5', five.r(), 'A fiver should be 5 GBP');

assert.equal('5678901234', five.rot('0123456789'), 'Numbers should be rotated');
assert.equal('fghijklmnopqrstuvwxyzabcde', five.rot('abcdefghijklmnopqrstuvwxyz'), 'Small letters should be rotated');
assert.equal('FGHIJKLMNOPQRSTUVWXYZABCDE', five.rot('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 'Capital letters too');
assert.equal('$_$ -,- @.@?', five.rot('$_$ -,- @.@?'), 'Emoticons should not be rotated');

assert.equal(five * five, 25);
assert.equal(five + five, 10);
assert.equal(five / five, 1);
assert.equal(five - five, 0);
assert.equal((five / five) * (five), five);

var fiveEmitter = five.emitter();
var emitterTested = false;

fiveEmitter.on('five', function(e) {
  assert.equal(5, e, 'Five event emitter should only emit 5');
  emitterTested = true;
});

setTimeout(function() {
  if(!emitterTested) {
    console.error('The five event emitter did something unexpected! I hope you\'re not using this feature in production');
    process.exit(1);
  }
  process.exit(0);
}, 100);

var asyncTests = 1;
five.async(function(err, five) {
	assert.equal(err, null, 'Async should not result in an error.');
	assert.equal(five, 5, 'Async should pass 5 to callback.');
	asyncTests--;
});

setInterval(function() {
	if (!asyncTests) {
		process.exit(0);
	}
}, 100);
<commit_msg>Five Bucks Test<commit_after>var assert = require('assert');
var five = require('./');

assert.equal(5, five(), 'Five should give you five');
assert.notEqual(6, five(), 'Five should not give you not five');

assert.equal('The Law of Fives states simply that: All things happen in fives, or are divisible by or are multiples of five, or are somehow directly or indirectly appropriate to 5. The Law of Fives is never wrong.', five.law(), 'The Law of Fives should never be wrong');

assert.equal(five.convertTo(5), 5);
assert.equal(five.convertTo(3), 3);
assert.equal(five.convertTo(665456), 665456);

assert.equal('⁵', five.upHigh(), 'An up high five should be a superscripted 5');
assert.equal('₅', five.downLow(), 'A down low five should be a subscripted 5');
assert.equal('V', five.roman(), 'A roman five should be a V');

assert.equal('خمسة', five.arabic(), 'A arabic five should be خمسة');
assert.equal('beş', five.azerbaijani(), 'A azerbaijani five should be beş');
assert.equal('bost', five.basque(), 'A basque five should be bost');
assert.equal('пяць', five.belarusian(), 'A belarusian five should be пяць');
assert.equal('pet', five.bosnian(), 'A bosnian five should be pet');
assert.equal('пет', five.bulgarian(), 'A bulgarian five should be пет');
assert.equal('cinc', five.catalan(), 'A catalan five should be cinc');
assert.equal('五', five.chinese(), 'A chinese five should be 五');
assert.equal('wǔ', five.chinese('pinyin'), 'A chinese five in Pīnyīn should be wǔ');
assert.equal('伍', five.chinese('financial'), 'A chinese five in financial contexts should be 伍');
assert.equal('tahlapi', five.choctaw(), 'A choctaw five should be tahlapi');
assert.equal('pet', five.croatian(), 'A croatian five should be pet');
assert.equal('pět', five.czech(), 'A czech five should be pět');
assert.equal('mek', five.dothraki(), 'A dothraki five should be mek');
assert.equal('hen', five.dovah(), 'A dovah five should be hen');
assert.equal('vijf', five.dutch(), 'A dutch five should be vijf');
assert.equal('lempe', five.elvish(), 'A elvish five should be lempe');
assert.equal('five', five.english(), 'A english five should be five');
assert.equal('kvin', five.esperanto(), 'An esperanto five should be kvin');
assert.equal('viis', five.estonian(), 'An estonian five should be viis');
assert.equal('viisi', five.finnish(), 'A finnish five should be viisi');
assert.equal('cinq', five.french(), 'A french five should be cinq');
assert.equal('fünf', five.german(), 'A german five should be fünf');
assert.equal('πέντε', five.greek(), 'A greek five should be πέντε');
assert.equal('חמש', five.hebrew(), 'A hebrew five should be חמש');
assert.equal('पांच', five.hindi(), 'A hindi five should be पांच');
assert.equal('öt', five.hungarian(), 'A hungarian five should be öt');
assert.equal('fimm', five.icelandic(), 'An icelandic five should be fimm');
assert.equal('lima', five.indonesian(), 'A indonesian five should be lima');
assert.equal('cúig', five.irish(), 'A irish five should be cúig');
assert.equal('cinque', five.italian(), 'A italian five should be cinque');
assert.equal('五', five.japanese(), 'A japanese five should be 五');
assert.equal('ಐದು', five.kannada(), 'A kannada five should be ಐದು');
assert.equal('vagh', five.klingon(), 'A klingon five should be vagh');
assert.equal('오', five.korean(), 'A korean five should be 오');
assert.equal('quinque', five.latin(), 'A latin five should be quinque');
assert.equal('pieci', five.latvian(), 'A latvian five should be pieci');
assert.equal('penki', five.lithuanian(), 'A lithuanian five should be penki');
assert.equal('ħamsa', five.maltese(), ' A maltese five should be ħamsa');
assert.equal('таван', five.mongolian(), 'A mongolian five should be таван');
assert.equal('पाँच', five.nepali(), 'A nepali five should be पाँच');
assert.equal('fem', five.norwegian(), 'A norwegian five should be fem');
assert.equal('پنج', five.persian(), 'A persian five should be پنج');
assert.equal('ivefay', five.piglatin(), 'A piglatin five should be ivefay');
assert.equal('pięć', five.polish(), 'A polish five should be pięć');
assert.equal('cinco', five.portuguese(), 'A portuguese five should be cinco');
assert.equal('ਪੰਜ', five.punjabi(), 'A punjabi five should be ਪੰਜ');
assert.equal('cinci', five.romanian(), 'A romanian five should be cinci');
assert.equal('пять', five.russian(), 'A russian five should be пять');
assert.equal('pet', five.serbian(), 'A serbian five should be pet');
assert.equal('පහ', five.sinhala(), 'A sinhala five should be පහ');
assert.equal('päť', five.slovakian(), 'A slovakian five should be päť');
assert.equal('pet', five.slovenian(), 'A slovenian five should be pet');
assert.equal('cinco', five.spanish(), 'A spanish five should be cinco');
assert.equal('fem', five.swedish(), 'A swedish five should be fem');
assert.equal('ஐந்து', five.tamil(), 'A tamil five should be ஐந்து');
assert.equal('ఐదు', five.telugu(), 'A telugu five should be ఐదు');
assert.equal('ห้า', five.thai(), 'A thai five should be ห้า');
assert.equal('beş', five.turkish(), 'A turkish five should be beş');
assert.equal('п’ять', five.ukrainian(), 'A ukrainian five should be п’ять');

assert.equal('.....', five.morseCode(), 'A five in morse code should be .....');
assert.equal('10', five.base(5), 'A quinary five should be 10');
assert.equal('11', five.base(4), 'An quaternary five should be 11')
assert.equal('101', five.binary(), 'A binary five should be 101');
assert.equal('5', five.octal(), 'An octal five should be 5');
assert.equal('5', five.hex(), 'An hexadecimal five should be 5');

assert.equal('30056e1cab7a61d256fc8edd970d14f5', five.mdFive(), 'md5 checksum of "five" should be 30056e1cab7a61d256fc8edd970d14f5');
assert.equal('1.618033988749895', five.golden(), 'A golden five is Phive');

assert.equal('-5', five.negative(), 'A negative five should be -5');
assert.equal('FIVE', five.loud(), 'A loud five should be FIVE');
assert.equal('IVEFAY', five.loud('piglatin'), 'A loud five in Pig Latin should be IVEFAY');
assert.equal('ПЯТЬ', five.loud('russian'), 'A loud five in Russian should be ПЯТЬ');
assert.equal('S', five.smooth(), 'A smooth five should be S');

assert.equal('🕔', five.oclock(), 'A unicode symbol for five o\'clock should be U+1F554');
assert.equal('🍺', five.oclockSomewhere(), 'A unicode symbol for \'It\'s five o\'clock somewhere\' should be U+1F37A');
assert.equal('🍔', five.guys(), 'A unicode symbol for Five Guys should be U+1F354');
assert.equal('$5.00', five.bucks(), 'Five bucks in USD should be $5.00');

assert.equal('o/', five.high(), 'A High five should be o/');

var now = new Date().valueOf();
var slowFive = five.tooSlow();
var finishes = new Date().valueOf();

assert.equal(5, slowFive, 'A too slow five should still be five');
assert.ok((finishes - now) > 500, 'A too slow five should take longer than 500 milliseconds to be returned, blocking execution and generally being a bad idea');

assert.equal(JSON.stringify(['Jackie','Tito','Jermaine','Marlon','Michael']), JSON.stringify(five.jackson()), 'A Jackson five should be the five members of the 70\'s pop family group the Jackson 5');

assert.equal(JSON.stringify(['Juwan Howard','Ray Jackson','Jimmy King','Jalen Rose','Chris Webber']), JSON.stringify(five.fab()), 'A fab five should be the 1991-1993 Michigan Mens Basketball Team');

assert.equal(JSON.stringify(['Sean Conlon', 'Ritchie Neville', 'Scott Robinson', 'Jason \'J\' Brown', 'Abz Love']), JSON.stringify(five.members()), 'A five five should be the 90\'s boy band 5ive');

assert.equal(JSON.stringify(['5ive', 'Invincible', 'Kingsize']), JSON.stringify(five.discography()), 'A five discography should be the studio albums released by the 90\'s boy band 5ive');

assert.equal(JSON.stringify(['Slam Dunk (Da Funk)', 'When the Lights Go Out', 'Got the Feelin\'', 'Everybody Get Up', 'It\'s the Things You Do', 'Until the Time Is Through', 'If Ya Gettin\' Down', 'Keep On Movin\'', 'Don\'t Wanna Let You Go', 'We Will Rock You', 'Let\'s Dance', 'Closer to Me', 'Rock the Party', 'I Wish It Could Be Christmas Everyday']), JSON.stringify(five.singles()), 'A five singles should be the singles released by the 90\'s boy band 5ive');

assert.equal(JSON.stringify(['Tigress','Viper','Crane','Monkey','Mantis']), JSON.stringify(five.furious()), 'A Furious five should be the five fictional members of the ninja group Furious Five from the movie Kung-Fu Panda');

assert.equal(five.luniz(), 'I Got 5 on It', 'A Luniz five should be the song title of their most famous hit');

assert.equal(five.funk(), '5 bad boys with the power to rock you', 'A funked five should be a group of bad boys with the power to rock you');

assert.equal(true, five.isFive(five()));
assert.equal(false, five.isFive(10));

assert.equal(JSON.stringify([5, 5]), JSON.stringify(five.filter([5, true, 5])));
assert.equal(JSON.stringify([5, 5, 5]), JSON.stringify(five.map([1, 2, 3])));
assert.equal(5, five.reduce([1, 2, 3]));

assert.equal('£5', five.r(), 'A fiver should be 5 GBP');

assert.equal('5678901234', five.rot('0123456789'), 'Numbers should be rotated');
assert.equal('fghijklmnopqrstuvwxyzabcde', five.rot('abcdefghijklmnopqrstuvwxyz'), 'Small letters should be rotated');
assert.equal('FGHIJKLMNOPQRSTUVWXYZABCDE', five.rot('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 'Capital letters too');
assert.equal('$_$ -,- @.@?', five.rot('$_$ -,- @.@?'), 'Emoticons should not be rotated');

assert.equal(five * five, 25);
assert.equal(five + five, 10);
assert.equal(five / five, 1);
assert.equal(five - five, 0);
assert.equal((five / five) * (five), five);

var fiveEmitter = five.emitter();
var emitterTested = false;

fiveEmitter.on('five', function(e) {
  assert.equal(5, e, 'Five event emitter should only emit 5');
  emitterTested = true;
});

setTimeout(function() {
  if(!emitterTested) {
    console.error('The five event emitter did something unexpected! I hope you\'re not using this feature in production');
    process.exit(1);
  }
  process.exit(0);
}, 100);

var asyncTests = 1;
five.async(function(err, five) {
	assert.equal(err, null, 'Async should not result in an error.');
	assert.equal(five, 5, 'Async should pass 5 to callback.');
	asyncTests--;
});

setInterval(function() {
	if (!asyncTests) {
		process.exit(0);
	}
}, 100);
<|endoftext|>