From 6cd09266c336f6ed60e5eb8f6a42b62e44d0efc0 Mon Sep 17 00:00:00 2001 From: Gavin Mogan Date: Sun, 26 Apr 2020 17:07:28 -0700 Subject: [PATCH] Mock out http calls with record/replay functionality * Use talkback to record any http calls to a real server * Record them to the tapes/ directory * This means it can be tested by those who don't have a server up and running. * Can remove the hidden variables in travis * Will do real api calls when tapes don't exist and record new ones Not all tapes committed cause I was concerned about leaking steamid and ips --- package-lock.json | 51 +++++++++++ package.json | 3 +- test/_globals.ts | 84 +++++++++++++++++++ test/executeConsoleCommand.test.ts | 16 ++-- test/getAllowedCommands.test.ts | 17 +--- test/getAnimalsLocation.test.ts | 19 +---- test/getBaseUrl.test.ts | 4 +- test/getHostileLocation.test.ts | 19 +---- test/getLandClaims.test.ts | 17 +--- test/getLog.test.ts | 25 ++---- test/getOnlinePlayers.test.ts | 23 ++--- test/getPlayerInventories.test.ts | 17 +--- test/getPlayerInventory.test.ts | 16 +--- test/getPlayerList.test.ts | 18 +--- test/getPlayersLocation.test.ts | 18 +--- test/getServerInfo.test.ts | 16 +--- test/getStats.test.ts | 19 +---- test/getWebUIUpdates.test.ts | 21 ++--- ...executeconsolecommand_command_foobar.json5 | 39 +++++++++ ...i_executeconsolecommand_command_help.json5 | 43 ++++++++++ 20 files changed, 278 insertions(+), 207 deletions(-) create mode 100644 test/_globals.ts create mode 100644 test/tapes/_api_executeconsolecommand_command_foobar.json5 create mode 100644 test/tapes/_api_executeconsolecommand_command_help.json5 diff --git a/package-lock.json b/package-lock.json index aa2ce30..e34bbfe 100644 --- a/package-lock.json +++ b/package-lock.json @@ -412,6 +412,12 @@ "integrity": "sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==", "dev": true }, + "buffer-shims": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/buffer-shims/-/buffer-shims-1.0.0.tgz", + "integrity": "sha1-mXjOMXOIxkmth5MCjDR37wRKi1E=", + "dev": true + }, "callsites": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", @@ -599,6 +605,12 @@ "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", "dev": true }, + "content-type": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.4.tgz", + "integrity": "sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==", + "dev": true + }, "core-util-is": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.2.tgz", @@ -1821,6 +1833,23 @@ "integrity": "sha1-Epai1Y/UXxmg9s4B1lcB4sc1tus=", "dev": true }, + "json5": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.1.3.tgz", + "integrity": "sha512-KXPvOm8K9IJKFM0bmdn8QXh7udDh1g/giieX0NLCaMnb4hEiVFqnop2ImTXCc5e0/oHz3LTqmHGtExn5hfMkOA==", + "dev": true, + "requires": { + "minimist": "^1.2.5" + }, + "dependencies": { + "minimist": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.5.tgz", + "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", + "dev": true + } + } + }, "jsonfile": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", @@ -2780,6 +2809,28 @@ } } }, + "talkback": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/talkback/-/talkback-2.1.1.tgz", + "integrity": "sha512-Ny6UFsKq0jlsWSWSbjHVGQNQdKX6XJr8XvsmWCc9YRMh5TyjnwxEsbz1ZsARpMSxZHPrkawd7l3DLpuKA5B7mA==", + "dev": true, + "requires": { + "buffer-shims": "^1.0.0", + "content-type": "^1.0.4", + "json5": "^2.1.1", + "lodash": "^4.17.15", + "mkdirp": "^1.0.3", + "node-fetch": "^2.2.1" + }, + "dependencies": { + "mkdirp": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", + "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", + "dev": true + } + } + }, "text-table": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz", diff --git a/package.json b/package.json index 3c4a2f4..d6bc0da 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "istanbul": "^0.4.5", "mocha": "^7.0.0", "shx": "^0.3.0", + "talkback": "^2.1.1", "ts-node": "^8.3.0", "typedoc": "^0.17.4", "typescript": "^3.8.3" @@ -75,4 +76,4 @@ "pre-push": "npm run lint" } } -} \ No newline at end of file +} diff --git a/test/_globals.ts b/test/_globals.ts new file mode 100644 index 0000000..5c9a968 --- /dev/null +++ b/test/_globals.ts @@ -0,0 +1,84 @@ +/* eslint-env mocha */ +/* + * Shareable items between tests + */ +import { URL } from 'url'; +import * as querystring from 'querystring'; +import * as chai from 'chai'; +import * as chaiAsPromised from 'chai-as-promised'; +import TalkbackServer from 'talkback/server'; +import { RecordMode } from 'talkback/options'; +import Tape from 'talkback/tape'; +import { Req } from 'talkback/types'; +import { SdtdServer } from '../lib/index'; + +// talkback's typescript/import returns different stuff than the require, so disable the eslint alert for now +//eslint-disable-next-line @typescript-eslint/no-var-requires +const talkback = require('talkback'); + +class TestGlobals { + testServer: SdtdServer; + proxy: TalkbackServer; + + constructor() { + this.testServer = { + ip: "localhost", + port: "5544", + adminUser: 'fakeadminuser', + adminToken: 'fakeadmintoken' + }; + const host = `http://${process.env.TESTIP}:${process.env.TESTPORT}`; + this.proxy = talkback({ + host: host, + record: RecordMode.NEW, + port: 5544, + path: `${__dirname}/tapes/`, + silent: true, + ignoreQueryParams: ['adminuser', 'admintoken'], + tapeNameGenerator: (tapeNumber: number, tape: Tape): string => { + const url = new URL(tape.req.url, host); + const query = querystring.parse(url.search.substr(1)); + delete query.adminuser; + delete query.admintoken; + return url.pathname.replace(/\//g, '_') + '_' + querystring.stringify(query, '_', '_') + ".json5"; + }, + requestDecorator: function(req: Req) { + const url = new URL(req.url, host); + const query = querystring.parse(url.search.substr(1)); + query.adminuser = process.env.TESTADMINUSER || 'unknown'; + query.admintoken = process.env.TESTADMINTOKEN || 'unknown'; + url.search = '?' + querystring.stringify(query); + req.url = url.toString().replace(host, ''); + return req; + } + }); + } + + setTestServer(testServer: SdtdServer): void { + this.testServer = testServer; + } + getTestServer(): SdtdServer { + return this.testServer; + } + + setProxy(proxy: TalkbackServer): void { + this.proxy = proxy; + } + getProxy(): TalkbackServer { + return this.proxy; + } +} + +const testGlobals = new TestGlobals(); +export default testGlobals; + +require('dotenv').config(); + +chai.use(chaiAsPromised); + +before(function(done) { + testGlobals.getProxy().start(() => done()); +}); +after(function() { + testGlobals.getProxy().close(); +}); diff --git a/test/executeConsoleCommand.test.ts b/test/executeConsoleCommand.test.ts index da89d11..ee73b52 100644 --- a/test/executeConsoleCommand.test.ts +++ b/test/executeConsoleCommand.test.ts @@ -1,36 +1,30 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; import * as chaiAsPromised from 'chai-as-promised'; -import { executeConsoleCommand, SdtdServer } from '../lib/index'; +import { executeConsoleCommand } from '../lib/index'; import { fail } from 'assert'; require('dotenv').config(); chai.use(chaiAsPromised); -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; - describe('/api/executeconsolecommand', async () => { it('Returns command, parameters and result', async () => { - const response = await executeConsoleCommand(testServer, "help"); + const response = await executeConsoleCommand(g.getTestServer(), "help"); chai.expect(response.command).to.be.a('string'); chai.expect(response.parameters).to.be.a('string'); }); it('Executes a command correctly', async () => { - const response = await executeConsoleCommand(testServer, "help"); + const response = await executeConsoleCommand(g.getTestServer(), "help"); chai.expect(response.command).to.eq('help'); chai.expect(response.parameters).to.eq(''); chai.expect(response.result).to.include("*** Generic Console Help ***"); }); it('Executes a an unknown command - foobar', async () => { try { - await executeConsoleCommand(testServer, "foobar"); + await executeConsoleCommand(g.getTestServer(), "foobar"); fail('should have failed'); } catch (e) { chai.expect(e).to.be.a('error'); diff --git a/test/getAllowedCommands.test.ts b/test/getAllowedCommands.test.ts index d63662b..b671835 100644 --- a/test/getAllowedCommands.test.ts +++ b/test/getAllowedCommands.test.ts @@ -1,22 +1,11 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getAllowedCommands, SdtdServer } from '../lib/index'; - -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; +import { getAllowedCommands } from '../lib/index'; describe('/api/getAllowedCommands', async () => { it('Returns an array', async () => { - const response = await getAllowedCommands(testServer); + const response = await getAllowedCommands(g.getTestServer()); chai.expect(response.commands).to.be.a('array'); }); }); \ No newline at end of file diff --git a/test/getAnimalsLocation.test.ts b/test/getAnimalsLocation.test.ts index 76a0734..bc8104f 100644 --- a/test/getAnimalsLocation.test.ts +++ b/test/getAnimalsLocation.test.ts @@ -1,28 +1,17 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getAnimalsLocation, SdtdServer } from '../lib/index'; - -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; +import { getAnimalsLocation } from '../lib/index'; describe('/api/getAnimalsLocation', async () => { it('Returns an array of animal info', async () => { - const response = await getAnimalsLocation(testServer); + const response = await getAnimalsLocation(g.getTestServer()); chai.expect(response).to.be.an('array'); }); it('Contains expected information', async () => { - const response = await getAnimalsLocation(testServer); + const response = await getAnimalsLocation(g.getTestServer()); if (response.length > 0) { const animal = response[0]; chai.expect(animal.id).to.be.a('number'); diff --git a/test/getBaseUrl.test.ts b/test/getBaseUrl.test.ts index 468cbae..10537ff 100644 --- a/test/getBaseUrl.test.ts +++ b/test/getBaseUrl.test.ts @@ -1,10 +1,8 @@ 'use strict'; +import './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; import { getBaseUrl } from '../lib/index'; -chai.use(chaiAsPromised); - describe('getBaseUrl', async () => { it('standard returns http', async () => { chai.expect( diff --git a/test/getHostileLocation.test.ts b/test/getHostileLocation.test.ts index 25c6007..3ea3088 100644 --- a/test/getHostileLocation.test.ts +++ b/test/getHostileLocation.test.ts @@ -1,28 +1,17 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getHostileLocation, SdtdServer } from '../lib/index'; - -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; +import { getHostileLocation } from '../lib/index'; describe('/api/getHostileLocation', async () => { it('Returns an array of hostile info', async () => { - const response = await getHostileLocation(testServer); + const response = await getHostileLocation(g.getTestServer()); chai.expect(response).to.be.an('array'); }); it('Contains expected information', async () => { - const response = await getHostileLocation(testServer); + const response = await getHostileLocation(g.getTestServer()); if (response.length > 0) { const animal = response[0]; chai.expect(animal.id).to.be.a('number'); diff --git a/test/getLandClaims.test.ts b/test/getLandClaims.test.ts index 4733d0c..7802fc3 100644 --- a/test/getLandClaims.test.ts +++ b/test/getLandClaims.test.ts @@ -1,22 +1,11 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getLandClaims, SdtdServer } from '../lib/index'; - -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; +import { getLandClaims } from '../lib/index'; describe('/api/getLandClaims', async () => { it('Returns an array of animal info', async () => { - const response = await getLandClaims(testServer); + const response = await getLandClaims(g.getTestServer()); chai.expect(response.claimowners).to.be.a('array'); chai.expect(response.claimsize).to.be.a('number'); }); diff --git a/test/getLog.test.ts b/test/getLog.test.ts index 3f2cae2..0d9c208 100644 --- a/test/getLog.test.ts +++ b/test/getLog.test.ts @@ -1,22 +1,11 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getWebUIUpdates, getLog, SdtdServer } from '../lib/index'; - -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; +import { getWebUIUpdates, getLog } from '../lib/index'; describe('/api/getLog', async () => { it('Returns expected output', async () => { - const response = await getLog(testServer); + const response = await getLog(g.getTestServer()); chai.expect(response.firstLine).to.be.a('number'); chai.expect(response.lastLine).to.be.a('number'); chai.expect(response.entries).to.be.a('array'); @@ -25,18 +14,18 @@ describe('/api/getLog', async () => { // Obsolete to test this in here // This is a test to see if allocs is working properly, we should assume it does xit('Cycles through logs when firstLine is given', async () => { - const webUiUpdates = await getWebUIUpdates(testServer); + const webUiUpdates = await getWebUIUpdates(g.getTestServer()); const firstLine = webUiUpdates.newlogs - 75; - const response = await getLog(testServer, firstLine); + const response = await getLog(g.getTestServer(), firstLine); chai.expect(response.firstLine).to.eq(firstLine); }); xit('Supports the count parameter', async () => { - const webUiUpdates = await getWebUIUpdates(testServer); + const webUiUpdates = await getWebUIUpdates(g.getTestServer()); const count = 100; const firstLine = webUiUpdates.newlogs - (count + 20); - const response = await getLog(testServer, firstLine, count); + const response = await getLog(g.getTestServer(), firstLine, count); chai.expect(response.entries).to.have.lengthOf(count); }); }); \ No newline at end of file diff --git a/test/getOnlinePlayers.test.ts b/test/getOnlinePlayers.test.ts index 77b5c1c..9e57eff 100644 --- a/test/getOnlinePlayers.test.ts +++ b/test/getOnlinePlayers.test.ts @@ -1,27 +1,16 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getOnlinePlayers, SdtdServer } from '../lib/index'; - -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; +import { getOnlinePlayers } from '../lib/index'; describe('/api/getOnlinePlayers', async () => { it('Returns an array of player info', async () => { - const response = await getOnlinePlayers(testServer); + const response = await getOnlinePlayers(g.getTestServer()); chai.expect(response).to.be.an('array'); }); it('Contains identifying information for players', async () => { - const response = await getOnlinePlayers(testServer); + const response = await getOnlinePlayers(g.getTestServer()); if (response.length > 0) { const playerStats = response[0]; @@ -33,7 +22,7 @@ describe('/api/getOnlinePlayers', async () => { }); it('Contains location data', async () => { - const response = await getOnlinePlayers(testServer); + const response = await getOnlinePlayers(g.getTestServer()); if (response.length > 0) { const playerStats = response[0]; @@ -45,7 +34,7 @@ describe('/api/getOnlinePlayers', async () => { }); it('Contains kills deaths score experience and level data', async () => { - const response = await getOnlinePlayers(testServer); + const response = await getOnlinePlayers(g.getTestServer()); if (response.length > 0) { const playerStats = response[0]; diff --git a/test/getPlayerInventories.test.ts b/test/getPlayerInventories.test.ts index ff49e34..2a60804 100644 --- a/test/getPlayerInventories.test.ts +++ b/test/getPlayerInventories.test.ts @@ -1,22 +1,11 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getPlayerInventories, SdtdServer } from '../lib/index'; - -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; +import { getPlayerInventories } from '../lib/index'; describe('/api/getPlayerInventories', async () => { it('Returns expected info', async () => { - const response = await getPlayerInventories(testServer); + const response = await getPlayerInventories(g.getTestServer()); chai.expect(response).to.be.a('array'); }); }); \ No newline at end of file diff --git a/test/getPlayerInventory.test.ts b/test/getPlayerInventory.test.ts index 67bdeb1..cede494 100644 --- a/test/getPlayerInventory.test.ts +++ b/test/getPlayerInventory.test.ts @@ -1,21 +1,11 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getPlayerInventory, SdtdServer } from '../lib/index'; +import { getPlayerInventory } from '../lib/index'; -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; describe('/api/getPlayerInventory', async () => { it('Returns a playername, bag, belt and equipment', async () => { - const response = await getPlayerInventory(testServer, process.env.TESTPLAYER as string); + const response = await getPlayerInventory(g.getTestServer(), process.env.TESTPLAYER as string); chai.expect(response.playername).to.be.a('string'); chai.expect(response.bag).to.be.a('array'); chai.expect(response.belt).to.be.a('array'); diff --git a/test/getPlayerList.test.ts b/test/getPlayerList.test.ts index f999339..55839ef 100644 --- a/test/getPlayerList.test.ts +++ b/test/getPlayerList.test.ts @@ -1,28 +1,18 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getPlayerList, SdtdServer } from '../lib/index'; +import { getPlayerList } from '../lib/index'; -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; describe('/api/getPlayerList', async () => { it('Returns expected output', async () => { - const response = await getPlayerList(testServer); + const response = await getPlayerList(g.getTestServer()); chai.expect(response.total).to.be.a('number'); chai.expect(response.totalUnfiltered).to.be.a('number'); chai.expect(response.firstResult).to.be.a('number'); chai.expect(response.players).to.be.a('array'); }); it('Limits response if rowsPerPage is given', async () => { - const response = await getPlayerList(testServer, 1); + const response = await getPlayerList(g.getTestServer(), 1); chai.expect(response.players).to.be.a('array'); chai.expect(response.players).to.have.length(1); }); diff --git a/test/getPlayersLocation.test.ts b/test/getPlayersLocation.test.ts index c5032a1..6d0b886 100644 --- a/test/getPlayersLocation.test.ts +++ b/test/getPlayersLocation.test.ts @@ -1,26 +1,16 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import * as SdtdApi from '../lib/index'; +import { getPlayersLocation } from '../lib/index'; -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdApi.SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; describe('/api/getPlayersLocation', async () => { it('Returns an array', async () => { - const response = await SdtdApi.getPlayersLocation(testServer, false); + const response = await getPlayersLocation(g.getTestServer(), false); chai.expect(response).to.be.a('array'); }); it('Returns an array with data if offline is set to true', async () => { - const response = await SdtdApi.getPlayersLocation(testServer, true); + const response = await getPlayersLocation(g.getTestServer(), true); chai.expect(response).to.be.a('array'); chai.expect(response).to.have.length.greaterThan(0); chai.expect(response[0].steamid).to.be.a("string"); diff --git a/test/getServerInfo.test.ts b/test/getServerInfo.test.ts index ef5056b..4537429 100644 --- a/test/getServerInfo.test.ts +++ b/test/getServerInfo.test.ts @@ -1,21 +1,11 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getServerInfo, SdtdServer } from '../lib/index'; +import { getServerInfo } from '../lib/index'; -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; describe('/api/getServerInfo', async () => { it('Returns expected output', async () => { - const response = await getServerInfo(testServer); + const response = await getServerInfo(g.getTestServer()); chai.expect(response.GameType.value).to.be.a('string'); chai.expect(response.GameName.value).to.be.a('string'); chai.expect(response.GameHost.value).to.be.a('string'); diff --git a/test/getStats.test.ts b/test/getStats.test.ts index 7660290..abcfbd7 100644 --- a/test/getStats.test.ts +++ b/test/getStats.test.ts @@ -1,22 +1,11 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getStats, SdtdServer } from '../lib/index'; - -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; +import { getStats } from '../lib/index'; describe('/api/getstats', async () => { it('Returns expected info', async () => { - const response = await getStats(testServer); + const response = await getStats(g.getTestServer()); chai.expect(response.players).to.be.a('number'); chai.expect(response.animals).to.be.a('number'); chai.expect(response.hostiles).to.be.a('number'); @@ -27,6 +16,6 @@ describe('/api/getstats', async () => { it('Accepts extra options', async () => { // If 7d2d server runs on same machine as you are running tests, this 1 ms timeout is sometimes not enough. - await chai.expect(getStats(testServer, { timeout: 1 })).to.be.rejectedWith(Error); + await chai.expect(getStats(g.getTestServer(), { timeout: 1 })).to.be.rejectedWith(Error); }); }); \ No newline at end of file diff --git a/test/getWebUIUpdates.test.ts b/test/getWebUIUpdates.test.ts index 6544ece..db42b13 100644 --- a/test/getWebUIUpdates.test.ts +++ b/test/getWebUIUpdates.test.ts @@ -1,22 +1,11 @@ 'use strict'; +import g from './_globals'; import * as chai from 'chai'; -import * as chaiAsPromised from 'chai-as-promised'; -import { getWebUIUpdates, SdtdServer } from '../lib/index'; - -require('dotenv').config(); - -chai.use(chaiAsPromised); - -const testServer: SdtdServer = { - ip: process.env.TESTIP as string, - port: process.env.TESTPORT as string, - adminUser: process.env.TESTADMINUSER as string, - adminToken: process.env.TESTADMINTOKEN as string -}; +import { getWebUIUpdates } from '../lib/index'; describe('/api/getWebUIUpdates', async () => { it('Returns expected output', async () => { - const response = await getWebUIUpdates(testServer); + const response = await getWebUIUpdates(g.getTestServer()); chai.expect(response.gametime.days).to.be.a('number'); chai.expect(response.gametime.hours).to.be.a('number'); chai.expect(response.gametime.minutes).to.be.a('number'); @@ -28,10 +17,10 @@ describe('/api/getWebUIUpdates', async () => { }); it('Limits newlogs response if latestLine is given', async () => { const logsOffset = 75; - const firstResponse = await getWebUIUpdates(testServer); + const firstResponse = await getWebUIUpdates(g.getTestServer()); const newlogs = firstResponse.newlogs; - const secondResponse = await getWebUIUpdates(testServer, newlogs - logsOffset); + const secondResponse = await getWebUIUpdates(g.getTestServer(), newlogs - logsOffset); chai.expect(secondResponse.newlogs).to.eq(logsOffset); }); diff --git a/test/tapes/_api_executeconsolecommand_command_foobar.json5 b/test/tapes/_api_executeconsolecommand_command_foobar.json5 new file mode 100644 index 0000000..1800239 --- /dev/null +++ b/test/tapes/_api_executeconsolecommand_command_foobar.json5 @@ -0,0 +1,39 @@ +{ + meta: { + createdAt: '2020-04-27T00:03:01.915Z', + host: 'http://78.46.203.193:8082', + resHumanReadable: true, + }, + req: { + url: '/api/executeconsolecommand?command=foobar', + method: 'GET', + headers: { + accept: '*/*', + 'user-agent': 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)', + 'accept-encoding': 'gzip,deflate', + connection: 'close', + }, + body: '', + }, + res: { + status: 404, + headers: { + 'content-type': [ + 'text/html; charset=utf-8', + ], + server: [ + 'Mono-HTTPAPI/1.0', + ], + date: [ + 'Mon, 27 Apr 2020 00:03:02 GMT', + ], + 'content-length': [ + '15', + ], + connection: [ + 'close', + ], + }, + body: 'Unknown command', + }, +} \ No newline at end of file diff --git a/test/tapes/_api_executeconsolecommand_command_help.json5 b/test/tapes/_api_executeconsolecommand_command_help.json5 new file mode 100644 index 0000000..d531f82 --- /dev/null +++ b/test/tapes/_api_executeconsolecommand_command_help.json5 @@ -0,0 +1,43 @@ +{ + meta: { + createdAt: '2020-04-27T00:03:01.569Z', + host: 'http://78.46.203.193:8082', + resHumanReadable: true, + }, + req: { + url: '/api/executeconsolecommand?command=help', + method: 'GET', + headers: { + accept: '*/*', + 'user-agent': 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)', + 'accept-encoding': 'gzip,deflate', + connection: 'close', + }, + body: '', + }, + res: { + status: 200, + headers: { + 'content-type': [ + 'application/json; charset=utf-8', + ], + server: [ + 'Mono-HTTPAPI/1.0', + ], + date: [ + 'Mon, 27 Apr 2020 00:03:01 GMT', + ], + 'content-length': [ + '13510', + ], + connection: [ + 'close', + ], + }, + body: { + command: 'help', + parameters: '', + result: '*** Generic Console Help ***\nTo get further help on a specific topic or command type (without the brackets)\n help \n\nGeneric notation of command parameters:\n Required parameter\n Possible types of parameter values\n [param name] Optional parameter\n\n*** List of Help Topics ***\nNone yet\n\n*** List of Commands ***\n admin => Manage user permission levels\n aiddebug => Toggles AIDirector debug output.\n audio => Watch audio stats\n automove => Player auto movement\n ban => Manage ban entries\n bents => Switches block entities on/off\n BiomeParticles => Debug\n buff => Applies a buff to the local player\n buffplayer => Apply a buff to a player\n chunkcache cc => shows all loaded chunks in cache\n chunkobserver co => Place a chunk observer on a given position.\n chunkreset cr => resets the specified chunks\n commandpermission cp => Manage command permission levels\n cpm-additemloot additemloot => add item to SecureLoot below the given entity\n cpm-announcenighttime announcenighttime an => Turn NightTime announcement on/off\n cpm-arrest arrest => Put a player in jail (reversed claim jail required!)\n cpm-bcheck bcheck => Checks the type of block by coordinates or under your feet.\n cpm-bdup bdup => Copy an Area to another location\n cpm-bexport bexport => Exports as Prefab some space\n cpm-brender brender => Renders a Prefab on given location\n cpm-brepblock brepblock => Replace blocks from a defined location\n cpm-bun bun blockutf8names => Kick any players with UTF-8 chars in name at login\n cpm-bundo bundo => Undo last prefab command\n cpm-ccc ccc => Manage advanced claims\n cpm-ccp ccp chatcommandpermissions => Set permission levels on admin chatcommands\n cpm-chatgroupcolor chatgroupcolor cgc => Manage chat color by groupmembership.\n cpm-checkloot checkloot => check items from SecureLoot below the given entity\n cpm-cpmprefix cpmprefix => Set prefix for CPM chatcommands.\n cpm-cs cs => Spawn scouts near a player or coordinate\n cpm-cvc cvc checkvehiclecontent => check the content of a vehicle.\n cpm-db db deactivatebed => Deactivate a players bed(roll).\n cpm-ds donorslot ds => Add, Remove and View steamids on the ReservedSlots list.\n cpm-entityremove entityremove => remove entity from game\n cpm-eoc eoc executeonclient => Let a local player fire a local only console coommand (or any)\n cpm-etele etele => Teleport an entity\n cpm-fblock fblock => Fill a defined area with a specific block\n cpm-fblock1 fblock1 => place one block at a time without the need of chunkreloading (RPC)\n cpm-gc gc => Invoke the garbagecollector. Free some memory.\n cpm-getbicycle getbicycle => Get lost or stuck bicycle to player\n cpm-getbike getbike => Get lost or stuck minibike to player\n cpm-getgyrocopter getgyrocopter => Get lost or stuck gyrocopter to player\n cpm-getjeep getjeep => Get lost or stuck jeep to player\n cpm-getmotorcycle getmotorcycle => Get lost or stuck motorcycle to player\n cpm-getprefab getprefab => Get info/manage the RWG prefab you are standing in.\n cpm-giveplus giveplus => give an item to a player(s) (entity id or name)\n cpm-givexp givexp => give XP to a player\n cpm-got got => give items to or trade items with other player\n cpm-grablcb grablcb => Put all landclaims within of and owned by player in his/her backpack.\n cpm-help => Help on console and specific CSMM Patrons Mod commands\n cpm-hidechatcommand hidechatcommand hccp => specify a chat message prefix that defines chat commands that are hidden from chat\n cpm-lce lce listcustomentity => List entity with custom parameter for better filtering.\n cpm-listbedplayer listbedplayer lbp => list bed locations of all players or a specific player\n cpm-listbuffs listbuffs lbuffs => List or search all available buffs\n cpm-listfriendsplayer listfriendsplayer lfp => list friends of a single player or all players\n cpm-listlandclaims listlandclaims llc => lists all land protection blocks and owners\n cpm-listplayerbuffs listplayerbuffs lpbuffs => List players active buffs\n cpm-listplayerskill listplayerskill lps => list players Skills\n cpm-loctrack loctrack => Manage locationtracker settings and data\n cpm-mrr mrr markresetregion => Manage the reset regions list.\n cpm-multipleentityspawn multipleentityspawn mes => spawn multiple entities around some coordinate or player\n cpm-mutechatplayer mutechatplayer mcp => mute a player on public chat\n cpm-mv mv => Move player command (to coordinates and to other player). Optionally restrict to friends only.\n cpm-mvw mvw => Move player to waypoint.\n cpm-ov ov ownvehicle => take ownership of a vehicle.\n cpm-overridechatname overridechatname ocn => Change a player\'s chat name.\n cpm-own own => define an owner to SecureLoot/SecureDoor for a player.\n cpm-pd pd permadeath => Manage permadeath players\n cpm-pfb pfb preventfallingblocks => Prevent falling blocks on server.\n cpm-playerchatcolor playerchatcolor pcc => Change default player chat color.\n cpm-playsound playsound => Play an ingame sound on any server/player position.\n cpm-protectplayer protectplayer protect => Set protective bubble on player.\n cpm-release release => Release a player from jail.\n cpm-remitem remitem => remove items from SecureLoot below the given entity\n cpm-removelandprotection2 removelandprotection2 rlp2 => removes the association of a land protection block without players needing to be near\n cpm-resetregionsnow resetregionsnow => Execute shutdown immediately and reset marked regions.\n cpm-resetrwgprefabs resetrwgprefabs rrp => Reset all RWG prefabs.\n cpm-resetunclaimedregionsnow resetunclaimedregionsnow => Execute shutdown immediately and reset ALL regions except the ones that have LCB/Adv. Claim on.\n cpm-rpd rpd resetplayerdata => Reset a player\n cpm-rt rt repairtrees => Repair indestructable trees (only with damageindicator)\n cpm-say2 say2 => Sends a message to all connected clients with specific sender\n cpm-sayadmin sayadmin => Send a PM to all players meeting the minimum receipients permisson level\n cpm-sayplayer2 sayplayer2 pm2 => send a message to a single player with a specific sender name\n cpm-scn scn serverchatname => Set server chatname globally\n cpm-sdc sdc setdeathcount => Set a player\'s deathcount.\n cpm-setbundosize setbundosize => Set the size of history on bundo\n cpm-setplayerstatus setplayerstatus sps => Change players attributes (zombiekills, playerkills)\n cpm-showinventory2 showinventory2 si2 => list inventory of a given player\n cpm-shutdownba shutdownba => Timed shutdown with bloodmoon awareness.\n cpm-sleepers sleepers => Remove sleepervolumes from world\n cpm-targetedhorde targetedhorde th => Spawn targeted horde near a (or all) player or coordinate\n cpm-teleportplayerhome teleportplayerhome teleh => teleport a player to his home (on bedroll)\n cpm-tp2bag tp2bag teleport2bag => Teleport player to his/her backpack after death.\n cpm-tprotect tprotect => Set protection to a location in same way as trader.\n cpm-traderlist traderlist => List Trader Areas\n cpm-unlockall unlockall => unlock all secure loots, chests and doors for the current player.\n cpm-w2l w2l => Write to console.\n cpm-wi wi wipeinventory => Reset a player\'s inventory completely (bag, belt and equipment).\n cpm-wlf wlf => Adds all friends of a player to whitelist(s) of their claim(s)\n cpm-wpc wpc => Manage CPM waypoints\n creativemenu cm => enables/disables the creativemenu\n debuff => Removes a buff from the local player\n debuffplayer => Remove a buff from a player\n debugmenu dm => enables/disables the debugmenu \n debugshot dbs => Lets you make a screenshot that will have some generic info\non it and a custom text you can enter. Also stores a list\nof your current perk levels in a CSV file next to it.\n debugweather => Dumps internal weather state to the console.\n decomgr => \n dms => Gives control over Dynamic Music functionality.\n dof => Control DOF\n enablerendering => enable/disable live map rendering\n enablescope es => toggle debug scope\n exhausted => Makes the player exhausted.\n exportcurrentconfigs => Exports the current game config XMLs\n exportprefab => Exports a prefab from a world area\n floatingorigin fo => \n fov => Camera field of view\n gamestage => usage: gamestage - displays the gamestage of the local player.\n getgamepref gg => Gets game preferences\n getgamestat ggs => Gets game stats\n getoptions => Gets game options\n gettime gt => Get the current game time\n gfx => Graphics commands\n give => give an item to a player (entity id or name)\n givequest => usage: givequest questname\n giveself => usage: giveself itemName [qualityLevel=6] [count=1] [putInInventory=false] [spawnWithMods=true]\n giveselfxp => usage: giveselfxp 10000\n help => Help on console and specific commands\n kick => Kicks user with optional reason. "kick playername reason"\n kickall => Kicks all users with optional reason. "kickall reason"\n kill => Kill a given entity\n killall => Kill all entities\n lgo listgameobjects => List all active game objects\n lights => Debug views to optimize lights\n listents le => lists all entities\n listitems li => lists all items that contain the given substring\n listknownplayers lkp => lists all players that were ever online\n listlandprotection llp => lists all land protection blocks and owners\n listplayerids lpi => Lists all players with their IDs for ingame commands\n listplayers lp => lists all players\n listthreads lt => lists all threads\n loggamestate lgs => Log the current state of the game\n loglevel => Telnet/Web only: Select which types of log messages are shown\n mem => Prints memory information and unloads resources or changes garbage collector\n memcl => Prints memory information on client and calls garbage collector\n occlusion => Control OcclusionManager\n openiddebug => enable/disable OpenID debugging\n pirs => tbd\n pois => Switches distant POIs on/off\n pplist => Lists all PersistentPlayer data\n prefab => \n prefabupdater => \n profilenetwork => Writes network profiling information\n profiling => Enable Unity profiling for 300 frames\n reloadwebpermissions => force reload of web permissions file\n removelandprotection rlp => removes the association of a land protection block to the owner\n removequest => usage: removequest questname\n rendermap => render the current map to a file\n repairchunkdensity rcd => check and optionally fix densities of a chunk\n reply re => send a message to the player who last sent you a PM\n saveworld sa => Saves the world manually.\n say => Sends a message to all connected clients\n sayplayer pm => send a message to a single player\n ScreenEffect => Sets a screen effect\n setgamepref sg => sets a game pref\n setgamestat sgs => sets a game stat\n settargetfps => Set the target FPS the game should run at (upper limit)\n settempunit stu => Set the current temperature units.\n settime st => Set the current game time\n show => Shows custom layers of rendering.\n showalbedo albedo => enables/disables display of albedo in gBuffer\n showchunkdata sc => shows some date of the current chunk\n showClouds => Artist command to show one layer of clouds.\n showhits => Show hit entity locations\n showinventory si => list inventory of a given player\n shownexthordetime => Displays the wandering horde time\n shownormals norms => enables/disables display of normal maps in gBuffer\n showspecular spec => enables/disables display of specular values in gBuffer\n showswings => Show melee swing arc rays\n shutdown => shuts down the game\n sleeper => Show sleeper info\n smoothworldall swa => Applies some batched smoothing commands.\n sounddebug => Toggles SoundManager debug output.\n spawnairdrop => Spawns an air drop\n spawnentity se => spawns an entity\n spawnentityat sea => Spawns an entity at a give position\n spawnscouts => Spawns zombie scouts\n SpawnScreen => Display SpawnScreen\n spawnsupplycrate => Spawns a supply crate where the player is\n spawnwanderinghorde spawnwh => Spawns a wandering horde of zombies\n spectator spectatormode sm => enables/disables spectator mode\n spectrum => Force a particular lighting spectrum.\n stab => stability\n starve hungry food => Makes the player starve (optionally specify the amount of food you want to have in percent).\n switchview sv => Switch between fpv and tpv\n SystemInfo => List SystemInfo\n teleport tp => Teleport the local player\n teleportplayer tele => Teleport a given player\n thirsty water => Makes the player thirsty (optionally specify the amount of water you want to have in percent).\n traderarea => ...\n trees => Switches trees on/off\n updatelighton => Commands for UpdateLightOnAllMaterials and UpdateLightOnPlayers\n version => Get the currently running version of the game and loaded mods\n visitmap => Visit an given area of the map. Optionally run the density check on each visited chunk.\n water => Control water settings\n weather => Control weather settings\n weathersurvival => Enables/disables weather survival\n webpermission => Manage web permission levels\n webstat => DEBUG PURPOSES ONLY\n webtokens => Manage web tokens\n whitelist => Manage whitelist entries\n wsmats workstationmaterials => Set material counts on workstations.\n xui => Execute XUi operations\n xuireload => Access xui related functions such as reinitializing a window group, opening a window group\n zip => Control zipline settings\n', + }, + }, +} \ No newline at end of file