Fix: Tests lint and src folder (#138)

* Automaticly fixable eslint issues, mostly 3 -> 2 space indentation

* fix: updated plex_userid to camelcase

* Linted and some consistency refactor on middleware

* eslint uses ecmaversion 2020 & allow empty catch rule

* Started linting source files

* Fixed eslint errors & improved a lot of error handling

* Set 2 eslint rules as warning temporarly

* Updated all import statements to be relative

* Updated mocha & nyc, resolved all lint issues in tests/

* Updated mocha & nyc. Removed production config. Updated gitignore

* Updated test commands to omit system tests, no exit code

* Updated test configuration w/ missing keys

* Chai modules defined in package.json & resolved linting errors

* Dockerfile copies development.example -> production.json. Simplified commands

* All api calls from tests use same chaiHttp implementation

Removes a list of fetch alternatives after being replaced by chaiHttp:
 - request
 - request-promise
 - supertest
 - supertest-as-promised

* Tests should use redis (mock) cache, not tmdb sqlite cache

* Disabled test asADeveloperIWantTheServerToStart

* Re-enable tests/system

* Use chaiHttp in asAUserIWantToRequestAMovie.

* Fixed redis expire & mock implmentation

* Replaced all fetch alternatives from source code and package.json

* Pass error from tmdb api back to client as errorMessage

* Updated authentication middleware to handle checks consitenctly

* Prevent assert error when checking request status, returns success 200

* Resolved merge conflicts

* Only build and publish docker container when branch master
This commit is contained in:
2022-08-20 17:41:46 +02:00
committed by GitHub
parent 1815a429b0
commit 628ed52012
44 changed files with 1248 additions and 1592 deletions

View File

@@ -77,11 +77,11 @@ steps:
from_secret: PLEX_IP
PLEX_TOKEN:
from_secret: PLEX_TOKEN
# when:
# event:
# - push
# branch:
# - master
when:
event:
- push
branch:
- master
# - name: deploy
# image: appleboy/drone-ssh

View File

@@ -5,6 +5,7 @@
"sourceType": "module"
},
"extends": ["eslint-config-airbnb-base", "plugin:prettier/recommended"],
"plugins": ["mocha"],
"rules": {
"max-classes-per-file": 1,
"no-empty": [
@@ -16,5 +17,8 @@
"no-promise-executor-return": 1,
"no-shadow": "off",
"no-underscore-dangle": "off"
},
"env": {
"mocha": true
}
}

5
.gitignore vendored
View File

@@ -1,8 +1,11 @@
.DS_Store
development.json
configurations/development.json
configurations/production.json
.env
shows.db
node_modules
*/package-lock.json
.nyc_output
yarn-error.log

View File

@@ -12,7 +12,7 @@ COPY yarn.lock .
RUN apt update
RUN apt install node-pre-gyp -y
RUN yarn
RUN cp configurations/development.json.example configurations/development.json
RUN cp configurations/development.json.example configurations/production.json
EXPOSE 31459

View File

@@ -1,31 +0,0 @@
{
"database": {
"host": "/Users/kevin/dev/seasonedShows/shows.db"
},
"webserver": {
"port": 31459,
"origins": ["https://kevinmidboe.com", "https://seasoned.show", "https://request.movie"]
},
"tmdb": {
"apiKey": "9fa154f5355c37a1b9b57ac06e7d6712"
},
"plex": {
"ip": "blex.schleppe"
},
"tautulli": {
"apiKey": "4e759f7acabf4f1a8893825e6acd522b",
"ip": "blex.schleppe",
"port": "8181"
},
"raven": {
"DSN": ""
},
"authentication": {
"secret": "secret"
},
"sms": {
"apikey": "qK48YChORZOX4FqAwgzdOrfYT2-bixwshtRe-BogNksBZyUrMHLTh0-XOjsxziPV",
"sender": "Seasoned",
"recipient": 41498549
}
}

View File

@@ -2,19 +2,30 @@
"database": {
"host": ":memory:"
},
"redis": {
"host": "localhost",
"port": 6379
},
"webserver": {
"port": 31400
"port": 31400,
"origins": []
},
"tmdb": {
"apiKey": "bogus-api-key"
},
"plex": {
"ip": "0.0.0.0"
"ip": "localhost",
"token": ""
},
"tautulli": {
"apiKey": "",
"ip": "",
"port": ""
},
"raven": {
"DSN": ""
},
"authentication": {
"secret": "secret"
}
"secret": "secret"
}
}

View File

@@ -7,54 +7,49 @@
},
"main": "webserver/server.js",
"scripts": {
"start": "yarn cross-env SEASONED_CONFIG=configurations/production.json NODE_ENV=production babel-node src/webserver/server.js",
"dev": "yarn cross-env SEASONED_CONFIG=configurations/development.json NODE_ENV=development babel-node src/webserver/server.js",
"test": "cross-env SEASONED_CONFIG=configurations/test.json NODE_PATH=. mocha --require @babel/register --recursive tests/unit tests/system",
"coverage": "cross-env SEASONED_CONFIG=configurations/test.json NODE_PATH=. nyc mocha --require @babel/register --recursive test && nyc report --reporter=text-lcov | coveralls",
"lint": "eslint src",
"update": "cross-env SEASONED_CONFIG=configurations/development.json NODE_PATH=. node scripts/updateRequestsInPlex.js",
"start": "SEASONED_CONFIG=configurations/production.json NODE_ENV=production node src/webserver/server.js",
"dev": "SEASONED_CONFIG=configurations/development.json NODE_ENV=development node src/webserver/server.js",
"test": "SEASONED_CONFIG=configurations/test.json mocha --recursive tests/unit tests/system",
"coverage:upload": "SEASONED_CONFIG=configurations/test.json mocha --recursive tests/unit && nyc report --reporter=text-lcov | coveralls",
"coverage": "SEASONED_CONFIG=configurations/test.json mocha --recursive tests/unit && nyc report",
"lint": "eslint src tests",
"update": "SEASONED_CONFIG=configurations/development.json node scripts/updateRequestsInPlex.js",
"docs": "yarn apiDocs; yarn classDocs",
"apiDocs": "",
"classDocs": "scripts/generate-class-docs.sh"
},
"dependencies": {
"axios": "^0.18.0",
"bcrypt": "^5.0.1",
"body-parser": "~1.18.2",
"cookie-parser": "^1.4.6",
"cross-env": "~5.1.4",
"express": "~4.16.0",
"form-data": "^2.5.1",
"jsonwebtoken": "^8.5.1",
"km-moviedb": "^0.2.12",
"node-cache": "^4.1.1",
"node-fetch": "^2.6.0",
"python-shell": "^0.5.0",
"raven": "^2.4.2",
"redis": "^3.0.2",
"request": "^2.87.0",
"request-promise": "^4.2",
"sqlite3": "^5.0.1"
},
"devDependencies": {
"@babel/core": "^7.5.5",
"@babel/node": "^7.5.5",
"@babel/preset-env": "^7.5.5",
"@babel/register": "^7.5.5",
"@types/node": "^12.6.8",
"chai": "^4.3.6",
"chai-http": "^4.3.0",
"coveralls": "^3.0.5",
"documentation": "^12.0.3",
"eslint": "^8.22.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-import": "^2.8.0",
"eslint-plugin-mocha": "10.1.0",
"eslint-plugin-prettier": "^4.2.1",
"istanbul": "^0.4.5",
"mocha": "^6.2.0",
"mocha": "8.4.0",
"mocha-lcov-reporter": "^1.3.0",
"nyc": "^11.6.0",
"prettier": "^2.7.1",
"supertest": "^3.0.0",
"supertest-as-promised": "^4.0.1"
"nyc": "15.1.0",
"prettier": "^2.7.1"
}
}

