Move unit tests to test/ folder

Move unit tests for client, master, and the lib to test/ and move plugin
unit tests to <plugin dir>/test.
This commit is contained in:
Hornwitser committed 2019-09-14 14:49:52 +02:00
1 parent 74c99b9e13
commit a63c341209
16 files changed
+18 -12

No files matched your search

+40
View File
@@ -0,0 +1,40 @@
const assert = require('assert').strict;
const client = require("../client");
describe("Client testing", function() {
describe("randomDynamicPort()", function() {
it("should return a port number", function() {
let port = client._randomDynamicPort()
assert.equal(typeof port, "number");
assert(Number.isInteger(port));
assert(0 <= port && port < 2**16);
});
it("should return a port number in the dynamic range", function() {
function validate(port) {
return 49152 <= port && port <= 65535;
}
for (let i=0; i < 20; i++) {
assert(validate(client._randomDynamicPort()));
}
});
});
describe("generatePassword()", function() {
it("should return a string", async function() {
let password = await client._generatePassword(1);
assert.equal(typeof password, "string");
});
it("should return a string of the given length", async function() {
let password = await client._generatePassword(10);
assert.equal(password.length, 10);
});
it("should contain only a-z, A-Z, 0-9", async function() {
let password = await client._generatePassword(10);
assert(/^[a-zA-Z0-9]+$/.test(password), `${password} failed test`);
});
});
});
+212
View File
@@ -0,0 +1,212 @@
const assert = require("assert").strict;
const fs = require("fs-extra");
const database = require("lib/database");
describe("lib/database", function() {
describe("mapToObject()", function() {
it("should throw on non-string key", function() {
assert.throws(
() => database.mapToObject(new Map([[1, 1]])),
new Error("Expected all keys to be string but got number")
);
assert.throws(
() => database.mapToObject(new Map([[Symbol(), 1]])),
new Error("Expected all keys to be string but got symbol")
);
});
it("should throw convert a map to an object", function() {
assert.deepEqual(
database.mapToObject(new Map([['a', 1], ['b', true]])),
{'a': 1, 'b': true}
);
});
});
describe("loadJsonAsMap()", function() {
let badTypes = ['null', 'array', 'number', 'string', 'boolean'];
for (let type of badTypes) {
it(`should reject on ${type} JSON`, async function() {
await assert.rejects(
database.loadJsonAsMap(`test/json/${type}.json`),
new Error(`Expected object but got ${type}`)
);
});
}
it("should work on empty object JSON", async function() {
assert.deepEqual(
await database.loadJsonAsMap('test/json/object.json'),
new Map()
);
});
it("should work on object JSON", async function() {
assert.deepEqual(
await database.loadJsonAsMap('test/json/load_map.json'),
new Map([['a', 1], ['b', true]])
);
});
it("should give an empty Map for non-existant file", async function() {
assert.deepEqual(
await database.loadJsonAsMap('test/json/does-not-exist'),
new Map()
);
});
});
describe("saveMapAsJson()", function() {
it("should save a mapping as JSON", async function() {
let testFile = 'test/json/save_map.json';
async function deleteTestFile() {
try {
await fs.unlink(testFile);
} catch (err) {
/* istanbul ignore if */
if (err.code !== 'ENOENT') {
throw err;
}
}
}
await deleteTestFile();
await database.saveMapAsJson(
testFile, new Map([['c', {}], ['d', "foo"]])
);
assert.equal(
await fs.readFile(testFile, {encoding: 'utf-8'}),
'{\n "c": {},\n "d": "foo"\n}'
);
await deleteTestFile();
});
});
describe("class ItemDatabase", function() {
describe("constructor()", function() {
it("should create an empty database with no args", function() {
let items = new database.ItemDatabase();
assert.deepEqual(items._items, new Map());
});
it("should restore the passed serialized database", function() {
let items = new database.ItemDatabase({'a': 1, 'b': 2});
assert.deepEqual(items._items, new Map([['a', 1], ['b', 2]]));
});
it("should throw on invalid serialized database", function() {
assert.throws(
() => new database.ItemDatabase({'a': NaN}),
new Error("count must be a number")
);
assert.throws(
() => new database.ItemDatabase({'a': 'a'}),
new Error("count must be a number")
);
});
});
describe(".serialize()", function() {
it("should return a serialized database", function() {
let items = new database.ItemDatabase({'a': 10});
assert.deepEqual(items.serialize(), {'a': 10});
});
it("should remove zero count entries", function() {
let items = new database.ItemDatabase({'a': 0});
assert.deepEqual(items.serialize(), {});
});
});
describe(".size", function() {
it("should give an approximate size of the database", function() {
let items = new database.ItemDatabase({'a': 10});
assert.equal(items.size, 1);
});
});
describe(".getItemCount()", function() {
it("should return the count of the given item", function() {
let items = new database.ItemDatabase({'a': 10});
assert.equal(items.getItemCount('a'), 10);
});
it("should return zero if item does not exist", function() {
let items = new database.ItemDatabase();
assert.equal(items.getItemCount('b'), 0);
});
it("should throw on invalid name", function() {
let items = new database.ItemDatabase();
assert.throws(
() => items.getItemCount(2),
new Error("name must be a string")
);
});
});
describe(".addItem()", function() {
it("should add a new item", function() {
let items = new database.ItemDatabase();
items.addItem('a', 10);
assert.deepEqual(items._items, new Map([['a', 10]]));
})
it("should add an existing item", function() {
let items = new database.ItemDatabase({'a': 10});
items.addItem('a', 10);
assert.deepEqual(items._items, new Map([['a', 20]]));
})
it("should throw on invalid name", function() {
let items = new database.ItemDatabase();
assert.throws(
() => items.addItem(2, 10),
new Error("name must be a string")
);
});
it("should throw on invalid count", function() {
let items = new database.ItemDatabase();
assert.throws(
() => items.addItem('a', NaN),
new Error("count must be a number")
);
});
});
describe(".removeItem()", function() {
it("should remove an existing item", function() {
let items = new database.ItemDatabase({'a': 20});
items.removeItem('a', 10);
assert.deepEqual(items._items, new Map([['a', 10]]));
})
it("should turn a non-existing item negative", function() {
let items = new database.ItemDatabase();
items.removeItem('a', 10);
assert.deepEqual(items._items, new Map([['a', -10]]));
})
it("should throw on invalid name", function() {
let items = new database.ItemDatabase();
assert.throws(
() => items.removeItem(2, 10),
new Error("name must be a string")
);
});
it("should throw on invalid count", function() {
let items = new database.ItemDatabase();
assert.throws(
() => items.removeItem('a', 'b'),
new Error("count must be a number")
);
});
});
});
});
+115
View File
@@ -0,0 +1,115 @@
const assert = require("assert");
const fs = require("fs");
const path = require("path");
const parallel = require("mocha.parallel");
const mkdirp = require("mkdirp");
const factorioServer = require("lib/factorioServer");
describe("class factorioServer/index.js", ()=>{
it("is a class (or at least a function)", ()=>{
assert.equal(typeof factorioServer, "function");
});
describe(".deleteInstance(instanceName)", ()=>{
it("deletes an instance, defaulting to the classes instanceDirectory", async () => {
let server = new factorioServer({
instanceDirectory: path.resolve(__dirname, "_testData_deleteInstance"),
instanceName: "Unit testing instance",
});
await server.initialize();
await server.deleteInstance();
assert.equal(await server.isValidInstance(), false);
return true;
});
});
describe(".isValidInstance(instanceName)", ()=>{
it("tells us whether an instance exists or not", async () => {
let server = new factorioServer({
instanceDirectory: path.join(__dirname, "_testData_isValidInstance"),
instanceName: "Unit testing instance",
});
await server.deleteInstance();
let status = await server.isValidInstance();
assert.equal(status, false);
let x = await server.initialize(); // creates our instance
let status2 = await server.isValidInstance();
assert.equal(status2, true);
await server.deleteInstance(); // clean up folder
return true;
});
it("does not get tricked by an empty folder", async () => {
let server = new factorioServer({
instanceDirectory: path.join(__dirname, "_testData_isValidInstance_2"),
instanceName: "Unit testing instance",
});
assert.equal(await server.isValidInstance(), false);
mkdirp.sync(path.join(__dirname, "_testData_isValidInstance_2")); // create empty folder simulating instance
assert.equal(await server.isValidInstance(), false);
await server.initialize(); // create a proper instance
assert.equal(await server.isValidInstance(), true);
await server.deleteInstance(); // delete the instance and ensure we see that it is in fact deleted
assert.equal(await server.isValidInstance(), false);
return true;
}).timeout(5000);
});
describe(".initialize()", ()=>{
it("creates an instance", done => {
let server = new factorioServer({
instanceDirectory: path.resolve(__dirname, "_testData_initialize"),
instanceName: "Unit testing instance",
});
server.initialize().then(()=>{
return server.deleteInstance();
}).then(() => {
done();
}).catch(e => console.log(e));
});
});
describe(".createMap(mapName.zip)", ()=>{
it("creates a map file as instanceDirectory/saves/map.zip", async function(){
/* istanbul ignore if */ if (process.env.FAST_TEST) this.skip();
this.timeout(20000); // these test often takes a lot of time in the map creation step (4500 ms on i3 dev system)
let relativePath = path.relative('.', __dirname);
let server = new factorioServer({
instanceDirectory: path.join(relativePath, "_testData_createMap"),
instanceName: "Unit testing instance",
onProgress: false,
});
await server.initialize();
let maps = fs.readdirSync(path.join(relativePath, "_testData_createMap", "saves"));
assert.equal(maps.length, 0);
await server.createMap();
let maps2 = fs.readdirSync(path.join(relativePath, "_testData_createMap", "saves"));
assert(maps2.includes("map.zip"));
await server.deleteInstance();
return true;
});
it("supports custom filenames", async function(){
/* istanbul igoner if */ if (process.env.FAST_TEST) this.skip();
this.timeout(20000);
let relativePath = path.relative('.', __dirname);
let server = new factorioServer({
instanceDirectory: path.join(relativePath, "_testData_createMap_2"),
instanceName: "Unit testing instance",
onProgress: false,
});
await server.initialize();
let maps = fs.readdirSync(path.join(relativePath, "_testData_createMap_2", "saves"));
assert.equal(maps.length, 0);
await server.createMap("mapWithCustomName.zip");
let maps2 = fs.readdirSync(path.join(relativePath, "_testData_createMap_2", "saves"));
assert(maps2.includes("mapWithCustomName.zip"));
await server.deleteInstance();
return true;
});
});
});
+135
View File
@@ -0,0 +1,135 @@
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const fileOps = require('lib/fileOps');
// create folders for testing
function setupTestingEnv(){
if (!fs.existsSync(path.resolve(__dirname, "database"))){
fs.mkdirSync(path.resolve(__dirname, "database"));
}
if (!fs.existsSync(path.resolve(__dirname, "test"))){
fs.mkdirSync(path.resolve(__dirname, "test"));
}
if (!fs.existsSync(path.resolve(__dirname, "test/folder"))){
fs.mkdirSync(path.resolve(__dirname, "test/folder"));
}
if (!fs.existsSync(path.resolve(__dirname, "test/another folder"))){
fs.mkdirSync(path.resolve(__dirname, "test/another folder"));
}
if (!fs.existsSync(path.resolve(__dirname, "test/file.txt"))){
fs.writeFileSync(path.resolve(__dirname, "test/file.txt"), "contents");
}
if (!fs.existsSync(path.resolve(__dirname, "test/another file.txt"))){
fs.writeFileSync(path.resolve(__dirname, "test/another file.txt"), "more contents");
}
// we need this xfile to test a branch in fileOps.getNewestFile()s propagation
if (!fs.existsSync(path.resolve(__dirname, "test/xfile.txt"))){
fs.writeFileSync(path.resolve(__dirname, "test/xfile.txt"), "contents");
}
}
setupTestingEnv();
setupTestingEnv(); // run twice to get branch coverage
describe("fileOps.js", function(){
describe("fileOps.getDirectoriesSync()", function(){
it("gets an array of directory names from a path", function(){
let directories = fileOps.getDirectoriesSync(path.resolve(__dirname, "test"));
// because there are no arrays for some reason
assert(typeof directories == "object");
// they are sorted alphabetically because thats the way it is
assert(directories[0] == "another folder" && directories[1] == "folder");
});
it("does not return any filenames", function(){
let directories = fileOps.getDirectoriesSync(path.resolve(__dirname, "test"));
// this is a function to return directories, not files. So yeah.
assert(!directories.includes("file.txt") && !directories.includes("another file.txt"));
});
it("throws when lacking first argument", function(){
assert.throws(function(){
let files = fileOps.getDirectoriesSync();
}, Error);
});
});
describe("fileOps.getFileNamesSync(path)", function(){
it("gets names of files in directory", function(){
let files = fileOps.getFileNamesSync(path.resolve(__dirname, "test"));
assert(files.length > 0);
assert(files.includes("file.txt") && files.includes("another file.txt"));
});
it("throws when lacking first argument", function(){
assert.throws(function(){
let files = fileOps.getFileNamesSync();
}, Error);
});
});
describe("fileOps.getNewestFile()", function(){
it("gets the newest file in a directory async", function(done){
fileOps.getNewestFile(path.resolve(__dirname, "test/"), fileOps.getFileNamesSync(path.resolve(__dirname, "test")), function(err, newest){
assert(newest && typeof newest.file == "string");
done();
});
});
it("throws if callback is missing", function(){
assert.throws(function(){
fileOps.getNewestFile("test", fileOps.getFileNamesSync(path.resolve(__dirname, "test")));
}, Error);
});
it("executes callback(err) if no files are provided", function(done){
fileOps.getNewestFile(path.resolve(__dirname, "test"), [], function(err, newest){
assert(err && typeof err == "object");
done();
});
});
it("executes callback(err) if launched without a directory", function(done){
fileOps.getNewestFile("", fileOps.getFileNamesSync(path.resolve(__dirname, "test")), function(err, newest){
assert(err);
done();
});
});
it("executes callback(err) when you do stupid shit", function(done){
fileOps.getNewestFile({thisWontWork: "but not crash either"}, {lolz:"yeah..."}, function(err, newest){
assert(err);
// ENOENT: no such file or directory, stat 'C:\**\factorioClusterio\lib\test\undefined'
done();
});
});
});
describe("fileOps.deleteFolderRecursiveSync(path)", function(){
it("deletes a folder and all files and folders in it", function(){
let x = fileOps.deleteFolderRecursiveSync(path.resolve(__dirname, "test"));
assert.throws(function(){
fs.statSync(path.resolve(__dirname, "test"));
}, Error);
assert(x);
// give it some extra time because its sometimes very slow
}).timeout(5000);
it("returns false if you give it an invalid path", function(){
let x = fileOps.deleteFolderRecursiveSync("This isn't a real path");
assert(!x);
});
});
describe("fileOps.deleteFolderRecursive(path)", function(){
it("deletes a folder and all files and folders in it, just like sync version", async function(){
setupTestingEnv();
assert(fs.statSync(path.resolve(__dirname, "test")));
let x = await fileOps.deleteFolderRecursive(path.resolve(__dirname, "test"));
assert.throws(function(){
fs.statSync(path.resolve(__dirname, "test"));
}, Error);
assert(x === undefined, "Promise version of this function does not have a return value upon success");
return true;
}).timeout(5000);
it("throws like a promise does if you give it an invalid path", async function(){
let x = await fileOps.deleteFolderRecursive("Look this path is fake!")
.catch(e => {
assert(e);
assert.equal(e.code, "ENOENT");
return true;
});
});
});
});
+27
View File
@@ -0,0 +1,27 @@
var assert = require("assert");
var fs = require("fs-extra");
var fileOps = require("lib/fileOps");
var generateSSLcert = require("lib/generateSSLcert.js")
describe("generateSSLcert.js(options)", ()=>{
it("Creates a folder with a .crt and .key file in it", async function() {
/* istanbul ignore if */ if (process.env.FAST_TEST) this.skip();
let certPath = "lib/certTestPlsDelete/cert.crt";
let privKeyPath = "lib/certTestPlsDelete/cert.key";
assert(!await fs.exists(certPath)); // if it already exsits, the test might pass because of leftover data (which is bad)
await generateSSLcert({
// bits:512, // supported, but I just use the default of 2048 for this test
sslCertPath: certPath,
sslPrivKeyPath: privKeyPath,
doLogging: false,
});
assert(await fs.exists(certPath)); // private key
assert(await fs.exists(privKeyPath)); // certificate file
// remove certificates and data from the test
fileOps.deleteFolderRecursiveSync("lib/certTestPlsDelete");
}).timeout(10000);
});
+74
View File
@@ -0,0 +1,74 @@
const assert = require("assert");
const util = require("util");
const getFactorioLocale = require("lib/getFactorioLocale");
const asObjectAsync = util.promisify(getFactorioLocale.asObject);
describe("getFactorioLocale.js", function() {
describe("asObject()", function() {
it("requires 2 strings and a function as parameters", function() {
function validate(err) {
return err.message == "Error: wrong parameters provided"
}
let message = "getFactorioLocale is responding incorrectly to invalid arguments"
let callback = (err,object) => true;
assert.throws(() => getFactorioLocale.asObject(), validate, message);
assert.throws(() => getFactorioLocale.asObject("hello", "I forgot my callback"), validate, message);
assert.throws(() => getFactorioLocale.asObject(undefined, undefined, callback), validate, message);
// the proper way to do it
getFactorioLocale.asObject("factorio_0.15.27", "en", callback);
});
it("returns a nested object with base game locale information", async function() {
let object = await asObjectAsync("factorio", "en");
assert.equal(typeof object, "object");
assert.equal(object["entity-name"]["fish"], "Fish");
assert.equal(object["entity-name"]["small-lamp"], "Lamp");
let empty_keys = 0;
Object.keys(object).forEach(key => {
// first level of the nested object is always an object
assert.equal(typeof object[key], "object");
Object.keys(object[key]).forEach(key2 => {
// second level of the nested object is always a string, nearly always truthy
if (!object[key][key2]) {
empty_keys++;
}
assert.equal(typeof object[key][key2], "string");
});
});
assert(empty_keys < 10, `Got unusually high amount (${empty_keys}) of empty keys`);
});
it("has some duplicate keys", async function() {
let object = await asObjectAsync("factorio", "en");
let arrayOfKeys = [];
// collect all keys in a single array
Object.keys(object).forEach(key => {
arrayOfKeys.push(key);
Object.keys(object[key]).forEach(key2 => {
arrayOfKeys.push(key2);
});
});
// check for duplicates
let duplicateKeys = [];
let i = 0;
arrayOfKeys.forEach(key => {
let o = 0;
arrayOfKeys.forEach(key2 => {
if(i != o && key == key2){
duplicateKeys.push(key);
}
o++
});
i++;
});
// we got 704 but this is a very unexact number
assert(duplicateKeys.length > 10)
});
});
});
@@ -0,0 +1,18 @@
const isFactorioCommand = require("lib/isFactorioCommand");
const assert = require("assert");
describe("inventoryImports/isFactorioCommand.js()", function(){
it("Returns false if input is not a factorio command", function(){
assert(isFactorioCommand({}) == false, "This is not even a string so should return false");
assert(isFactorioCommand("Howdy boys!") == false, "This is not a command so should return false");
assert(isFactorioCommand("/c this ain't a command because its invalid LUA") == false, "This is not valid LUA so it should return false");
assert(isFactorioCommand("Trying to trick the system /c game.print('Hello world!')") == false, "this is still not a command");
});
it("Returns true if it is a valid command", function(){
assert(isFactorioCommand("/c game.print('hello world')"), "This is a valid command, should output true not false")
});
it("Fails to understand that leading spaces are valid", function(){
assert(isFactorioCommand(" /c game.print('Hello world!')") == false, "This should be true but often returns false unintentionally. If you see this you probably fixed the bug so change this test, OK?")
});
});
+40
View File
@@ -0,0 +1,40 @@
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 obj2 = {};
obj2 = objectOps.deepclone(obj1);
obj1.cat.colors = "black";
assert.equal(obj1.cat.colors, "black");
assert.equal(obj2.cat.colors[1], "yellow");
});
it("throws on non JSON parameters", function(){
assert.throws(function(){
let y = objectOps.deepclone(objectOps.deepclone);
});
});
});
});
+48
View File
@@ -0,0 +1,48 @@
const assert = require("assert");
const stringUtils = require("lib/stringUtils");
describe("stringUtils.js", function(){
describe("hashCode", function(){
it("Produces a 32bit signed int hash from a string", function(){
let x = stringUtils.hashCode("whatever");
let y = stringUtils.hashCode(" a much longer string to prove this works for long strings as well and also special characters &!¤(#)¤");
assert(typeof x == "number", "hashCode should be returning a 32 bit signed int");
assert(x.toString() == "1934383586");
assert(y.toString() == "1648886132");
});
let permutations = 1000;
it("Rarely produces same hash for different strings ("+permutations+" hashes with collision check)", function(){
let keyHashPairs = [];
for(let i = 0; i < permutations; i++){
let string = Math.random().toString();
keyHashPairs.push({
key:string,
hash:stringUtils.hashCode(string),
});
}
for(let i = 0; i < permutations; i++){
for(let o = 0; o < permutations; o++){
assert(i == o || keyHashPairs[o].key != keyHashPairs[i].key, "Woha, Math.random() generated 2 equal numbers???");
assert(i == o || keyHashPairs[o].hash != keyHashPairs[i].hash, "Hash collision, as long at it doesn't happen again its fine.");
}
}
});
it("Returns 0 for 0 length strings", function(){
let x = stringUtils.hashCode("");
assert.deepEqual(x, 0);
});
it("Throws when supplied with anything other than a string", function(){
assert.throws(function(){
stringUtils.hashCode([]);
}, "ERROR: Not a string")
assert.throws(function(){
stringUtils.hashCode({});
}, "ERROR: Not a string")
assert.throws(function(){
stringUtils.hashCode(0);
}, "ERROR: Not a string")
});
});
});
+136
View File
@@ -0,0 +1,136 @@
const assert = require('assert').strict;
const request = require('supertest');
const validateHTML = require('html5-validator');
const parallel = require('mocha.parallel');
const jwt = require("jsonwebtoken");
const master = require('../master.js');
const authenticate = require('lib/authenticate');
const database = require('lib/database');
master._db.slaves = new Map();
master._db.items = new database.ItemDatabase();
// Fields required in the config
master._config.factorioDirectory = "factorio";
master._config.itemStats = { maxEntries:60, entriesPerSecond: 1 / 60 };
master._config.disableFairItemDistribution = true;
const testSecret = "TestSecretDoNotUse";
authenticate.setAuthSecret(testSecret);
const token = jwt.sign({ id: "api" }, testSecret, { expiresIn: 600 });
async function get(path) {
return await request(master.app).get(path).expect(200);
}
async function getValidate(path) {
let res = await get(path);
let validation = await validateHTML(res.text);
let filtered = validation.messages.filter(msg => msg.type !== "info");
assert(filtered.length === 0, "there are HTML errors on the page, please fix: "+JSON.stringify(validation.messages, null, 4));
}
describe('Master testing', function() {
describe('#GET /api/getFactorioLocale', function() {
it('should get the basegame factorio locale', async function() {
let res = await get('/api/getFactorioLocale');
let object = res.body;
// test that it is looks like a factorio locale
assert.equal(typeof object, "object");
assert.equal(object["entity-name"]["fish"], "Fish");
assert.equal(object["entity-name"]["small-lamp"], "Lamp");
});
});
// describe("#GET /api/")
parallel("#GET static website data", function() {
this.timeout(6000);
let paths = ["/", "/nodes", "/settings", "/nodeDetails"];
for (let path of paths) {
it(`sends some HTML when accessing ${path}`, () => getValidate(path));
}
});
let persistentMaster = request(master.app);
describe("#POST /api/place", function() {
it("adds an itemStack to the masters inventory", function() {
return persistentMaster.post("/api/place").send({
name:"steel-plate",
count:20,
instanceName:"unitTest"
}).set(
"X-Access-Token", token
).expect(200).then(function(res) {
assert.equal(res.text, "success", "something went wrong with the request")
});
});
});
describe("#GET /api/inventory", function() {
it("returns the masters current inventory", function() {
return persistentMaster.get("/api/inventory").expect(200).then(function(res) {
let inventory = JSON.parse(res.text);
assert.equal(typeof inventory, "object", "Inventory should be an object");
assert(inventory.length >= 1, "There should be at least 1 entry in the inventory");
let contains20SteelPlate = false;
inventory.forEach(itemStack => {
if(itemStack.name == "steel-plate" && itemStack.count >= 20) contains20SteelPlate = true;
});
assert(contains20SteelPlate, "Please ensure there are at least 20 steel plate in the inventory")
});
});
});
describe("#POST /api/remove", function() {
it("returns an itemStack of how many items were removed", function() {
return persistentMaster.post("/api/remove").send({
name:"steel-plate",
count:10
}).set(
"X-Access-Token", token
).expect(200).then(function(res) {
assert.equal(res.body.count, 10, `Expected 10 steel got ${res.text}`);
});
});
it("works correctly for items named addItem or removeItem", async function() {
function add(item) {
return persistentMaster.post("/api/place").send({
name: item,
count: 10
}).set(
"X-Access-Token", token
).expect(200).then(function(res) {
assert.equal(res.text, 'success', `/api/place ${item} failed with ${res.text}`);
})
}
function remove(item) {
return persistentMaster.post("/api/remove").send({
name: item,
count: 10
}).set(
"X-Access-Token", token
).expect(200).then(function(res) {
assert.deepEqual(res.body, {"name":item,"count":10});
});
}
await Promise.all([add("addItem"), add("removeItem")]);
await Promise.all([remove("addItem"), remove("removeItem")]);
});
it("returns an empty itemStack if you don't have any of the item you request", function() {
return persistentMaster.post("/api/remove").send({
name:"imaginaryItem",
count:999999
}).set(
"X-Access-Token", token
).expect(200).then(function(res) {
assert.equal(res.body.name, "imaginaryItem", "Make sure body.name is the item we asked for");
assert.equal(res.body.count, 0, "Count should be 0 since we are asking for something that does not exist anywhere");
assert.equal(Object.keys(res.body).length, 2, "name and count should be the only keys on this object");
});
});
});
});