Fix misc problems detected by ESLint

Reformat and clean up issues detected by ESLint.
This commit is contained in:
Hornwitser committed 2020-06-17 20:59:37 +02:00
1 parent 8cb21c5fa8
commit e9f5cae4f0
34 files changed
+132 -189

No files matched your search

+1 -1
View File
@@ -69,7 +69,7 @@ class Command {
}
async run(args, control) {
await this._handler.call(this, args, control);
await this._handler(args, control);
}
}
+9 -11
View File
@@ -395,7 +395,7 @@ class ConfigGroup {
value = Number.parseFloat(value);
}
} else if (def.type === "object" ) {
} else if (def.type === "object") {
try {
value = JSON.parse(value);
} catch (err) {
@@ -409,10 +409,8 @@ class ConfigGroup {
throw new InvalidValue(`Field ${name} cannot be null`);
}
} else {
if (basicType(value) !== def.type) {
throw new InvalidValue(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`);
}
} else if (basicType(value) !== def.type) {
throw new InvalidValue(`Expected type of ${name} to be ${def.type}, not ${basicType(value)}`);
}
let prev = this._fields.get(name);
@@ -493,10 +491,9 @@ class ConfigGroup {
if (value !== null && basicType(value) !== def.type) {
continue;
}
} else {
if (basicType(value) !== def.type) {
continue;
}
} else if (basicType(value) !== def.type) {
continue;
}
if (def.enum && !def.enum.includes(value)) {
@@ -655,10 +652,11 @@ class ConfigGroup {
throw new Error(`Config field ${item.name} has already been defined`);
}
let computed = Object.assign({
let computed = {
optional: false,
fullName: `${this.groupName}.${item.name}`,
}, item);
...item,
};
if (!computed.optional && computed.initial_value === undefined) {
throw new Error(`Non-optional field ${item.name} needs an initial_value`);
-1
View File
@@ -144,7 +144,6 @@ async function saveMapAsJsonArray(filePath, map) {
}
function checkName(name) {
if (typeof name !== "string") {
throw new Error("name must be a string");
+1
View File
@@ -196,6 +196,7 @@ async function exportItems(server, modVersions, items) {
iconLayer.scale(realScale);
}
// eslint-disable-next-line no-loop-func
iconLayer.scan(0, 0, iconLayer.bitmap.width, iconLayer.bitmap.height, function(x, y, sidx) {
x += xs;
y += ys;
+7 -9
View File
@@ -167,9 +167,9 @@ function randomDynamicPort() {
async function generatePassword(length) {
function validChar(byte) {
const ranges = ["az", "AZ", "09"];
return ranges.some(range =>
return ranges.some(range => (
range.codePointAt(0) <= byte && byte <= range.codePointAt(1)
);
));
}
let randomBytesAsync = util.promisify(crypto.randomBytes);
@@ -559,9 +559,9 @@ class FactorioServer extends events.EventEmitter {
let channel = line
.slice(6, channelEnd)
.toString("utf-8")
.replace(/\\x([0-9a-f]{2})/g, (match, p1) =>
.replace(/\\x([0-9a-f]{2})/g, (match, p1) => (
String.fromCharCode(parseInt(p1, 16))
)
))
;
let type = line.slice(channelEnd + 1, channelEnd + 2).toString("utf-8");
@@ -619,10 +619,8 @@ class FactorioServer extends events.EventEmitter {
if (!expected.includes(output[name])) {
continue heuristicLoop;
}
} else {
if (expected !== output[name]) {
continue heuristicLoop;
}
} else if (expected !== output[name]) {
continue heuristicLoop;
}
}
@@ -651,7 +649,7 @@ class FactorioServer extends events.EventEmitter {
};
this._rconClient = new rconClient.Rcon(config);
this._rconClient.on("error", err => { /* Ignore */ });
this._rconClient.on("error", () => { /* Ignore */ });
this._rconClient.on("authenticated", () => { this._rconReady = true; this.emit("rcon-ready"); });
this._rconClient.on("end", () => {
this._rconClient = null;
+1 -1
View File
@@ -1,3 +1,3 @@
"use strict";
const fileOps = require("./fileOps");
module.exports = fileOps;
module.exports = fileOps;
-12
View File
@@ -310,18 +310,6 @@ class WebSocketClientConnector extends WebSocketBaseConnector {
console.error("SOCKET | Error:", err);
});
/*
this._socket.on("unexpected-response", (req, res) => {
let data = "";
res.on('data', (chunk) => { data += chunk; });
res.on('end', () => {
console.error(`SOCKET | Unexpeced Response ${res.statusCode}`);
console.error(data);
this._socket.emit("error", new Error(`Unexpected Response ${res.statusCode}`));
});
});
*/
this._socket.on("open", () => {
console.log("SOCKET | Open");
});
+10 -8
View File
@@ -11,8 +11,8 @@ const errors = require("lib/errors");
class Message {
/**
* Name of the plugin this message belongs to, or null.
* @returns {?string}
**/
* @returns {?string} - plugin name or null if not from a plugin.
*/
get plugin() {
if (this._plugin === undefined) {
let index = this.type.indexOf(":");
@@ -78,9 +78,10 @@ class Request extends Message {
}
if (forwardTo === "instance") {
requestProperties = Object.assign(
{ "instance_id": { type: "integer" }}, requestProperties
);
requestProperties = {
"instance_id": { type: "integer" },
...requestProperties,
};
} else if (forwardTo !== "master" && forwardTo !== null) {
throw new Error(`Invalid forwardTo value ${forwardTo}`);
@@ -635,9 +636,10 @@ class Event extends Message {
this.broadcastTo = broadcastTo;
if (forwardTo === "instance") {
eventProperties = Object.assign(
{ "instance_id": { type: "integer" }}, eventProperties
);
eventProperties = {
"instance_id": { type: "integer" },
...eventProperties,
};
} else if (forwardTo !== "master" && forwardTo !== null) {
throw new Error(`Invalid forwardTo value ${forwardTo}`);
+2
View File
@@ -1,3 +1,5 @@
// This file will be rewritten from scratch
/* eslint-disable */
/**
Provides tools to manage mods in a clusterio install
@module
+3 -3
View File
@@ -26,7 +26,7 @@ function download(url, file, callback){
// this might be an invalid path!
fs.stat(pathArray.join("/"), (err, stat) => {
if(err){
makeDirectory(pathArray.join("/")).then(()=>{
makeDirectory(pathArray.join("/")).then(() => {
doDownload(url, file, callback);
});
} else {
@@ -82,7 +82,7 @@ let downloadList = [
// initiate folder creations and downloads
function processMkdirRecursive(callback){
let item = directories.shift();
makeDirectory(item).then(()=>{
makeDirectory(item).then(() => {
if(directories.length == 0){
if(callback) callback();
} else {
@@ -92,7 +92,7 @@ function processMkdirRecursive(callback){
}
function processDownloadRecursive(callback){
let item = downloadList.shift();
download(item.url, item.file, item.callback).then(()=>{
download(item.url, item.file, item.callback).then(() => {
if(downloadList.length == 0){
if(callback) callback();
} else {
+25 -24
View File
@@ -1,35 +1,36 @@
/**
Helper functions related to objects
@module
*/
* Helper functions related to objects
* @module
*/
"use strict";
/**
Deep clones an object, is actually just JSON.parse(JSON.stringify()) but looks cleaner.
@param {object} obj to clone
@returns {object} The cloned object.
@example
a = {"thingy":"with a value"};
b = a;
a == b; // true
c = objectOps.deepclone(a);
a == c; // false
*/
* Deep clones an object, is actually just JSON.parse(JSON.stringify()) but looks cleaner.
* @param {object} obj to clone
* @returns {object} The cloned object.
*
* @example
* a = {"thingy":"with a value"};
* b = a;
* a == b; // true
* c = objectOps.deepclone(a);
* a == c; // false
*/
module.exports.deepclone = function(obj){
return JSON.parse(JSON.stringify(obj));
};
/**
Checks if a string is valid JSON using try/catch. If passed an object it will always return true.
@param {string} string to verify
@returns {boolean} true if valid JSON.
@example
objectOps.isJSON("99 bottles of beer"); // false
objectOps.isJSON("99"); // true
objectOps.isJSON({"thingy":"that is an object"}); // true
objectOps.isJSON(JSON.stringify({"thingy":"that is an object"})); // true
*/
/**
* Checks if a string is valid JSON using try/catch. If passed an object it will always return true.
* @param {string} string to verify
* @returns {boolean} true if valid JSON.
*
* @example
* objectOps.isJSON("99 bottles of beer"); // false
* objectOps.isJSON("99"); // true
* objectOps.isJSON({"thingy":"that is an object"}); // true
* objectOps.isJSON(JSON.stringify({"thingy":"that is an object"})); // true
*/
module.exports.isJSON = function(string){
let stringIsJson = false;
let x;
+3 -3
View File
@@ -167,9 +167,9 @@ class ValueCollector extends Collector {
function removeMatchingLabels(mapping, labels) {
for (let key of mapping.keys()) {
let candidate = keyToLabels(key);
let hasLabels = Object.entries(labels).every(([name, value]) => {
return candidate.get(name) === value;
});
let hasLabels = Object.entries(labels).every(([name, value]) => (
candidate.get(name) === value
));
if (hasLabels) {
mapping.delete(key);
}
+2 -2
View File
@@ -74,7 +74,7 @@ const serverHandshake = ajv.compile({
$schema: "http://json-schema.org/draft-07/schema#",
title: "Server Handshake",
description: "Message sent from the server to a client during the handshake",
allOf: [ messageSchema ],
allOf: [messageSchema],
anyOf: [
{
properties: {
@@ -137,7 +137,7 @@ const clientHandshake = ajv.compile({
$schema: "http://json-schema.org/draft-07/schema#",
title: "Client Message",
description: "Message sent from a client to the server",
allOf: [ messageSchema ],
allOf: [messageSchema],
anyOf: [
{
properties: {
+4 -3
View File
@@ -535,7 +535,7 @@ class BaseConnection extends link.Link {
}
}
let controlConnections = new Array();
let controlConnections = [];
class ControlConnection extends BaseConnection {
constructor(registerData, connector, user) {
super("control", connector);
@@ -560,7 +560,7 @@ class ControlConnection extends BaseConnection {
this.ws_dumper = null;
this.connector.on("connect", () => {
this.connector._socket.clusterio_ignore_dump = !!this.ws_dumper;
this.connector._socket.clusterio_ignore_dump = Boolean(this.ws_dumper);
});
this.connector.on("close", () => {
if (this.ws_dumper) {
@@ -880,6 +880,7 @@ class SlaveConnection extends BaseConnection {
});
for (let event of ["connect", "drop", "close"]) {
// eslint-disable-next-line no-loop-func
this.connector.on(event, () => {
for (let masterPlugin of masterPlugins.values()) {
masterPlugin.onSlaveConnectionEvent(this, event);
@@ -991,7 +992,7 @@ const wss = new WebSocket.Server({
* 2<sup>31</sup>-1.
*/
function isInteger(value) {
return value | 0 === value;
return (value | 0) === value;
}
+2 -2
View File
@@ -112,7 +112,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
}
for (let instanceTech of message.data.technologies) {
let [name, level, progress, researched] = instanceTech;
let [name, level, progress, researched] = instanceTech;
let tech = this.technologies.get(name);
if (!tech) {
this.technologies.set(name, { level, progress, researched });
@@ -152,7 +152,7 @@ class MasterPlugin extends plugin.BaseMasterPlugin {
let technologies = [];
for (let [name, tech] of this.technologies) {
technologies.push([ name, tech.level, tech.progress, tech.researched ]);
technologies.push([name, tech.level, tech.progress, tech.researched]);
}
return { technologies };
+7 -5
View File
@@ -16,7 +16,7 @@ const prometheusDoleFactorGauge = new prometheus.Gauge(
);
class neuralDole {
getRequestStats(itemname,samples)
{
var sum=0;
@@ -28,7 +28,7 @@ class neuralDole {
if (sum==0) return 0.1;
return sum/samples;
}
constructor({
items,
}){
@@ -41,6 +41,7 @@ class neuralDole {
this.stats=[];
this.debt= {};
}
doMagic() {
for (let [name, count] of this.items._items) {
let magicData = doleNN.Tick(
@@ -50,7 +51,7 @@ class neuralDole {
this.getRequestStats(name,5)
);
this.stats[name]=this.stats[name] || [];
this.stats[name].unshift({ req:0,given:0 });//stats[name][0] is the one we currently collect
this.stats[name].unshift({ req: 0, given: 0 });//stats[name][0] is the one we currently collect
if (this.stats[name].length>10) this.stats[name].pop();//remove if too many samples in stats
this.dole[name] = magicData[0];
@@ -59,6 +60,7 @@ class neuralDole {
}
this.itemsLastTick = new Map(this.items._items);
}
divider(object) {
let magicData = doleNN.Dose(
object.count, // numReq
@@ -100,7 +102,7 @@ function doleDivider({
let itemCount = items.getItemCount(object.name);
const doleDivisionRetardation = 10; //lower rates will equal more dramatic swings
const maxDoleDivision = 250; //a higher cap will divide the store more ways, but will take longer to recover as supplies increase
const originalCount = Number(object.count) || 0;
object.count /= ((_doleDivisionFactor[object.name]||0)+doleDivisionRetardation)/doleDivisionRetardation;
object.count = Math.round(object.count);
@@ -128,4 +130,4 @@ function doleDivider({
module.exports = {
doleDivider,
neuralDole,
};
};
+10 -10
View File
@@ -47,7 +47,7 @@ function Dose(numreq,instore,store_last_tick,dole,carry,prev_req,numreq_total_ad
instore=Number(instore);
var instore_adj=instore;
if (instore_adj==0) instore_adj=0.1;
var b=Math.trunc(prev_req/instore_adj*numreq);
var inp1=[numreq,instore_adj,store_last_tick/numreq,dole,carry];//0..4
var inp2=[prev_req/numreq,numreq/numreq_total_adj,store_last_tick/numreq_total_adj,prev_req/instore_adj,b,numreq_total_adj,store_last_tick,debt];//5..12
@@ -55,7 +55,7 @@ function Dose(numreq,instore,store_last_tick,dole,carry,prev_req,numreq_total_ad
var internal=new Array(20).fill(0);
var outputs=[0,0,0,0];
//NN: Please don't touch :), code is generated
outputs[0]=inputs[7]*0.8058582544;
outputs[0]=sigmoid2(outputs[0]);
outputs[1]=sigmoid0(outputs[1]);
@@ -65,20 +65,20 @@ function Dose(numreq,instore,store_last_tick,dole,carry,prev_req,numreq_total_ad
debt=debt || 0;
if (outputs[0]>0.99) outputs[0]=1.0;
var res1=Number(outputs[0])*numreq+outputs[3]+debt;
var res_capped=Math.round(res1);
if (res_capped>numreq) res_capped=numreq;
if (res_capped>instore) res_capped=instore;
if (res_capped<0) res_capped=0;
res1=res1 || 0;
res_capped=res_capped || 0;//Safeguard against wrong values
debt=res1-res_capped;
debt_cap=Math.round(numreq*1.5)+5;
if (debt>debt_cap) debt=debt_cap;
carry=sigmoid0(outputs[2]*carry+outputs[0]) || 0;
return [res_capped,dole+outputs[1],carry,debt];
}
@@ -102,9 +102,9 @@ function Tick(instore,dole,store_last_tick,numreq_total_adj)
var internal=new Array(10).fill(0);
var outputs=[0,0];
//NN: Please don't touch :), code is generated
outputs[0]=inputs[3]*0.9364774823;
outputs[0]=outputs[0]*1.0*0.4590721726;
outputs[0]=outputs[0]*0.4590721726;
outputs[0]=sigmoid2(outputs[0]);
outputs[1]=outputs[0]*1.828422785;
outputs[1]=sigmoid3(outputs[1]);
@@ -113,8 +113,8 @@ function Tick(instore,dole,store_last_tick,numreq_total_adj)
if (numreq_total_adj<0.11) avg=1;//When no item's are requested, result is 0.1 ; In that case there is no deficit, so return 1 = 100% demand fulfilled
if (avg>1) avg=1;
if (avg<0) avg=0;
return [sigmoid0(outputs[0]),avg];
}
module.exports = { Dose,Tick };
module.exports = { Dose,Tick };
+8 -8
View File
@@ -13,24 +13,24 @@ function drawcontents(data) {
data = data.filter(function(item) {
return search.test(item.name);
});
sortByKey(data, "count");
const table = document.querySelector("#contents tbody"); //tables have tbody inserted automatically
const rows = table.children;
//update existing rows or create new ones
data.forEach(function(item, i) {
// format count to have .s in it for large number readability (1,000,000)
item.count = item.count.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
let row = rows[i];
if(!row) {
row = document.createElement("tr");
row.innerHTML = "<td><div></div></td><td class=name></td><td class=count></td>";
table.appendChild(row);
}
const itemIcon = row.querySelector("div");
const iconClass = getItemIconClass(item.name);
if (itemIcon.getAttribute("class") !== iconClass) {
@@ -56,13 +56,13 @@ function drawcontents(data) {
if(name.textContent !== localeName) {
name.textContent = localeName;
}
const count = row.querySelector(".count");
if(count.textContent !== ""+item.count) {
if(count.textContent !== String(item.count)) {
count.textContent = item.count;
}
});
//remove excess rows, for example, after filtering
while (data.length < rows.length) {
table.removeChild(rows[data.length]);
+1 -1
View File
@@ -12,4 +12,4 @@ module.exports = function(app) {
app.get("/nodeDetails", function(req, res) {
res.render("nodeDetails");
});
};
};
+12 -42
View File
@@ -23,7 +23,6 @@ const version = require("./package").version;
// internal libraries
const fileOps = require("lib/fileOps");
const hashFile = require("lib/hash").hashFile;
const factorio = require("lib/factorio");
const link = require("lib/link");
const plugin = require("lib/plugin");
@@ -88,7 +87,7 @@ const serverSettingsActions = {
"game_password": applyAsConfig("password"),
"require_user_verification": applyAsConfig("require-user-verification"),
"tags": applyAsConfig("tags"),
"visibility": async function action(server, value) {
"visibility": async (server, value) => {
for (let scope of ["lan", "public", "steam"]) {
try {
let enabled = Boolean(value[scope]);
@@ -352,13 +351,14 @@ class Instance extends link.Link{
throw new Error(`Expected name of module for plugin ${pluginName} to match the plugin name`);
}
module = Object.assign({
module = {
version: plugin.info.version,
dependencies: { "clusterio": "*" },
path: modulePath,
load: [],
require: [],
}, module);
...module,
};
modules.set(module.name, module);
}
@@ -380,12 +380,13 @@ class Instance extends link.Link{
throw new Error(`Expected name of module ${entry.name} to match the directory name`);
}
module = Object.assign({
module = {
path: path.join("modules", entry.name),
dependencies: { "clusterio": "*" },
load: [],
require: [],
}, module);
...module,
};
modules.set(module.name, module);
}
}
@@ -754,7 +755,7 @@ class Slave extends link.Link {
console.error(err);
process.exit(1);
});
});;
});
});
this.connector.on("close", () => {
@@ -874,10 +875,10 @@ class Slave extends link.Link {
// save a copy of the instance config
let warnedOutput = Object.assign(
{ _warning: "Changes to this file will be overwritten by the master server's copy." },
instanceInfo.config.serialize()
);
let warnedOutput = {
_warning: "Changes to this file will be overwritten by the master server's copy.",
...instanceInfo.config.serialize(),
};
await fs.outputFile(
path.join(instanceInfo.path, "instance.json"),
JSON.stringify(warnedOutput, null, 4)
@@ -1237,37 +1238,6 @@ async function startSlave() {
});
await slaveConnector.connect();
/*
} else if (command == "manage"){
await manage(config, instance);
// process.exit(0);
*/
}
// string, function
// returns [{modName:string,hash:string}, ... ]
function hashMods(instance, callback) {
if(!callback) {
throw new Error("ERROR in function hashMods NO CALLBACK");
}
function hashMod(name) {
if (path.extname(name) != ".zip") {
// Can't hash unzipped mods, return null that's filtered out later
return null;
} else {
return hashFile(instance.path("mods", name)).then(hash => (
{ modName: name, hash: hash }
));
}
}
let promises = fs.readdirSync(instance.path("mods")).map(hashMod);
Promise.all(promises).then(hashes => {
// Remove null entries from hashMod
callback(hashes.filter(entry => entry !== null));
});
}
module.exports = {
+1 -1
View File
@@ -156,7 +156,7 @@ describe("Integration of Clusterio", function() {
],
];
for (let [prop, value, , ] of testConfigs) {
for (let [prop, value, ,] of testConfigs) {
value = `"'${JSON.stringify(value).replace(/"/g, process.platform === "win32" ? '""' : '\\"')}'"`;
let args = `--instance test --field factorio.settings --prop ${prop} --value ${value}`;
await exec(`node clusterctl --config ${controlConfigPath} set-instance-config-prop ${args}`);
+2
View File
@@ -23,6 +23,7 @@ class TestControl extends link.Link {
}
async debugWsMessageEventHandler() { }
async instanceOutputEventHandler() { }
}
@@ -35,6 +36,7 @@ class TestControlConnector extends link.WebSocketClientConnector {
// Mark that this test takes a lot of time, or depeneds on a test
// that takes a lot of time.
function slowTest(test) {
// eslint-disable-next-line no-process-env
if (process.env.FAST_TEST) {
test.skip();
}
+1 -1
View File
@@ -27,7 +27,7 @@ describe("Integration of lib/factorio/server", function() {
before(async function() {
// Delete result from previous run of these tests
if (fs.existsSync(writePath)) {
if (await fs.pathExists(writePath)) {
await fs.remove(writePath);
}
+5 -4
View File
@@ -287,7 +287,7 @@ describe("lib/config/classes", function() {
});
it("should work if field is in enum", function() {
testInstance.set("enum", "c"),
testInstance.set("enum", "c");
assert.equal(testInstance.get("enum"), "c");
});
@@ -299,7 +299,7 @@ describe("lib/config/classes", function() {
});
it("should work if field is optional", function() {
testInstance.set("test", "spam"),
testInstance.set("test", "spam");
assert.equal(testInstance.get("test"), "spam");
});
@@ -311,7 +311,7 @@ describe("lib/config/classes", function() {
});
it("should treat empty string as null", function() {
testInstance.set("test", ""),
testInstance.set("test", "");
assert.equal(testInstance.get("test"), null);
});
@@ -451,7 +451,8 @@ describe("lib/config/classes", function() {
});
it("should construct a finalized class", function() {
TestConfig.finalize();
new TestConfig();
let config = new TestConfig();
assert(config);
});
});
+1 -1
View File
@@ -13,7 +13,7 @@ describe("lib/database", function() {
new Error("Expected all keys to be string but got number")
);
assert.throws(
() => database.mapToObject(new Map([[Symbol(), 1]])),
() => database.mapToObject(new Map([[Symbol("test"), 1]])),
new Error("Expected all keys to be string but got symbol")
);
});
+1 -1
View File
@@ -18,5 +18,5 @@ describe("lib/factorio/export", function() {
let locale = await factorio._exportLocale(testServer, new Map(), ["base"], "en");
assert.deepEqual(locale, new Map([["test.key-a", "1"], ["test.key-b", "2"]]));
});
});;
});
});
+1 -1
View File
@@ -93,7 +93,7 @@ describe("lib/factorio/server", function() {
it("should return a port number in the dynamic range", function() {
function validate(port) {
return 49152 <= port && port <= 65535;
return (49152 <= port && port <= 65535);
}
for (let i=0; i < 20; i++) {
assert(validate(factorio._randomDynamicPort()));
+2 -1
View File
@@ -5,7 +5,7 @@ const path = require("path");
const generateSSLcert = require("lib/generateSSLcert");
describe("generateSSLcert.js(options)", ()=>{
describe("generateSSLcert.js(options)", function() {
let testDir = path.join("temp", "test", "certTest");
before(async function() {
await fs.remove(testDir);
@@ -13,6 +13,7 @@ describe("generateSSLcert.js(options)", ()=>{
it("Creates a folder with a .crt and .key file in it", async function() {
this.timeout(1000);
// eslint-disable-next-line no-process-env
if (process.env.FAST_TEST) {
this.skip();
}
+1 -1
View File
@@ -81,7 +81,7 @@ describe("lib/link/connectors", function() {
describe(".processHandshake()", function() {
it("should close on invalid message", function() {
testConnector._socket.closeCalled = false;
testConnector._processHandshake({ data: "invalid message" }),
testConnector._processHandshake({ data: "invalid message" });
assert(testConnector._socket.closeCalled, "Close was not called on the socket");
});
it("should call register on hello", function() {
+1 -1
View File
@@ -56,7 +56,7 @@ describe("lib/link/link", function() {
);
});
it("should set the handler", function() {
let handler = (message) => {};
function handler(message) { }
testLink.setHandler("handler_test", handler, (message) => true);
assert.equal(testLink._handlers.get("handler_test"), handler);
});
+3 -7
View File
@@ -45,7 +45,7 @@ describe("lib/link/messages", function() {
let handlerResult;
it("should attach handler to a target link", function() {
testRequest.attach(testTargetLink, async (message) => handlerResult );
testRequest.attach(testTargetLink, async (message) => handlerResult);
assert(testTargetLink._handlers.has("test_request"), "Handler was not set");
});
it("should send result of calling the handler", async function() {
@@ -83,9 +83,7 @@ describe("lib/link/messages", function() {
testSourceLink.connector.send = (type, data) => {
request = { type, data };
};
testSourceLink.waitFor = (type, condition) => {
return { data: { type, request }};
};
testSourceLink.waitFor = (type, condition) => ({ data: { type, request }});
assert.deepEqual(
await testRequest.send(testSourceLink, { test: "request" }),
{ type: "test_response", request: { type: "test_request", data: { test: "request" }}}
@@ -94,9 +92,7 @@ describe("lib/link/messages", function() {
delete testSourceLink.waitFor;
});
it("should throw error response", async function() {
testSourceLink.waitFor = (type, condition) => {
return { data: { error: "test error" }};
};
testSourceLink.waitFor = (type, condition) => ({ data: { error: "test error" }});
await assert.rejects(
testRequest.send(testSourceLink, { test: "blah" }),
new errors.RequestError("test error")
+3 -22
View File
@@ -3,31 +3,12 @@ var assert = require("assert");
var objectOps = require("lib/objectOps");
describe("objectOps.js", function(){
/*describe("objectOps.clone()", function(){
it("clones javascript objects", function(){
var object1 = {hello:"world", cat:{legs:4, name:"Kitty", colors:["brown", "yellow", "purple"]}};
var object2 = {};
object2 = objectOps.clone(object1);
assert.equal(object2.cat.name, object1.cat.name)
assert.equal(object1.hello, object2.hello)
});
it("does not deep clone objects", function(){
var obj1 = {hello:"world", cat:{legs:4, name:"Kitty", colors:["brown", "yellow", "purple"]}};
var obj2 = {};
obj2 = objectOps.clone(obj1);
obj1.cat.colors = "black";
assert.equal(obj1.cat.colors, "black");
assert.notEqual(obj2.cat.colors[1], "yellow");
});
});*/
describe("objectOps.deepclone()", function(){
it("deep clones javascript objects", function(){
var obj1 = { hello:"world", cat:{ legs:4, name:"Kitty", colors:["brown", "yellow", "purple"] }};
var obj1 = { hello: "world", cat: { legs: 4, name: "Kitty", colors: ["brown", "yellow", "purple"] }};
var obj2 = {};
obj2 = objectOps.deepclone(obj1);
obj1.cat.colors = "black";
assert.equal(obj1.cat.colors, "black");
assert.equal(obj2.cat.colors[1], "yellow");
@@ -38,4 +19,4 @@ describe("objectOps.js", function(){
});
});
});
});
});
+1 -1
View File
@@ -103,7 +103,7 @@ describe("lib/plugin", function() {
plugin.attachPluginMessages(mockLink, {}, null);
});
it("should attach handler for the given message", function() {
let mockEventEventHandler = function() {};
function mockEventEventHandler() { };
plugin.attachPluginMessages(mockLink, { name: "test", messages: { mockEvent }}, { mockEventEventHandler });
assert(mockLink._handlers.get("test:test_event"), "handler was not registered");
});
+1 -1
View File
@@ -523,7 +523,7 @@ describe("lib/prometheus", function() {
let serializedResult = {
metric: { type: "type", name: "name", help: "Help", labels: ["a", "b"] },
samples: [ ['a="1",b="2"', 1], ['a="3",b="4"', 5] ],
samples: [['a="1",b="2"', 1], ['a="3",b="4"', 5]],
};
let deserializedResult = {
metric: new prometheus.Metric("type", "name", "Help", ["a", "b"]),