test-utils.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // @ts-check
  2. /**
  3. * @typedef {import('mongodb').MongoClient} MongoClient
  4. * @typedef {import('mongodb-legacy').MongoClient} LegacyMongoClient
  5. */
  6. /**
  7. * Delete all data from the test Mongo database
  8. *
  9. * This doesn't drop the collections, so indexes are preserved.
  10. *
  11. * @param {MongoClient | LegacyMongoClient} mongoClient
  12. */
  13. async function cleanupTestDatabase(mongoClient) {
  14. ensureTestDatabase(mongoClient)
  15. const db = mongoClient.db()
  16. const allCollections = await db.collections()
  17. const collections = allCollections.filter(
  18. coll => coll.collectionName !== 'migrations'
  19. )
  20. await Promise.all(collections.map(coll => coll.deleteMany({})))
  21. }
  22. /**
  23. * Drop the test Monto database
  24. *
  25. * This drops the whole database, including indexes.
  26. *
  27. * @param {MongoClient | LegacyMongoClient } mongoClient
  28. */
  29. async function dropTestDatabase(mongoClient) {
  30. ensureTestDatabase(mongoClient)
  31. await mongoClient.db().dropDatabase()
  32. }
  33. /**
  34. * Ensure that the given client is connected to a test database.
  35. *
  36. * This should be called before performing destructive operations on the test
  37. * database.
  38. *
  39. * @param {MongoClient | LegacyMongoClient } mongoClient
  40. */
  41. function ensureTestDatabase(mongoClient) {
  42. const dbName = mongoClient.db().databaseName
  43. const env = process.env.NODE_ENV
  44. if (dbName !== 'test-overleaf' || env !== 'test') {
  45. throw new Error(
  46. `Refusing to clear database '${dbName}' in environment '${env}'`
  47. )
  48. }
  49. }
  50. module.exports = { cleanupTestDatabase, dropTestDatabase }