Parcourir la source

Refactored tests file architecture. Removed WebSockets test, added experimentCollect API route test

rigwild il y a 4 ans
Parent
commit
ff4d55738c

+ 2 - 3
package.json

@@ -10,7 +10,7 @@
     "app:build": "vue-cli-service build",
     "app:lint": "vue-cli-service lint",
     "doc": "apidoc -i server/routes -o doc",
-    "test": "node test/api/_test_setup_start.js && ava --verbose && node test/api/_test_setup_stop.js"
+    "test": "node test/utils/_test_setup_start.js && ava --verbose && node test/utils/_test_setup_stop.js"
   },
   "dependencies": {
     "@hapi/boom": "^7.4.2",
@@ -27,8 +27,7 @@
     "serve-static": "^1.13.2",
     "sharp": "^0.22.1",
     "ua-parser-js": "^0.7.19",
-    "winston": "^3.2.1",
-    "ws": "^7.0.0"
+    "winston": "^3.2.1"
   },
   "devDependencies": {
     "@vue/cli-plugin-babel": "^3.7.0",

+ 0 - 106
test/api/databaseWebSocket.js

@@ -1,106 +0,0 @@
-'use strict'
-
-import test from 'ava'
-import WebSocket from 'ws'
-import { json, getHttpServer, getWebSocketServer, connectDb } from './_test_functions'
-import DataController from '../../server/database/controllers/Data'
-
-// Database and WebSocket testing
-
-// Before all tests, connect to the database
-test.beforeEach(async t => (t.context.server = await getHttpServer()))
-
-test('Check database is working', async t => {
-  // Connect to database
-  await connectDb()
-
-  // Add the document
-  const testData = { AUTOMATED_TEST_DB: true, TEST_DATABASE_OBJ: { msg: 'add' } }
-  const doc = await DataController.add(testData)
-  t.deepEqual(doc.data, testData, json(doc))
-
-  // Find the document
-  const findDoc = await DataController.find(doc.id)
-  t.deepEqual(findDoc.data, testData, json(findDoc))
-
-  // Update the document
-  testData.TEST_DATABASE_OBJ.msg = 'updated'
-  const updateTo = { AUTOMATED_TEST_DB: true, newObject: 'test', newProperties: { test: true } }
-  const docUpdated = await DataController.update(doc.id, updateTo)
-  t.deepEqual(docUpdated.data, updateTo, json(docUpdated))
-
-  // Delete the added document
-  await t.notThrowsAsync(DataController.del(doc.id))
-})
-
-test('Check WebSocket server is working', async t => {
-  // Connect to database
-  await connectDb()
-
-  // Start the server and get its ephemeral port
-  const server = t.context.server.listen(0)
-  const { port } = server.address()
-
-  // Start the WebSocket server
-  getWebSocketServer(server)
-
-  t.timeout(15000)
-  t.plan(11)
-
-  // Start the WebSocket client
-  const ws = new WebSocket(`ws://localhost:${port}`)
-  await new Promise((resolve, reject) => {
-    let sent = 0
-    let received = 0
-    ws.on('open', async () => {
-      // Send data on connect
-      ws.send(JSON.stringify({ AUTOMATED_TEST_WS: true, TEST_OBJECT: { msg: 'open' } }))
-      t.pass()
-      sent++
-    })
-    ws.on('message', async receivedData => {
-      received++
-      if (sent === 1) {
-        // Send data on receive
-        t.is('{"message":"ok"}', receivedData, json(receivedData))
-        ws.send(JSON.stringify({ AUTOMATED_TEST_WS: true, TEST_OBJECT: { msg: 'message' } }))
-        t.pass()
-        sent++
-      }
-      else if (sent === 2) {
-        // Send invalid JSON data
-        t.is('{"message":"ok"}', receivedData, json(receivedData))
-        ws.send('Not a valid JSON string')
-        t.pass()
-        sent++
-      }
-      else if (sent === 3) {
-        // Received error from server, check it is valid JSON
-        let obj = null
-        t.notThrows(() => {
-          try {
-            obj = JSON.parse(receivedData)
-          }
-          catch (err) {
-            throw new Error('Not valid JSON')
-          }
-        })
-        t.truthy(obj, json(receivedData))
-        t.is(obj.log.error, 'Invalid JSON data.', json(obj))
-        t.truthy(obj.log.stack, json(obj))
-        t.is(sent, received)
-        resolve()
-      }
-    })
-    ws.on('error', async err => {
-      // Unknown WebSocket error
-      t.fail(json(err.message))
-      reject(err)
-    })
-  })
-
-  // Delete every collected data during test
-  const db = DataController.Model
-  const found = await db.deleteMany({ 'data.AUTOMATED_TEST_WS': true })
-  t.true(found.deletedCount >= 2)
-})

+ 2 - 2
test/api/dataCollect.js

@@ -2,8 +2,8 @@
 
 import test from 'ava'
 import request from 'supertest'
-import { apiPrefix } from '../../config'
-import { json, getHttpServer } from './_test_functions'
+import { apiPrefix } from '../../../config'
+import { json, getHttpServer } from '../../utils/_test_functions'
 
 // ROUTE /dataCollect
 

+ 39 - 0
test/server/api/experimentCollect.js

@@ -0,0 +1,39 @@
+'use strict'
+
+import test from 'ava'
+import request from 'supertest'
+import { apiPrefix } from '../../../config'
+import { json, getHttpServer } from '../../utils/_test_functions'
+
+// ROUTE /experimentCollect
+
+// Before each tests, start a server
+test.beforeEach(async t => (t.context.server = await getHttpServer()))
+
+test('POST /experimentCollect - No body', async t => {
+  const res = await request(t.context.server)
+    .post(`${apiPrefix}/experimentCollect`)
+
+  t.is(res.status, 400, json(res))
+  t.true(res.body.message.includes('Missing parameter'), json(res.body))
+  t.true(res.body.message.includes('msgId'), json(res.body))
+  t.true(res.body.message.includes('msg'), json(res.body))
+})
+
+test('POST /experimentCollect - Invalid body parameters', async t => {
+  const res = await request(t.context.server)
+    .post(`${apiPrefix}/experimentCollect`)
+    .send({ msgId: { notAstring: 'not a string' }, msg: 'Valid data' })
+
+  t.is(res.status, 400, json(res))
+  t.true(res.body.message.includes('Invalid body parameter'), json(res.body))
+  t.truthy(res.body.data.find(x => x.includes('"msgId" must be a string.')), json(res.body))
+})
+
+test('POST /experimentCollect - Valid body parameters', async t => {
+  const res = await request(t.context.server)
+    .post(`${apiPrefix}/experimentCollect`)
+    .send({ msgId: 'TEST_FEATURE', msg: { some: 'data' } })
+
+  t.is(res.status, 204)
+})

+ 2 - 2
test/api/getImage.js

@@ -2,8 +2,8 @@
 
 import test from 'ava'
 import request from 'supertest'
-import { apiPrefix, imageServedUrl } from '../../config'
-import { json, getHttpServer } from './_test_functions'
+import { apiPrefix, imageServedUrl } from '../../../config'
+import { json, getHttpServer } from '../../utils/_test_functions'
 
 // ROUTE /getImage
 

+ 2 - 2
test/api/getImageExtracts.js

@@ -5,8 +5,8 @@ import request from 'supertest'
 import sharp from 'sharp'
 import fs from 'fs-extra'
 import path from 'path'
-import { apiPrefix, imageServedUrl, imagesPath } from '../../config'
-import { json, getHttpServer } from './_test_functions'
+import { apiPrefix, imageServedUrl, imagesPath } from '../../../config'
+import { json, getHttpServer } from '../../utils/_test_functions'
 
 // ROUTE /getImageExtracts
 

+ 2 - 2
test/api/listScenes.js

@@ -2,8 +2,8 @@
 
 import test from 'ava'
 import request from 'supertest'
-import { apiPrefix } from '../../config'
-import { json, getHttpServer } from './_test_functions'
+import { apiPrefix } from '../../../config'
+import { json, getHttpServer } from '../../utils/_test_functions'
 
 // ROUTE /listScenes
 

+ 2 - 2
test/api/listScenesQualities.js

@@ -2,8 +2,8 @@
 
 import test from 'ava'
 import request from 'supertest'
-import { apiPrefix } from '../../config'
-import { json, getHttpServer } from './_test_functions'
+import { apiPrefix } from '../../../config'
+import { json, getHttpServer } from '../../utils/_test_functions'
 
 // ROUTE /listSceneQualities
 

+ 2 - 2
test/api/ping.js

@@ -2,8 +2,8 @@
 
 import test from 'ava'
 import request from 'supertest'
-import { apiPrefix } from '../../config'
-import { json, getHttpServer } from './_test_functions'
+import { apiPrefix } from '../../../config'
+import { json, getHttpServer } from '../../utils/_test_functions'
 
 // ROUTE /ping
 

+ 33 - 0
test/server/database.js

@@ -0,0 +1,33 @@
+'use strict'
+
+import test from 'ava'
+import { json, getHttpServer, connectDb } from '../utils/_test_functions'
+import DataController from '../../server/database/controllers/Data'
+
+// Database and WebSocket testing
+
+// Before all tests, connect to the database
+test.beforeEach(async t => (t.context.server = await getHttpServer()))
+
+test('Check database is working', async t => {
+  // Connect to database
+  await connectDb()
+
+  // Add the document
+  const testData = { AUTOMATED_TEST_DB: true, TEST_DATABASE_OBJ: { msg: 'add' } }
+  const doc = await DataController.add(testData)
+  t.deepEqual(doc.data, testData, json(doc))
+
+  // Find the document
+  const findDoc = await DataController.find(doc.id)
+  t.deepEqual(findDoc.data, testData, json(findDoc))
+
+  // Update the document
+  testData.TEST_DATABASE_OBJ.msg = 'updated'
+  const updateTo = { AUTOMATED_TEST_DB: true, newObject: 'test', newProperties: { test: true } }
+  const docUpdated = await DataController.update(doc.id, updateTo)
+  t.deepEqual(docUpdated.data, updateTo, json(docUpdated))
+
+  // Delete the added document
+  await t.notThrowsAsync(DataController.del(doc.id))
+})

+ 0 - 21
test/api/_test_functions.js

@@ -3,14 +3,11 @@
 import path from 'path'
 import express from 'express'
 import bodyParser from 'body-parser'
-import WebSocket from 'ws'
 import serveStatic from 'serve-static'
 import routes from '../../server/routes'
 import { apiPrefix, imageServedUrl, imagesPath } from '../../config'
 import connectDb from '../../server/database'
 import { errorHandler } from '../../server/functions'
-import { errorHandler as wsErrorHandler } from '../../server/webSocket'
-import wsMessageHandler from '../../server/webSocket/messageHandler'
 
 // Path to `test` directory
 export const testDir = path.resolve(__dirname, '..')
@@ -38,23 +35,5 @@ export const getHttpServer = () => {
   return app
 }
 
-/**
- * Open a WebSocket server on top of a HTTP server
- *
- * @param {object} httpServer a HTTP server instance (ie. Express server object)
- * @returns {object} a WebSocket server instance
- */
-export const getWebSocketServer = httpServer => {
-  const wss = new WebSocket.Server({ server: httpServer })
-  wss.on('error', err => {
-    throw err
-  })
-  wss.on('connection', ws => {
-    ws.on('message', data => wsMessageHandler(ws)(data).catch(wsErrorHandler(ws)))
-    ws.on('error', wsErrorHandler(ws))
-  })
-  return wss
-}
-
 /** Connect to the database */
 export { connectDb }

test/api/_test_setup_start.js → test/utils/_test_setup_start.js


test/api/_test_setup_stop.js → test/utils/_test_setup_stop.js


+ 1 - 8
yarn.lock

@@ -1517,7 +1517,7 @@ async-each@^1.0.1:
   resolved "https://registry.yarnpkg.com/async-each/-/async-each-1.0.3.tgz#b727dbf87d7651602f06f4d4ac387f47d91b0cbf"
   integrity sha512-z/WhQ5FPySLdvREByI2vZiTWwCnF0moMJ1hK9YQwDTHKh6I7/uSckMetoRGb5UBZPC1z0jlw+n/XCgjeH7y1AQ==
 
-async-limiter@^1.0.0, async-limiter@~1.0.0:
+async-limiter@~1.0.0:
   version "1.0.0"
   resolved "https://registry.yarnpkg.com/async-limiter/-/async-limiter-1.0.0.tgz#78faed8c3d074ab81f22b4e985d79e8738f720f8"
   integrity sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==
@@ -10069,13 +10069,6 @@ ws@^6.0.0:
   dependencies:
     async-limiter "~1.0.0"
 
-ws@^7.0.0:
-  version "7.0.0"
-  resolved "https://registry.yarnpkg.com/ws/-/ws-7.0.0.tgz#79351cbc3f784b3c20d0821baf4b4ff809ffbf51"
-  integrity sha512-cknCal4k0EAOrh1SHHPPWWh4qm93g1IuGGGwBjWkXmCG7LsDtL8w9w+YVfaF+KSVwiHQKDIMsSLBVftKf9d1pg==
-  dependencies:
-    async-limiter "^1.0.0"
-
 x-xss-protection@1.1.0:
   version "1.1.0"
   resolved "https://registry.yarnpkg.com/x-xss-protection/-/x-xss-protection-1.1.0.tgz#4f1898c332deb1e7f2be1280efb3e2c53d69c1a7"