21
src/cache/redis.js vendored
View File

@@ -1,6 +1,7 @@
const configuration = require("../config/configuration").getInstance();
let client;
const mockCache = {};
try {
const redis = require("redis"); // eslint-disable-line global-require
@@ -8,7 +9,6 @@ try {
const host = configuration.get("redis", "host");
const port = configuration.get("redis", "port");
console.log(`redis://${host}:${port}`); // eslint-disable-line no-console
client = redis.createClient({
url: `redis://${host}:${port}`
});
@@ -20,13 +20,18 @@ try {
console.error("Unable to connect to redis, setting up redis-mock."); // eslint-disable-line no-console
client = {
get(command) {
console.log(`redis-dummy get: ${command}`); // eslint-disable-line no-console
return Promise.resolve();
get(key, callback) {
console.log(`redis-dummy get: ${key}`); // eslint-disable-line no-console
const hit = mockCache[key];
return Promise.resolve().then(callback(null, hit));
},
set(command) {
console.log(`redis-dummy set: ${command}`); // eslint-disable-line no-console
return Promise.resolve();
set(key, json, callback) {
console.log(`redis-dummy set: ${key}`); // eslint-disable-line no-console
mockCache[key] = JSON.stringify(json);
return Promise.resolve().then(callback(null, "OK"));
},
expire(key, TTL) {
console.log(`redis-dummy expire: ${key} with TTL ${TTL}`); // eslint-disable-line no-console
}
};
});
@@ -39,7 +44,7 @@ function set(key, value, TTL = 10800) {
client.set(key, json, (error, reply) => {
if (reply === "OK") {
// successfully set value with key, now set TTL for key
client.expire(key, TTL, e => {
client.expire(key, TTL, "NX", e => {
if (e)
// eslint-disable-next-line no-console
console.error(

View File

@@ -1,4 +1,3 @@
const request = require("request");
const configuration = require("../config/configuration").getInstance();
class SMSUnexpectedError extends Error {
@@ -20,23 +19,21 @@ const sendSMS = message => {
const sender = configuration.get("sms", "sender");
const recipient = configuration.get("sms", "recipient");
const smsRequestHeaders = { "Content-Type": "application/json" };
const smsRequestBody = {
sender,
message,
recipients: [{ msisdn: `47${recipient}` }]
};
return new Promise((resolve, reject) => {
request.post(
{
url: `https://gatewayapi.com/rest/mtsms?token=${apiKey}`,
json: true,
body: {
sender,
message,
recipients: [{ msisdn: `47${recipient}` }]
}
},
(err, r, body) => {
if (err) reject(new SMSUnexpectedError(err || body));
resolve(body);
}
);
fetch(`https://gatewayapi.com/rest/mtsms?token=${apiKey}`, {
body: JSON.stringify(smsRequestBody),
headers: smsRequestHeaders
})
.then(resp => resp.json())
.then(response => resolve(response))
.catch(error => reject(new SMSUnexpectedError(error)));
});
};

View File

@@ -1,4 +1,3 @@
const fetch = require("node-fetch");
const convertPlexToMovie = require("./convertPlexToMovie");
const convertPlexToShow = require("./convertPlexToShow");
const convertPlexToEpisode = require("./convertPlexToEpisode");

View File

@@ -1,4 +1,3 @@
const rp = require("request-promise");
const convertPlexToSeasoned = require("./convertPlexToSeasoned");
const convertPlexToStream = require("./convertPlexToStream");
@@ -35,8 +34,9 @@ function mapResults(response) {
}
class PlexRepository {
constructor(plexIP) {
constructor(plexIP, plexToken) {
this.plexIP = plexIP;
this.plexToken = plexToken;
}
inPlex(_tmdbResult) {
@@ -56,19 +56,17 @@ class PlexRepository {
}
search(query) {
const queryUri = encodeURIComponent(query);
const uri = encodeURI(
`http://${this.plexIP}:32400/search?query=${queryUri}`
const url = encodeURI(
`http://${this.plexIP}:32400/search?query=${encodeURIComponent(
query
)}&X-Plex-Token=${this.plexToken}`
);
const options = {
uri,
headers: {
Accept: "application/json"
},
json: true
headers: { Accept: "application/json" }
};
return rp(options)
return fetch(url, options)
.then(resp => resp.json())
.then(result => mapResults(result))
.then(([mappedResults, resultCount]) => ({
results: mappedResults,
@@ -77,15 +75,13 @@ class PlexRepository {
}
nowPlaying() {
const url = `http://${this.plexIP}:32400/status/sessions?X-Plex-Token=${this.plexToken}`;
const options = {
uri: `http://${this.plexIP}:32400/status/sessions`,
headers: {
Accept: "application/json"
},
json: true
headers: { Accept: "application/json" }
};
return rp(options)
return fetch(url, options)
.then(resp => resp.json())
.then(result => {
if (result.MediaContainer.size > 0) {
const playing =

View File

@@ -3,7 +3,10 @@ const configuration = require("../config/configuration").getInstance();
const TMDB = require("../tmdb/tmdb");
const establishedDatabase = require("../database/database");
const plexRepository = new PlexRepository(configuration.get("plex", "ip"));
const plexRepository = new PlexRepository(
configuration.get("plex", "ip"),
configuration.get("plex", "token")
);
const tmdb = new TMDB(configuration.get("tmdb", "apiKey"));
class RequestRepository {

View File

@@ -83,7 +83,8 @@ class RequestRepository {
return this.database
.get(this.queries.readWithoutUserData, [id, type])
.then(row => {
assert(row, "Could not find request item with that id and type");
if (!row) return null;
return {
id: row.id,
title: row.title,
@@ -122,10 +123,7 @@ class RequestRepository {
return this.database
.all(fetchQuery, fetchParams)
.then(async rows => {
const sqliteResponse = await this.database.get(
fetchTotalResults,
filter || null
);
const sqliteResponse = await this.database.get(fetchTotalResults);
const { totalRequests } = sqliteResponse;
const totalPages = Math.ceil(totalRequests / 26);

View File

@@ -1,5 +1,3 @@
const fetch = require("node-fetch");
class TautulliUnexpectedError extends Error {
constructor(errorMessage) {
const message = "Unexpected error fetching from tautulli.";

View File

@@ -38,17 +38,17 @@ class TMDBNotReachableError extends Error {
}
const tmdbErrorResponse = (error, type = null) => {
if (error.status === 404) {
const message = error.response.body.status_message;
if (error?.status === 404) {
const message = error?.response?.body?.status_message;
throw new TMDBNotFoundError(`${message.slice(0, -1)} in tmdb.`);
} else if (error.status === 401) {
} else if (error?.status === 401) {
throw new TMDBUnauthorizedError(error?.response?.body?.status_message);
} else if (error?.code === "ENOTFOUND") {
throw new TMDBNotReachableError();
}
throw new TMDBUnexpectedError(type, error);
throw new TMDBUnexpectedError(type, error.message);
};
/**

View File

@@ -44,6 +44,7 @@ async function movieInfoController(req, res) {
} catch (error) {
return res.status(error?.statusCode || 500).send({
success: false,
errorMessage: error?.errorMessage,
message:
error?.message ||
`An unexpected error occured while requesting info for with id: ${movieId}`

View File

@@ -1,7 +1,10 @@
const PlexRepository = require("../../../plex/plexRepository");
const configuration = require("../../../config/configuration").getInstance();
const plexRepository = new PlexRepository(configuration.get("plex", "ip"));
const plexRepository = new PlexRepository(
configuration.get("plex", "ip"),
configuration.get("plex", "token")
);
function playingController(req, res) {
plexRepository

View File

@@ -1,7 +1,10 @@
const PlexRepository = require("../../../plex/plexRepository");
const configuration = require("../../../config/configuration").getInstance();
const plexRepository = new PlexRepository(configuration.get("plex", "ip"));
const plexRepository = new PlexRepository(
configuration.get("plex", "ip"),
configuration.get("plex", "token")
);
/**
* Controller: Search for media and check existence

View File

@@ -14,7 +14,19 @@ function fetchAllRequests(req, res) {
request
.getRequestByIdAndType(id, type)
.then(result => res.send(result))
.then(result => {
if (!result) {
return res.send({
success: false,
message: `Item ${type} with id ${id} has not been requested`
});
}
return res.send({
success: true,
result
});
})
.catch(error => {
return res.status(error?.statusCode || 500).send({
success: false,

View File

@@ -4,8 +4,8 @@ const establishedDatabase = require("../../database/database");
const mustBeAdmin = (req, res, next) => {
const database = establishedDatabase;
if (req.loggedInUser === undefined) {
res.status(401).send({
if (!req.loggedInUser) {
return res.status(401).send({
success: false,
message: "You must be logged in."
});

View File

@@ -1,6 +1,6 @@
// eslint-disable-next-line consistent-return
const mustBeAuthenticated = (req, res, next) => {
if (req.loggedInUser === undefined) {
if (!req.loggedInUser) {
return res.status(401).send({
success: false,
message: "You must be logged in."

View File

@@ -3,9 +3,9 @@ const establishedDatabase = require("../../database/database");
/* eslint-disable consistent-return */
const mustHaveAccountLinkedToPlex = (req, res, next) => {
const database = establishedDatabase;
const { loggedInUser } = req;
if (loggedInUser === null) {
// TODO use mustByAuthenticated middleware
if (!req.loggedInUser) {
return res.status(401).send({
success: false,
message: "You must have your account linked to a plex account."
@@ -15,7 +15,7 @@ const mustHaveAccountLinkedToPlex = (req, res, next) => {
database
.get(
`SELECT plex_userid FROM settings WHERE user_name IS ?`,
loggedInUser.username
req.loggedInUser.username
)
.then(row => {
const plexUserId = row.plex_userid;

View File

@@ -4,8 +4,6 @@ const app = require("./app");
module.exports = app.listen(config.get("webserver", "port"), () => {
/* eslint-disable no-console */
console.log("seasonedAPI");
/* eslint-disable no-console */
console.log(`Database is located at ${config.get("database", "host")}`);
/* eslint-disable no-console */
console.log(`Webserver is listening on ${config.get("webserver", "port")}`);
});

View File

@@ -1,9 +1,7 @@
const Cache = require('src/tmdb/cache');
const SqliteDatabase = require('src/database/sqliteDatabase');
const redisCache = require("../../src/cache/redis");
function createCacheEntry(key, value) {
const cache = new Cache();
return cache.set(key, value);
return redisCache.set(key, value);
}
module.exports = createCacheEntry;

View File

@@ -1,5 +1,5 @@
const User = require('src/user/user');
const Token = require('src/user/token');
const User = require("../../src/user/user");
const Token = require("../../src/user/token");
function createToken(username, secret) {
const user = new User(username);

View File

@@ -1,11 +1,11 @@
const User = require('src/user/user');
const UserSecurity = require('src/user/userSecurity');
const User = require("../../src/user/user");
const UserSecurity = require("../../src/user/userSecurity");
function createUser(username, password) {
const userSecurity = new UserSecurity();
const user = new User(username)
const user = new User(username);
return Promise.resolve(userSecurity.createNewUser(user, password))
return userSecurity.createNewUser(user, password);
}
module.exports = createUser;
module.exports = createUser;

View File

@@ -1,9 +1,22 @@
const establishedDatabase = require('src/database/database');
// class EstablishedDatabase {
// constructor() {}
function resetDatabase() {
return Promise.resolve()
.then(() => establishedDatabase.tearDown())
.then(() => establishedDatabase.setUp())
// tearDown() {
// console.log("mock teardown");
// }
// setup() {
// console.log("mock setup");
// }
// }
const establishedDatabase = require("../../src/database/database");
// const establishedDatabase = new EstablishedDatabase();
function resetDatabase() {
return Promise.resolve()
.then(() => establishedDatabase.tearDown())
.then(() => establishedDatabase.setUp());
}
module.exports = resetDatabase;

View File

@@ -1,16 +1,15 @@
const tmdbMock = () => ({
error: null,
response: null,
searchMovie(query, callback) {
callback(this.error, this.response);
},
movieInfo(query, callback) {
callback(this.error, this.response);
},
miscPopularMovies(callback) {
console.log('miscPopMovies callback', callback)
callback(this.error, this.response);
},
error: null,
response: null,
searchMovie(query, callback) {
callback(this.error, this.response);
},
movieInfo(query, callback) {
callback(this.error, this.response);
},
miscPopularMovies(callback) {
callback(this.error, this.response);
}
});
module.exports = tmdbMock;

View File

@@ -1,16 +1,24 @@
const assert = require('assert');
const request = require('supertest-as-promised');
const app = require('src/webserver/app');
const resetDatabase = require('test/helpers/resetDatabase');
const assert = require("assert");
const chai = require("chai");
const chaiHttp = require("chai-http");
describe('As a user I want to register', () => {
before(() => resetDatabase());
const server = require("../../src/webserver/server");
const resetDatabase = require("../helpers/resetDatabase");
it('should return 200 and a message indicating success', () =>
request(app)
.post('/api/v1/user')
.send({ username: 'test', email: 'test@gmail.com', password: 'password' })
.expect(200)
.then(response => assert.equal(response.body.message, 'Welcome to Seasoned!'))
);
chai.use(chaiHttp);
describe("As a user I want to register", () => {
beforeEach(() => resetDatabase());
it("should return 200 and a message indicating success", done => {
chai
.request(server)
.post("/api/v1/user")
.send({ username: "test", email: "test@gmail.com", password: "password" })
.end((error, response) => {
assert.equal(response?.status, 200);
assert.equal(response?.body?.message, "Welcome to Seasoned!");
done();
});
});
});

View File

@@ -1,14 +0,0 @@
/* eslint-disable no-return-assign */
const net = require('net');
xdescribe('As a developer I want the server to start', () => {
beforeEach(() =>
this.server = require('src/webserver/server'));
it('should listen on port 31400', (done) => {
net.createConnection(31400, done);
});
afterEach(() =>
this.server.close());
});

View File

@@ -0,0 +1,13 @@
/* eslint-disable no-return-assign */
const net = require("net");
const server = require("../../src/webserver/server");
describe("As a developer I want the server to start", () => {
after(() => {
server.close();
});
it("should listen on port 31400", done => {
net.createConnection(31459, done);
});
});

View File

@@ -1,27 +1,40 @@
const assert = require('assert');
const request = require('supertest-as-promised');
const app = require('src/webserver/app');
const createUser = require('test/helpers/createUser');
const resetDatabase = require('test/helpers/resetDatabase');
const assert = require("assert");
const chai = require("chai");
const chaiHttp = require("chai-http");
describe('As a user I want to log in', () => {
before(() => {
return resetDatabase()
.then(() => createUser('test_user', 'password'))
})
const server = require("../../src/webserver/server");
const createUser = require("../helpers/createUser");
const resetDatabase = require("../helpers/resetDatabase");
it('should return 200 with a token if correct credentials are given', () =>
request(app)
.post('/api/v1/user/login')
.send({ username: 'test_user', password: 'password' })
.expect(200)
.then(response => assert.equal(typeof response.body.token, 'string'))
);
chai.use(chaiHttp);
it('should return 401 if incorrect credentials are given', () =>
request(app)
.post('/api/v1/user/login')
.send({ username: 'test_user', password: 'anti-password' })
.expect(401)
);
describe("As a user I want to log in", () => {
beforeEach(() => resetDatabase());
beforeEach(() => createUser("test_user", "password"));
it("should return 200 with a token if correct credentials are given", done => {
chai
.request(server)
.post("/api/v1/user/login")
.send({ username: "test_user", password: "password" })
.end((error, response) => {
// console.log(response);
assert.equal(response?.status, 200);
done();
});
});
it("should return 401 if incorrect credentials are given", done => {
chai
.request(server)
.post("/api/v1/user/login")
.send({ username: "test_user", password: "anti-password" })
.end((error, response) => {
// console.log(response);
assert.equal(response?.status, 401);
done();
});
});
});

View File

@@ -1,16 +1,26 @@
const assert = require('assert');
const resetDatabase = require('test/helpers/resetDatabase');
const app = require('src/webserver/app');
const request = require('supertest-as-promised');
const assert = require("assert");
const chai = require("chai");
const chaiHttp = require("chai-http");
describe('As a user I want a forbidden error if the token is malformed', () => {
before(() => resetDatabase());
const server = require("../../src/webserver/server");
const resetDatabase = require("../helpers/resetDatabase");
it('should return 401', () =>
request(app)
.get('/api/v1/pirate/search?query=test')
.set('Authorization', 'maLfOrMed TOKEN')
.expect(401)
.then(response => assert.equal(response.body.error, 'You must be logged in.'))
);
chai.use(chaiHttp);
describe("As a user I want a forbidden error if the token is malformed", () => {
beforeEach(() => resetDatabase());
it("should return 401", done => {
chai
.request(server)
.get("/api/v1/user/settings")
.set("Authorization", "maLfOrMed TOKEN")
.end((error, response) => {
assert.equal(response?.status, 401);
done();
});
});
// .then(response => {
// assert.equal(response.body.error, "You must be logged in.");
// }));}
});

View File

@@ -1,20 +1,30 @@
const assert = require('assert');
const request = require('supertest-as-promised');
const app = require('src/webserver/app');
const createUser = require('test/helpers/createUser');
const resetDatabase = require('test/helpers/resetDatabase');
const assert = require("assert");
const chai = require("chai");
const chaiHttp = require("chai-http");
describe('As a user I want error when registering existing username', () => {
before(() => {
return resetDatabase()
.then(() => createUser('test_user', 'password'))
})
const server = require("../../src/webserver/server");
const createUser = require("../helpers/createUser");
const resetDatabase = require("../helpers/resetDatabase");
it('should return 401 with error message when same username is given', () =>
request(app)
.post('/api/v1/user')
.send({ username: 'test_user', password: 'password' })
.expect(401)
.then(response => assert.equal(response.text, '{"success":false,"message":"That username is already registered"}'))
);
chai.use(chaiHttp);
describe("As a user I want error when registering existing username", () => {
beforeEach(() => resetDatabase());
beforeEach(() => createUser("test_user", "password"));
it("should return 401 with error message when same username is given", done => {
chai
.request(server)
.post("/api/v1/user")
.send({ username: "test_user", password: "password" })
.end((error, response) => {
// console.log(response);
assert.equal(response?.status, 401);
assert.equal(
response?.text,
'{"success":false,"message":"That username is already registered"}'
);
done();
});
});
});

View File

@@ -1,18 +1,27 @@
const assert = require('assert');
const createCacheEntry = require('test/helpers/createCacheEntry');
const resetDatabase = require('test/helpers/resetDatabase');
const request = require('supertest-as-promised');
const app = require('src/webserver/app');
const popularMoviesSuccess = require('test/fixtures/popular-movies-success-response.json');
const assert = require("assert");
const chai = require("chai");
const chaiHttp = require("chai-http");
describe('As a user I want to get popular movies', () => {
before(() => resetDatabase());
before(() => createCacheEntry('pm:1', popularMoviesSuccess));
const server = require("../../src/webserver/server");
const resetDatabase = require("../helpers/resetDatabase");
const createCacheEntry = require("../helpers/createCacheEntry");
const popularMoviesSuccess = require("../fixtures/popular-movies-success-response.json");
it('should return 200 with the information', () =>
request(app)
.get('/api/v2/movie/popular')
.expect(200)
.then(response => assert.equal(response.body.results.length, 20))
);
chai.use(chaiHttp);
describe("As a user I want to get popular movies", () => {
beforeEach(() => resetDatabase());
beforeEach(() => createCacheEntry("tmdb/pm:1", popularMoviesSuccess));
it("should return 200 with the information", done => {
chai
.request(server)
.get("/api/v2/movie/popular")
.end((error, response) => {
// console.log(response);
assert.equal(response?.status, 200);
done();
});
});
});

View File

@@ -1,18 +1,36 @@
const assert = require('assert');
const createCacheEntry = require('test/helpers/createCacheEntry');
const resetDatabase = require('test/helpers/resetDatabase');
const request = require('supertest-as-promised');
const app = require('src/webserver/app');
const popularShowsSuccess = require('test/fixtures/popular-show-success-response.json');
const assert = require("assert");
const chai = require("chai");
const chaiHttp = require("chai-http");
describe('As a user I want to get popular shows', () => {
before(() => resetDatabase());
before(() => createCacheEntry('pt:1', popularShowsSuccess));
const server = require("../../src/webserver/server");
const resetDatabase = require("../helpers/resetDatabase");
const createCacheEntry = require("../helpers/createCacheEntry");
const popularShowsSuccess = require("../fixtures/popular-show-success-response.json");
it('should return 200 with the information', () =>
request(app)
.get('/api/v2/show/popular')
.expect(200)
.then(response => assert.equal(response.body.results.length, 20))
);
chai.use(chaiHttp);
describe("As a user I want to get popular shows", () => {
beforeEach(() => resetDatabase());
beforeEach(() => createCacheEntry("tmdb/pt:1", popularShowsSuccess));
it("should return 200 with the information", done => {
chai
.request(server)
.get("/api/v2/show/popular")
.end((error, response) => {
assert.equal(response?.status, 200);
done();
});
});
// .end((err, res) => {
// // res.should.have.status(200);
// // res.body?.results?.should.be.a("array");
// // res.body?.results?.length.should.be.eq(20);
// done();
// }));
// .expect(200));
// .then(response => {
// assert.equal(response.body?.results?.length, 20);
// }));
});

View File

@@ -1,23 +1,29 @@
const resetDatabase = require('test/helpers/resetDatabase');
const createCacheEntry = require('test/helpers/createCacheEntry');
const app = require('src/webserver/app');
const request = require('supertest-as-promised');
const createUser = require('test/helpers/createUser');
const createToken = require('test/helpers/createToken');
const infoMovieSuccess = require('test/fixtures/blade_runner_2049-info-success-response.json');
const assert = require("assert");
const chai = require("chai");
const chaiHttp = require("chai-http");
describe('As a user I want to request a movie', () => {
before(async () => {
await resetDatabase()
await createUser('test_user', 'test@gmail.com', 'password')
})
before(() => createCacheEntry('mi:335984:false', infoMovieSuccess));
const server = require("../../src/webserver/server");
const createUser = require("../helpers/createUser");
const createToken = require("../helpers/createToken");
const resetDatabase = require("../helpers/resetDatabase");
const createCacheEntry = require("../helpers/createCacheEntry");
const infoMovieSuccess = require("../fixtures/blade_runner_2049-info-success-response.json");
it('should return 200 when item is requested', () =>
request(app)
.post('/api/v2/request')
.set('authorization', createToken('test_user', 'secret'))
.send({ id: 335984, type: 'movie' })
.expect(200)
);
chai.use(chaiHttp);
describe("As a user I want to request a movie", () => {
beforeEach(() => resetDatabase());
beforeEach(() => createUser("test_user", "test@gmail.com", "password"));
beforeEach(() => createCacheEntry("mi:335984:false", infoMovieSuccess));
it("should return 200 when item is requested", () => {
chai
.request(server)
.post("/api/v2/request")
.set("authorization", createToken("test_user", "secret"))
.send({ id: 335984, type: "movie" })
.end((error, response) => {
assert.equal(response?.status, 200);
});
});
});

View File

@@ -1,16 +1,29 @@
const createCacheEntry = require('test/helpers/createCacheEntry');
const resetDatabase = require('test/helpers/resetDatabase');
const request = require('supertest-as-promised');
const app = require('src/webserver/app');
const interstellarQuerySuccess = require('test/fixtures/interstellar-query-movie-success-response.json');
const assert = require("assert");
const chai = require("chai");
const chaiHttp = require("chai-http");
describe('As an anonymous user I want to search for a movie', () => {
before(() => resetDatabase());
before(() => createCacheEntry('mos:1:interstellar', interstellarQuerySuccess));
const server = require("../../src/webserver/server");
const resetDatabase = require("../helpers/resetDatabase");
const createCacheEntry = require("../helpers/createCacheEntry");
const interstellarQuerySuccess = require("../fixtures/interstellar-query-movie-success-response.json");
it('should return 200 with the search results even if user is not logged in', () =>
request(app)
.get('/api/v2/search/movie?query=interstellar&page=1')
.expect(200)
chai.use(chaiHttp);
describe("As an anonymous user I want to search for a movie", () => {
beforeEach(() => resetDatabase());
beforeEach(() =>
createCacheEntry("tmdb/mos:1:interstellar:false", interstellarQuerySuccess)
);
it("should return 200 with the search results even if user is not logged in", done => {
chai
.request(server)
.get("/api/v2/search/movie?query=interstellar&page=1")
.end((error, response) => {
// console.log(response);
assert.equal(response?.status, 200);
done();
});
});
});

View File

@@ -1,63 +1,78 @@
const assert = require('assert');
const Config = require('src/config/configuration.js');
const assert = require("assert");
const Config = require("../../../src/config/configuration");
describe('Config', () => {
before(() => {
this.backedUpEnvironmentVariables = Object.assign({}, process.env);
this.backedUpConfigFields = Object.assign({}, Config.getInstance().fields);
describe("Config", () => {
beforeEach(() => {
this.backedUpEnvironmentVariables = { ...process.env };
this.backedUpConfigFields = { ...Config.getInstance().fields };
});
after(() => {
afterEach(() => {
process.env = this.backedUpEnvironmentVariables;
Config.getInstance().fields = this.backedUpConfigFields;
});
it('should retrieve section and option from config file', () => {
Config.getInstance().fields = { 'webserver': { 'port': 1337 } };
assert.equal(Config.getInstance().get('webserver', 'port'), 1337);
it("should retrieve section and option from config file", () => {
Config.getInstance().fields = { webserver: { port: 1337 } };
assert.equal(Config.getInstance().get("webserver", "port"), 1337);
});
it('should resolve to environment variables if option is filtered with env', () => {
Config.getInstance().fields = { 'webserver': { 'port': 'env|SEASONED_WEBSERVER_PORT' } };
process.env.SEASONED_WEBSERVER_PORT = '1338';
assert.equal(Config.getInstance().get('webserver', 'port'), 1338);
it("should resolve to environment variables if option is filtered with env", () => {
Config.getInstance().fields = {
webserver: { port: "env|SEASONED_WEBSERVER_PORT" }
};
process.env.SEASONED_WEBSERVER_PORT = "1338";
assert.equal(Config.getInstance().get("webserver", "port"), 1338);
});
it('raises an exception if the environment variable does not exist', () => {
Config.getInstance().fields = { 'webserver': { 'port': 'env|DOES_NOT_EXIST' } };
process.env.SEASONED_WEBSERVER_PORT = '1338';
assert.throws(() => Config.getInstance().get('webserver', 'port'), /empty/);
it("raises an exception if the environment variable does not exist", () => {
Config.getInstance().fields = { webserver: { port: "env|DOES_NOT_EXIST" } };
process.env.SEASONED_WEBSERVER_PORT = "1338";
assert.throws(() => Config.getInstance().get("webserver", "port"), /empty/);
});
it('raises an exception if the environment variable is empty', () => {
Config.getInstance().fields = { 'webserver': { 'port': 'env|SEASONED_WEBSERVER_PORT' } };
process.env.SEASONED_WEBSERVER_PORT = '';
assert.throws(() => Config.getInstance().get('webserver', 'port'), /empty/);
it("raises an exception if the environment variable is empty", () => {
Config.getInstance().fields = {
webserver: { port: "env|SEASONED_WEBSERVER_PORT" }
};
process.env.SEASONED_WEBSERVER_PORT = "";
assert.throws(() => Config.getInstance().get("webserver", "port"), /empty/);
});
it('raises an exception if the section does not exist in the file', () => {
Config.getInstance().fields = { 'webserver': { 'port': '1338' } };
assert.throws(() => Config.getInstance().get('woops', 'port'), /does not exist/);
it("raises an exception if the section does not exist in the file", () => {
Config.getInstance().fields = { webserver: { port: "1338" } };
assert.throws(
() => Config.getInstance().get("woops", "port"),
/does not exist/
);
});
it('raises an exception if the option does not exist in the file', () => {
Config.getInstance().fields = { 'webserver': { 'port': '1338' } };
assert.throws(() => Config.getInstance().get('webserver', 'woops'), /does not exist/);
it("raises an exception if the option does not exist in the file", () => {
Config.getInstance().fields = { webserver: { port: "1338" } };
assert.throws(
() => Config.getInstance().get("webserver", "woops"),
/does not exist/
);
});
it('returns an array if field is an array', () => {
Config.getInstance().fields = { 'bouncer': { 'whitelist': [1, 2, 3] } };
assert.deepEqual(Config.getInstance().get('bouncer', 'whitelist'), [1, 2, 3]);
it("returns an array if field is an array", () => {
Config.getInstance().fields = { bouncer: { whitelist: [1, 2, 3] } };
assert.deepEqual(
Config.getInstance().get("bouncer", "whitelist"),
[1, 2, 3]
);
});
it('decodes field as base64 if base64| is before the variable', () => {
Config.getInstance().fields = { 'webserver': { 'port': 'base64|MTMzOA==' } };
assert.equal(Config.getInstance().get('webserver', 'port'), 1338);
it("decodes field as base64 if base64| is before the variable", () => {
Config.getInstance().fields = { webserver: { port: "base64|MTMzOA==" } };
assert.equal(Config.getInstance().get("webserver", "port"), 1338);
});
it('decodes environment variable as base64 if BASE64= is before the variable', () => {
Config.getInstance().fields = { 'webserver': { 'port': 'env|base64|SEASONED_WEBSERVER_PORT' } };
process.env.SEASONED_WEBSERVER_PORT = 'MTMzOA==';
assert.equal(Config.getInstance().get('webserver', 'port'), 1338);
it("decodes environment variable as base64 if BASE64= is before the variable", () => {
Config.getInstance().fields = {
webserver: { port: "env|base64|SEASONED_WEBSERVER_PORT" }
};
process.env.SEASONED_WEBSERVER_PORT = "MTMzOA==";
assert.equal(Config.getInstance().get("webserver", "port"), 1338);
});
});

View File

@@ -1,71 +1,77 @@
const assert = require('assert');
const Field = require('src/config/field.js');
const assert = require("assert");
const Field = require("../../../src/config/field");
describe('Field', () => {
it('should return an array if it is an array', () => {
describe("Field", () => {
it("should return an array if it is an array", () => {
const field = new Field([1, 2, 3]);
assert.deepEqual(field.value, [1, 2, 3]);
});
it('should return the plain value if it is an ordinary field', () => {
const field = new Field('plain value');
assert.equal(field.value, 'plain value');
it("should return the plain value if it is an ordinary field", () => {
const field = new Field("plain value");
assert.equal(field.value, "plain value");
});
it('should return false if boolean false is field', () => {
it("should return false if boolean false is field", () => {
const field = new Field(false);
assert.equal(field.value, false);
});
it('should not include any invalid filters', () => {
const field = new Field('invalid-filter|plain value');
assert.equal(field.value, 'plain value');
it("should not include any invalid filters", () => {
const field = new Field("invalid-filter|plain value");
assert.equal(field.value, "plain value");
});
it('should return the decoded value if it is filtered through base64', () => {
const field = new Field('base64|ZW5jb2RlZCB2YWx1ZQ==');
assert.equal(field.value, 'encoded value');
it("should return the decoded value if it is filtered through base64", () => {
const field = new Field("base64|ZW5jb2RlZCB2YWx1ZQ==");
assert.equal(field.value, "encoded value");
});
it('should not decode the value if it missing the filter', () => {
const field = new Field('ZW5jb2RlZCB2YWx1ZQ==');
assert.equal(field.value, 'ZW5jb2RlZCB2YWx1ZQ==');
it("should not decode the value if it missing the filter", () => {
const field = new Field("ZW5jb2RlZCB2YWx1ZQ==");
assert.equal(field.value, "ZW5jb2RlZCB2YWx1ZQ==");
});
it('should retrieve the environment variable if env filter is used', () => {
const environmentVariables = { REDIS_URL: 'redis://127.0.0.1:1234' };
const field = new Field('env|REDIS_URL', environmentVariables);
assert.equal(field.value, 'redis://127.0.0.1:1234');
it("should retrieve the environment variable if env filter is used", () => {
const environmentVariables = { REDIS_URL: "redis://127.0.0.1:1234" };
const field = new Field("env|REDIS_URL", environmentVariables);
assert.equal(field.value, "redis://127.0.0.1:1234");
});
it('should return undefined if the environment variable does not exist', () => {
it("should return undefined if the environment variable does not exist", () => {
const environmentVariables = { HTTP_PORT: 8080 };
const field = new Field('env|REDIS_URL', environmentVariables);
const field = new Field("env|REDIS_URL", environmentVariables);
assert.equal(field.value, undefined);
});
it('should return undefined if the environment variable is an empty string', () => {
const environmentVariables = { REDIS_URL: '' };
const field = new Field('env|REDIS_URL', environmentVariables);
it("should return undefined if the environment variable is an empty string", () => {
const environmentVariables = { REDIS_URL: "" };
const field = new Field("env|REDIS_URL", environmentVariables);
assert.deepEqual(field.value, undefined);
});
describe('Multiple filters', () => {
it('should decode the environment variable if base64 and env filter are used', () => {
const environmentVariables = { REDIS_URL: 'cmVkaXM6Ly9kYWdibGFkZXQubm8vMTIzNA==' };
const field = new Field('env|base64|REDIS_URL', environmentVariables);
assert.equal(field.value, 'redis://dagbladet.no/1234');
describe("Multiple filters", () => {
it("should decode the environment variable if base64 and env filter are used", () => {
const environmentVariables = {
REDIS_URL: "cmVkaXM6Ly9kYWdibGFkZXQubm8vMTIzNA=="
};
const field = new Field("env|base64|REDIS_URL", environmentVariables);
assert.equal(field.value, "redis://dagbladet.no/1234");
});
it('should disregard the order of filters when env and base64 are used', () => {
const environmentVariables = { REDIS_URL: 'cmVkaXM6Ly9kYWdibGFkZXQubm8vMTIzNA==' };
const field = new Field('base64|env|REDIS_URL', environmentVariables);
assert.equal(field.value, 'redis://dagbladet.no/1234');
it("should disregard the order of filters when env and base64 are used", () => {
const environmentVariables = {
REDIS_URL: "cmVkaXM6Ly9kYWdibGFkZXQubm8vMTIzNA=="
};
const field = new Field("base64|env|REDIS_URL", environmentVariables);
assert.equal(field.value, "redis://dagbladet.no/1234");
});
it('should return undefined if both filters are used and env var does not exist', () => {
const environmentVariables = { REDIS_URL: 'cmVkaXM6Ly9kYWdibGFkZXQubm8vMTIzNA==' };
const field = new Field('base64|env|REDIS_LOL', environmentVariables);
it("should return undefined if both filters are used and env var does not exist", () => {
const environmentVariables = {
REDIS_URL: "cmVkaXM6Ly9kYWdibGFkZXQubm8vMTIzNA=="
};
const field = new Field("base64|env|REDIS_LOL", environmentVariables);
assert.equal(field.value, undefined);
});
});

View File

@@ -1,34 +1,34 @@
const assert = require('assert');
const Filters = require('src/config/filters.js');
const assert = require("assert");
const Filters = require("../../../src/config/filters");
describe('Filters', () => {
it('should extract base64 as filter if it is at start of string followed by pipe', () => {
const filters = new Filters('base64|');
assert.deepEqual(filters.filters, ['base64']);
describe("Filters", () => {
it("should extract base64 as filter if it is at start of string followed by pipe", () => {
const filters = new Filters("base64|");
assert.deepEqual(filters.filters, ["base64"]);
});
it('should extract base64 and env as filters if both are separated by pipe', () => {
const filters = new Filters('base64|env|');
assert.deepEqual(filters.filters, ['base64', 'env']);
it("should extract base64 and env as filters if both are separated by pipe", () => {
const filters = new Filters("base64|env|");
assert.deepEqual(filters.filters, ["base64", "env"]);
});
it('should not extract any filters if none are present', () => {
const filters = new Filters('base64');
it("should not extract any filters if none are present", () => {
const filters = new Filters("base64");
assert.deepEqual(filters.filters, []);
});
it('should strip env filter from the value', () => {
const filters = new Filters('env|HELLO');
assert.deepEqual(filters.removeFiltersFromValue(), 'HELLO');
it("should strip env filter from the value", () => {
const filters = new Filters("env|HELLO");
assert.deepEqual(filters.removeFiltersFromValue(), "HELLO");
});
it('should strip env and base64 filter from the value', () => {
const filters = new Filters('env|base64|HELLO');
assert.deepEqual(filters.removeFiltersFromValue(), 'HELLO');
it("should strip env and base64 filter from the value", () => {
const filters = new Filters("env|base64|HELLO");
assert.deepEqual(filters.removeFiltersFromValue(), "HELLO");
});
it('should strip no filters from the value if there are no filters', () => {
const filters = new Filters('HELLO');
assert.deepEqual(filters.removeFiltersFromValue(), 'HELLO');
it("should strip no filters from the value if there are no filters", () => {
const filters = new Filters("HELLO");
assert.deepEqual(filters.removeFiltersFromValue(), "HELLO");
});
});

View File

@@ -1,31 +1,38 @@
const assert = require('assert');
const assert = require("assert");
// const convertTmdbToMovie = require('src/tmdb/convertTmdbToMovie');
const { Movie } = require('src/tmdb/types');
const bladeRunnerQuerySuccess = require('test/fixtures/blade_runner_2049-info-success-response.json')
const { Movie } = require("../../../src/tmdb/types");
const bladeRunnerQuerySuccess = require("../../fixtures/blade_runner_2049-info-success-response.json");
describe('Convert tmdb movieInfo to movie', () => {
beforeEach(() => [this.bladeRunnerTmdbMovie] = bladeRunnerQuerySuccess);
describe("Convert tmdb movieInfo to movie", () => {
beforeEach(() => {
[this.bladeRunnerTmdbMovie] = bladeRunnerQuerySuccess;
});
it('should translate the tmdb release date to movie year', () => {
const bladeRunner = Movie.convertFromTmdbResponse(this.bladeRunnerTmdbMovie);
it("should translate the tmdb release date to movie year", () => {
const bladeRunner = Movie.convertFromTmdbResponse(
this.bladeRunnerTmdbMovie
);
assert.strictEqual(bladeRunner.year, 2017);
});
it('should translate the tmdb release date to instance of Date', () => {
const bladeRunner = Movie.convertFromTmdbResponse(this.bladeRunnerTmdbMovie);
it("should translate the tmdb release date to instance of Date", () => {
const bladeRunner = Movie.convertFromTmdbResponse(
this.bladeRunnerTmdbMovie
);
assert(bladeRunner.releaseDate instanceof Date);
});
it('should translate the tmdb title to title', () => {
const bladeRunner = Movie.convertFromTmdbResponse(this.bladeRunnerTmdbMovie);
assert.equal(bladeRunner.title, 'Blade Runner 2049');
it("should translate the tmdb title to title", () => {
const bladeRunner = Movie.convertFromTmdbResponse(
this.bladeRunnerTmdbMovie
);
assert.equal(bladeRunner.title, "Blade Runner 2049");
});
it('should translate the tmdb vote_average to rating', () => {
const bladeRunner = Movie.convertFromTmdbResponse(this.bladeRunnerTmdbMovie);
it("should translate the tmdb vote_average to rating", () => {
const bladeRunner = Movie.convertFromTmdbResponse(
this.bladeRunnerTmdbMovie
);
assert.equal(bladeRunner.rating, 7.3);
});
});

View File

@@ -5,9 +5,9 @@ const Cache = require('src/tmdb/cache');
const SqliteDatabase = require('src/database/sqliteDatabase');
const tmdbMock = require('test/helpers/tmdbMock');
const emptyQuerySuccess = require('test/fixtures/empty-query-success-response.json');
const interstellarQuerySuccess = require('test/fixtures/arrival-info-success-response.json');
const popularMovieSuccessResponse = require('test/fixtures/popular-movies-success-response.json');
const emptyQuerySuccess = require('tests/fixtures/empty-query-success-response.json');
const interstellarQuerySuccess = require('tests/fixtures/arrival-info-success-response.json');
const popularMovieSuccessResponse = require('tests/fixtures/popular-movies-success-response.json');
describe('TMDB', function test() {
beforeEach(() => {

1899
yarn.lock

File diff suppressed because it is too large Load Diff