diff --git a/test/environment/setup.ts b/test/environment/setup.ts index 446809b1..3126f8b1 100644 --- a/test/environment/setup.ts +++ b/test/environment/setup.ts @@ -2,14 +2,7 @@ import * as fs from 'fs' import { DockerComposeEnvironment, Wait } from 'testcontainers' import axios from 'axios' import { TestConstants } from '../testHelpers/TestConstants' -import datasetJson1 from '../testHelpers/datasets/test-dataset-1.json' -import datasetJson2 from '../testHelpers/datasets/test-dataset-2.json' -import datasetJson3 from '../testHelpers/datasets/test-dataset-3.json' -import datasetJson4 from '../testHelpers/datasets/test-dataset-4.json' -import collectionJson from '../testHelpers/collections/test-collection-1.json' -import { ROOT_COLLECTION_ALIAS } from '../../src/collections/domain/models/Collection' -const NUMBER_OF_DATASETS = 4 const COMPOSE_FILE = 'docker-compose.yml' const CONTAINER_DATAVERSE_BOOTSTRAP_NAME = 'test_dataverse_bootstrap' @@ -24,7 +17,6 @@ const API_KEY_USER_PASSWORD = 'admin1' export default async function setupTestEnvironment(): Promise { await setupContainers() await setupApiKey() - await setupTestFixtures() } async function setupContainers(): Promise { @@ -54,88 +46,3 @@ async function setupApiKey(): Promise { }) console.log('API key obtained') } - -async function setupTestFixtures(): Promise { - console.log('Creating test datasets...') - await createDatasetViaApi(datasetJson1) - .then() - .catch(() => { - console.error('Tests setup: Error while creating test Dataset 1') - }) - await createDatasetViaApi(datasetJson2).catch(() => { - console.error('Tests setup: Error while creating test Dataset 2') - }) - await createDatasetViaApi(datasetJson4).catch(() => { - console.error('Tests setup: Error while creating test Dataset 4') - }) - await createCollectionViaApi(collectionJson) - .then() - .catch(() => { - console.error('Tests setup: Error while creating test Collection 1') - }) - await createDatasetViaApi(datasetJson3, collectionJson.alias) - .then() - .catch(() => { - console.error('Tests setup: Error while creating test Dataset 3') - }) - console.log('Test datasets created') - await waitForDatasetsIndexingInSolr() -} - -/* eslint-disable @typescript-eslint/no-explicit-any */ -async function createCollectionViaApi(collectionJson: any): Promise { - return await axios.post( - `${TestConstants.TEST_API_URL}/dataverses/root`, - collectionJson, - buildRequestHeaders() - ) -} - -/* eslint-disable @typescript-eslint/no-explicit-any */ -async function createDatasetViaApi( - datasetJson: any, - collectionId = ROOT_COLLECTION_ALIAS -): Promise { - return await axios.post( - `${TestConstants.TEST_API_URL}/dataverses/${collectionId}/datasets`, - datasetJson, - buildRequestHeaders() - ) -} - -/* eslint-disable @typescript-eslint/no-explicit-any */ -async function waitForDatasetsIndexingInSolr(): Promise { - console.log('Waiting for datasets indexing in Solr...') - let datasetsIndexed = false - let retry = 0 - while (!datasetsIndexed && retry < 10) { - await axios - .get(`${TestConstants.TEST_API_URL}/search?q=*&type=dataset`, buildRequestHeaders()) - .then((response) => { - const nDatasets = response.data.data.items.length - if (nDatasets === NUMBER_OF_DATASETS) { - datasetsIndexed = true - } - }) - .catch((error) => { - console.error( - `Tests setup: Error while waiting for datasets indexing in Solr: [${ - error.response.status - }]${error.response.data ? ` ${error.response.data.message}` : ''}` - ) - }) - await new Promise((resolve) => setTimeout(resolve, 1000)) - retry++ - } - if (!datasetsIndexed) { - throw new Error('Tests setup: Timeout reached while waiting for datasets indexing in Solr') - } - console.log('Datasets indexed in Solr') -} - -/* eslint-disable @typescript-eslint/no-explicit-any */ -function buildRequestHeaders(): any { - return { - headers: { 'Content-Type': 'application/json', 'X-Dataverse-Key': process.env.TEST_API_KEY } - } -} diff --git a/test/functional/datasets/CreateDataset.test.ts b/test/functional/datasets/CreateDataset.test.ts index 3ef15611..d1bf729f 100644 --- a/test/functional/datasets/CreateDataset.test.ts +++ b/test/functional/datasets/CreateDataset.test.ts @@ -3,6 +3,7 @@ import { ApiConfig } from '../../../src' import { TestConstants } from '../../testHelpers/TestConstants' import { DataverseApiAuthMechanism } from '../../../src/core/infra/repositories/ApiConfig' import { FieldValidationError } from '../../../src/datasets/domain/useCases/validators/errors/FieldValidationError' +import { deleteUnpublishedDatasetViaApi } from '../../testHelpers/datasets/datasetHelper' describe('execute', () => { beforeEach(async () => { @@ -56,6 +57,7 @@ describe('execute', () => { expect(createdDatasetIdentifiers).not.toBeNull() expect(createdDatasetIdentifiers.numericId).not.toBeNull() expect(createdDatasetIdentifiers.persistentId).not.toBeNull() + await deleteUnpublishedDatasetViaApi(createdDatasetIdentifiers.numericId) } }) diff --git a/test/functional/datasets/PublishDataset.test.ts b/test/functional/datasets/PublishDataset.test.ts index 54225df5..eb3955be 100644 --- a/test/functional/datasets/PublishDataset.test.ts +++ b/test/functional/datasets/PublishDataset.test.ts @@ -7,7 +7,10 @@ import { } from '../../../src' import { TestConstants } from '../../testHelpers/TestConstants' import { DataverseApiAuthMechanism } from '../../../src/core/infra/repositories/ApiConfig' -import { waitForNoLocks } from '../../testHelpers/datasets/datasetHelper' +import { + waitForNoLocks, + deletePublishedDatasetViaApi +} from '../../testHelpers/datasets/datasetHelper' const testNewDataset = { license: { @@ -57,12 +60,16 @@ describe('execute', () => { }) test('should successfully publish a dataset', async () => { - const dataset = await createDataset.execute(testNewDataset) + const createdDatasetIdentifiers = await createDataset.execute(testNewDataset) - const response = await publishDataset.execute(dataset.persistentId, VersionUpdateType.MAJOR) - await waitForNoLocks(dataset.numericId, 10) + const response = await publishDataset.execute( + createdDatasetIdentifiers.persistentId, + VersionUpdateType.MAJOR + ) + await waitForNoLocks(createdDatasetIdentifiers.numericId, 10) expect(response).toBeUndefined() + await deletePublishedDatasetViaApi(createdDatasetIdentifiers.persistentId) }) test('should throw an error when trying to publish a dataset that does not exist', async () => { diff --git a/test/integration/collections/CollectionsRepository.test.ts b/test/integration/collections/CollectionsRepository.test.ts index 31a14043..ef92cd96 100644 --- a/test/integration/collections/CollectionsRepository.test.ts +++ b/test/integration/collections/CollectionsRepository.test.ts @@ -3,40 +3,51 @@ import { TestConstants } from '../../testHelpers/TestConstants' import { ReadError } from '../../../src' import { ApiConfig } from '../../../src' import { DataverseApiAuthMechanism } from '../../../src/core/infra/repositories/ApiConfig' +import { + createCollectionViaApi, + deleteCollectionViaApi +} from '../../testHelpers/collections/collectionHelper' +import { ROOT_COLLECTION_ALIAS } from '../../../src/collections/domain/models/Collection' +import { CollectionPayload } from '../../../src/collections/infra/repositories/transformers/CollectionPayload' describe('CollectionsRepository', () => { const testGetCollection: CollectionsRepository = new CollectionsRepository() + let testCollectionId: number - beforeEach(async () => { + beforeAll(async () => { ApiConfig.init( TestConstants.TEST_API_URL, DataverseApiAuthMechanism.API_KEY, process.env.TEST_API_KEY ) + await createCollectionViaApi(TestConstants.TEST_CREATED_COLLECTION_ALIAS_2).then( + (collectionPayload: CollectionPayload) => (testCollectionId = collectionPayload.id) + ) }) - afterEach(async () => { + afterAll(async () => { ApiConfig.init( TestConstants.TEST_API_URL, DataverseApiAuthMechanism.API_KEY, process.env.TEST_API_KEY ) + await deleteCollectionViaApi(TestConstants.TEST_CREATED_COLLECTION_ALIAS_2) }) describe('getCollection', () => { describe('by default `root` Id', () => { test('should return the root collection of the Dataverse installation if no parameter is passed AS `root`', async () => { const actual = await testGetCollection.getCollection() - expect(actual.alias).toBe(TestConstants.TEST_CREATED_COLLECTION_1_ROOT) + expect(actual.alias).toBe(ROOT_COLLECTION_ALIAS) }) }) describe('by string alias', () => { test('should return collection when it exists filtering by id AS (alias)', async () => { const actual = await testGetCollection.getCollection( - TestConstants.TEST_CREATED_COLLECTION_1_ALIAS + TestConstants.TEST_CREATED_COLLECTION_ALIAS_2 ) - expect(actual.alias).toBe(TestConstants.TEST_CREATED_COLLECTION_1_ALIAS) + expect(actual.alias).toBe(TestConstants.TEST_CREATED_COLLECTION_ALIAS_2) }) test('should return error when collection does not exist', async () => { @@ -51,10 +62,8 @@ describe('CollectionsRepository', () => { }) describe('by numeric id', () => { test('should return collection when it exists filtering by id AS (id)', async () => { - const actual = await testGetCollection.getCollection( - TestConstants.TEST_CREATED_COLLECTION_1_ID - ) - expect(actual.id).toBe(TestConstants.TEST_CREATED_COLLECTION_1_ID) + const actual = await testGetCollection.getCollection(testCollectionId) + expect(actual.id).toBe(testCollectionId) }) test('should return error when collection does not exist', async () => { diff --git a/test/integration/datasets/DatasetsRepository.test.ts b/test/integration/datasets/DatasetsRepository.test.ts index b8af8cd6..5ecbbf76 100644 --- a/test/integration/datasets/DatasetsRepository.test.ts +++ b/test/integration/datasets/DatasetsRepository.test.ts @@ -2,16 +2,21 @@ import { DatasetsRepository } from '../../../src/datasets/infra/repositories/Dat import { TestConstants } from '../../testHelpers/TestConstants' import { createPrivateUrlViaApi, - deaccessionDatasetViaApi, publishDatasetViaApi, - waitForNoLocks + waitForNoLocks, + deleteUnpublishedDatasetViaApi, + waitForDatasetsIndexedInSolr, + deletePublishedDatasetViaApi, + deaccessionDatasetViaApi } from '../../testHelpers/datasets/datasetHelper' import { ReadError } from '../../../src/core/domain/repositories/ReadError' import { DatasetLockType, DatasetNotNumberedVersion, DatasetPreviewSubset, - VersionUpdateType + VersionUpdateType, + createDataset, + CreatedDatasetIdentifiers } from '../../../src/datasets' import { ApiConfig, WriteError } from '../../../src' import { DataverseApiAuthMechanism } from '../../../src/core/infra/repositories/ApiConfig' @@ -22,14 +27,16 @@ import { DatasetDescription } from '../../../src/datasets/domain/models/Dataset' import { ROOT_COLLECTION_ALIAS } from '../../../src/collections/domain/models/Collection' +import { + createCollectionViaApi, + deleteCollectionViaApi +} from '../../testHelpers/collections/collectionHelper' describe('DatasetsRepository', () => { const sut: DatasetsRepository = new DatasetsRepository() const nonExistentTestDatasetId = 100 - const latestVersionId = DatasetNotNumberedVersion.LATEST - - beforeEach(async () => { + beforeAll(async () => { ApiConfig.init( TestConstants.TEST_API_URL, DataverseApiAuthMechanism.API_KEY, @@ -37,7 +44,7 @@ describe('DatasetsRepository', () => { ) }) - afterEach(async () => { + afterAll(async () => { ApiConfig.init( TestConstants.TEST_API_URL, DataverseApiAuthMechanism.API_KEY, @@ -48,48 +55,100 @@ describe('DatasetsRepository', () => { describe('getAllDatasetPreviews', () => { const testPageLimit = 1 const expectedTotalDatasetCount = 4 + const createdDatasetIds: CreatedDatasetIdentifiers[] = [] + + beforeAll(async () => { + await createCollection() + await createDatasets() + }) + + afterAll(async () => { + await deleteDatasets() + await deleteCollection() + }) + + const createCollection = async () => { + await createCollectionViaApi(TestConstants.TEST_CREATED_COLLECTION_ALIAS_1) + } + + const createDatasets = async () => { + for (let i = 0; i < expectedTotalDatasetCount; i++) { + createdDatasetIds[i] = await createDataset.execute( + TestConstants.TEST_NEW_DATASET_DTO, + TestConstants.TEST_CREATED_COLLECTION_ALIAS_1 + ) + } + + await waitForDatasetsIndexedInSolr( + expectedTotalDatasetCount, + TestConstants.TEST_CREATED_COLLECTION_ALIAS_1 + ) + } + + const deleteDatasets = async () => { + for (let i = 0; i < expectedTotalDatasetCount; i++) { + await deleteUnpublishedDatasetViaApi(createdDatasetIds[i].numericId) + } + } + + const deleteCollection = async () => { + await deleteCollectionViaApi(TestConstants.TEST_CREATED_COLLECTION_ALIAS_1) + } test('should return all dataset previews when no pagination params are defined', async () => { - const actual: DatasetPreviewSubset = await sut.getAllDatasetPreviews() + const actual: DatasetPreviewSubset = await sut.getAllDatasetPreviews( + undefined, + undefined, + TestConstants.TEST_CREATED_COLLECTION_ALIAS_1 + ) expect(actual.datasetPreviews.length).toEqual(expectedTotalDatasetCount) - expect(actual.datasetPreviews[0].title).toMatch('Third Dataset') + expect(actual.datasetPreviews[0].persistentId).toMatch(createdDatasetIds[3].persistentId) expect(actual.totalDatasetCount).toEqual(expectedTotalDatasetCount) }) test('should return first dataset preview page', async () => { - const actual = await sut.getAllDatasetPreviews(testPageLimit, 0) + const actual = await sut.getAllDatasetPreviews( + testPageLimit, + 0, + TestConstants.TEST_CREATED_COLLECTION_ALIAS_1 + ) expect(actual.datasetPreviews.length).toEqual(1) - expect(actual.datasetPreviews[0].title).toMatch('Third Dataset') + expect(actual.datasetPreviews[0].persistentId).toMatch(createdDatasetIds[3].persistentId) expect(actual.totalDatasetCount).toEqual(expectedTotalDatasetCount) }) test('should return second dataset preview page', async () => { - const actual = await sut.getAllDatasetPreviews(testPageLimit, 1) + const actual = await sut.getAllDatasetPreviews( + testPageLimit, + 1, + TestConstants.TEST_CREATED_COLLECTION_ALIAS_1 + ) expect(actual.datasetPreviews.length).toEqual(1) - expect(actual.datasetPreviews[0].title).toMatch('Fourth Dataset') + expect(actual.datasetPreviews[0].persistentId).toMatch(createdDatasetIds[2].persistentId) expect(actual.totalDatasetCount).toEqual(expectedTotalDatasetCount) }) test('should return third dataset preview page', async () => { - const actual = await sut.getAllDatasetPreviews(testPageLimit, 2) + const actual = await sut.getAllDatasetPreviews( + testPageLimit, + 2, + TestConstants.TEST_CREATED_COLLECTION_ALIAS_1 + ) expect(actual.datasetPreviews.length).toEqual(1) - expect(actual.datasetPreviews[0].title).toMatch('Second Dataset') + expect(actual.datasetPreviews[0].persistentId).toMatch(createdDatasetIds[1].persistentId) expect(actual.totalDatasetCount).toEqual(expectedTotalDatasetCount) }) test('should return fourth dataset preview page', async () => { - const actual = await sut.getAllDatasetPreviews(testPageLimit, 3) + const actual = await sut.getAllDatasetPreviews( + testPageLimit, + 3, + TestConstants.TEST_CREATED_COLLECTION_ALIAS_1 + ) expect(actual.datasetPreviews.length).toEqual(1) - expect(actual.datasetPreviews[0].title).toMatch('First Dataset') + expect(actual.datasetPreviews[0].persistentId).toMatch(createdDatasetIds[0].persistentId) expect(actual.totalDatasetCount).toEqual(expectedTotalDatasetCount) }) - - test('should return datasets in the specified collection', async () => { - const actual = await sut.getAllDatasetPreviews(testPageLimit, 0, 'firstCollection') - expect(actual.datasetPreviews[0].title).toMatch('Third Dataset') - expect(actual.datasetPreviews.length).toEqual(1) - expect(actual.totalDatasetCount).toEqual(1) - }) }) describe('getDatasetSummaryFieldNames', () => { @@ -101,47 +160,60 @@ describe('DatasetsRepository', () => { describe('getDataset', () => { describe('by numeric id', () => { + let testDatasetIds: CreatedDatasetIdentifiers + + beforeAll(async () => { + testDatasetIds = await createDataset.execute(TestConstants.TEST_NEW_DATASET_DTO) + }) + + afterAll(async () => { + await deletePublishedDatasetViaApi(testDatasetIds.persistentId) + }) + test('should return dataset when it exists filtering by id and version id', async () => { const actual = await sut.getDataset( - TestConstants.TEST_CREATED_DATASET_1_ID, - latestVersionId, + testDatasetIds.numericId, + DatasetNotNumberedVersion.LATEST, false ) - expect(actual.id).toBe(TestConstants.TEST_CREATED_DATASET_1_ID) + expect(actual.id).toBe(testDatasetIds.numericId) }) test('should return dataset when it is deaccessioned and includeDeaccessioned param is set', async () => { - await publishDatasetViaApi(TestConstants.TEST_CREATED_DATASET_2_ID) - - await waitForNoLocks(TestConstants.TEST_CREATED_DATASET_2_ID, 10) - - await deaccessionDatasetViaApi(TestConstants.TEST_CREATED_DATASET_2_ID, '1.0') + await publishDatasetViaApi(testDatasetIds.numericId) + await waitForNoLocks(testDatasetIds.numericId, 10) + await deaccessionDatasetViaApi(testDatasetIds.numericId, '1.0') const actual = await sut.getDataset( - TestConstants.TEST_CREATED_DATASET_2_ID, - latestVersionId, + testDatasetIds.numericId, + DatasetNotNumberedVersion.LATEST, true ) - expect(actual.id).toBe(TestConstants.TEST_CREATED_DATASET_2_ID) + expect(actual.id).toBe(testDatasetIds.numericId) }) test('should return dataset when it is deaccessioned, includeDeaccessioned param is set, and user is unauthenticated', async () => { ApiConfig.init(TestConstants.TEST_API_URL, DataverseApiAuthMechanism.API_KEY, undefined) const actual = await sut.getDataset( - TestConstants.TEST_CREATED_DATASET_2_ID, - latestVersionId, + testDatasetIds.numericId, + DatasetNotNumberedVersion.LATEST, true ) - expect(actual.id).toBe(TestConstants.TEST_CREATED_DATASET_2_ID) + expect(actual.id).toBe(testDatasetIds.numericId) + ApiConfig.init( + TestConstants.TEST_API_URL, + DataverseApiAuthMechanism.API_KEY, + process.env.TEST_API_KEY + ) }) test('should return error when dataset is deaccessioned and includeDeaccessioned param is not set', async () => { const expectedError = new ReadError( - `[404] Dataset version ${latestVersionId} of dataset ${TestConstants.TEST_CREATED_DATASET_2_ID} not found` + `[404] Dataset version ${DatasetNotNumberedVersion.LATEST} of dataset ${testDatasetIds.numericId} not found` ) await expect( - sut.getDataset(TestConstants.TEST_CREATED_DATASET_2_ID, latestVersionId, false) + sut.getDataset(testDatasetIds.numericId, DatasetNotNumberedVersion.LATEST, false) ).rejects.toThrow(expectedError) }) @@ -151,20 +223,34 @@ describe('DatasetsRepository', () => { ) await expect( - sut.getDataset(nonExistentTestDatasetId, latestVersionId, false) + sut.getDataset(nonExistentTestDatasetId, DatasetNotNumberedVersion.LATEST, false) ).rejects.toThrow(expectedError) }) }) describe('by persistent id', () => { + let testDatasetIds: CreatedDatasetIdentifiers + + beforeAll(async () => { + testDatasetIds = await createDataset.execute(TestConstants.TEST_NEW_DATASET_DTO) + }) + + afterAll(async () => { + await deleteUnpublishedDatasetViaApi(testDatasetIds.numericId) + }) + test('should return dataset when it exists filtering by persistent id and version id', async () => { const createdDataset = await sut.getDataset( - TestConstants.TEST_CREATED_DATASET_1_ID, - latestVersionId, + testDatasetIds.numericId, + DatasetNotNumberedVersion.LATEST, + false + ) + const actual = await sut.getDataset( + createdDataset.persistentId, + DatasetNotNumberedVersion.LATEST, false ) - const actual = await sut.getDataset(createdDataset.persistentId, latestVersionId, false) - expect(actual.id).toBe(TestConstants.TEST_CREATED_DATASET_1_ID) + expect(actual.id).toBe(testDatasetIds.numericId) }) test('should return error when dataset does not exist', async () => { @@ -172,35 +258,36 @@ describe('DatasetsRepository', () => { const expectedError = new ReadError( `[404] Dataset with Persistent ID ${testWrongPersistentId} not found.` ) - await expect(sut.getDataset(testWrongPersistentId, latestVersionId, false)).rejects.toThrow( - expectedError - ) + await expect( + sut.getDataset(testWrongPersistentId, DatasetNotNumberedVersion.LATEST, false) + ).rejects.toThrow(expectedError) }) }) }) describe('Private URLs', () => { const expectedErrorInvalidToken = '[404] Private URL user not found' + let testDatasetIds: CreatedDatasetIdentifiers let privateUrlToken: string beforeAll(async () => { - try { - const response = await createPrivateUrlViaApi(TestConstants.TEST_CREATED_DATASET_1_ID) - privateUrlToken = response.data.data.token - } catch (error) { - throw new Error('Tests beforeAll(): Error while creating Dataset private URL') - } + testDatasetIds = await createDataset.execute(TestConstants.TEST_NEW_DATASET_DTO) + const response = await createPrivateUrlViaApi(testDatasetIds.numericId) + privateUrlToken = response.data.data.token + }) + + afterAll(async () => { + await deleteUnpublishedDatasetViaApi(testDatasetIds.numericId) }) describe('getPrivateUrlDataset', () => { test('should return dataset when token is valid', async () => { const actual = await sut.getPrivateUrlDataset(privateUrlToken) - expect(actual.id).toBe(TestConstants.TEST_CREATED_DATASET_1_ID) + expect(actual.id).toBe(testDatasetIds.numericId) }) test('should return error when token is not valid', async () => { const expectedError = new ReadError(expectedErrorInvalidToken) - await expect(sut.getPrivateUrlDataset('invalidToken')).rejects.toThrow(expectedError) }) }) @@ -213,49 +300,62 @@ describe('DatasetsRepository', () => { test('should return error when token is not valid', async () => { const expectedError = new ReadError(expectedErrorInvalidToken) - await expect(sut.getPrivateUrlDatasetCitation('invalidToken')).rejects.toThrow( expectedError ) }) }) + }) - describe('getDatasetUserPermissions', () => { - test('should return user permissions filtering by dataset id', async () => { - const actual = await sut.getDatasetUserPermissions(TestConstants.TEST_CREATED_DATASET_1_ID) - expect(actual.canViewUnpublishedDataset).toBe(true) - expect(actual.canEditDataset).toBe(true) - expect(actual.canPublishDataset).toBe(true) - expect(actual.canManageDatasetPermissions).toBe(true) - expect(actual.canDeleteDatasetDraft).toBe(true) - }) + describe('getDatasetUserPermissions', () => { + let testDatasetIds: CreatedDatasetIdentifiers - test('should return error when dataset does not exist', async () => { - const expectedError = new ReadError( - `[404] Dataset with ID ${nonExistentTestDatasetId} not found.` - ) + beforeAll(async () => { + testDatasetIds = await createDataset.execute(TestConstants.TEST_NEW_DATASET_DTO) + }) - await expect(sut.getDatasetUserPermissions(nonExistentTestDatasetId)).rejects.toThrow( - expectedError - ) - }) + afterAll(async () => { + await deleteUnpublishedDatasetViaApi(testDatasetIds.numericId) + }) + + test('should return user permissions filtering by dataset id', async () => { + const actual = await sut.getDatasetUserPermissions(testDatasetIds.numericId) + expect(actual.canViewUnpublishedDataset).toBe(true) + expect(actual.canEditDataset).toBe(true) + expect(actual.canPublishDataset).toBe(true) + expect(actual.canManageDatasetPermissions).toBe(true) + expect(actual.canDeleteDatasetDraft).toBe(true) + }) + + test('should return error when dataset does not exist', async () => { + const expectedError = new ReadError( + `[404] Dataset with ID ${nonExistentTestDatasetId} not found.` + ) + + await expect(sut.getDatasetUserPermissions(nonExistentTestDatasetId)).rejects.toThrow( + expectedError + ) }) }) describe('getDatasetLocks', () => { + let testDatasetIds: CreatedDatasetIdentifiers + + beforeAll(async () => { + testDatasetIds = await createDataset.execute(TestConstants.TEST_NEW_DATASET_DTO) + }) + + afterAll(async () => { + await deletePublishedDatasetViaApi(testDatasetIds.persistentId) + }) + test('should return list of dataset locks by dataset id for a dataset while publishing', async () => { - await publishDatasetViaApi(TestConstants.TEST_CREATED_DATASET_2_ID) - .then() - .catch((error) => { - console.log(JSON.stringify(error)) - }) - const actual = await sut.getDatasetLocks(TestConstants.TEST_CREATED_DATASET_2_ID) + await publishDatasetViaApi(testDatasetIds.numericId) + const actual = await sut.getDatasetLocks(testDatasetIds.numericId) expect(actual.length).toBe(1) expect(actual[0].lockType).toBe(DatasetLockType.FINALIZE_PUBLICATION) expect(actual[0].userId).toBe('dataverseAdmin') - expect(actual[0].message).toBe( - 'Publishing the dataset; Registering PIDs for Datafiles; Validating Datafiles Asynchronously' - ) + expect(actual[0].message).toContain('Publishing the dataset') }) test('should return error when dataset does not exist', async () => { @@ -268,10 +368,20 @@ describe('DatasetsRepository', () => { }) describe('getDatasetCitation', () => { + let testDatasetIds: CreatedDatasetIdentifiers + + beforeAll(async () => { + testDatasetIds = await createDataset.execute(TestConstants.TEST_NEW_DATASET_DTO) + }) + + afterAll(async () => { + await deletePublishedDatasetViaApi(testDatasetIds.persistentId) + }) + test('should return citation when dataset exists', async () => { const actualDatasetCitation = await sut.getDatasetCitation( - TestConstants.TEST_CREATED_DATASET_1_ID, - latestVersionId, + testDatasetIds.numericId, + DatasetNotNumberedVersion.LATEST, false ) expect(typeof actualDatasetCitation).toBe('string') @@ -283,16 +393,21 @@ describe('DatasetsRepository', () => { ) await expect( - sut.getDatasetCitation(nonExistentTestDatasetId, latestVersionId, false) + sut.getDatasetCitation(nonExistentTestDatasetId, DatasetNotNumberedVersion.LATEST, false) ).rejects.toThrow(expectedError) }) test('should return citation when dataset is deaccessioned', async () => { + await publishDatasetViaApi(testDatasetIds.numericId) + await waitForNoLocks(testDatasetIds.numericId, 10) + await deaccessionDatasetViaApi(testDatasetIds.numericId, '1.0') + const actualDatasetCitation = await sut.getDatasetCitation( - TestConstants.TEST_CREATED_DATASET_2_ID, - latestVersionId, + testDatasetIds.numericId, + DatasetNotNumberedVersion.LATEST, true ) + expect(typeof actualDatasetCitation).toBe('string') }) }) @@ -343,7 +458,7 @@ describe('DatasetsRepository', () => { ) const actualCreatedDataset = await sut.getDataset( createdDataset.numericId, - latestVersionId, + DatasetNotNumberedVersion.LATEST, false ) @@ -381,16 +496,26 @@ describe('DatasetsRepository', () => { }) describe('publishDataset', () => { + let testDatasetIds: CreatedDatasetIdentifiers + + beforeAll(async () => { + testDatasetIds = await createDataset.execute(TestConstants.TEST_NEW_DATASET_DTO) + }) + + afterAll(async () => { + await deletePublishedDatasetViaApi(testDatasetIds.persistentId) + }) + test('should publish a new dataset version', async () => { const expectedMajorVersion = 1 - await waitForNoLocks(TestConstants.TEST_CREATED_DATASET_4_ID, 10) + await waitForNoLocks(testDatasetIds.numericId, 10) - await sut.publishDataset(TestConstants.TEST_CREATED_DATASET_4_ID, VersionUpdateType.MAJOR) - await waitForNoLocks(TestConstants.TEST_CREATED_DATASET_4_ID, 10) + await sut.publishDataset(testDatasetIds.numericId, VersionUpdateType.MAJOR) + await waitForNoLocks(testDatasetIds.numericId, 10) const newDatasetVersion = await sut.getDataset( - TestConstants.TEST_CREATED_DATASET_4_ID, - latestVersionId, + testDatasetIds.numericId, + DatasetNotNumberedVersion.LATEST, false ) diff --git a/test/integration/files/FilesRepository.test.ts b/test/integration/files/FilesRepository.test.ts index ec755977..c133b8d9 100644 --- a/test/integration/files/FilesRepository.test.ts +++ b/test/integration/files/FilesRepository.test.ts @@ -5,26 +5,33 @@ import { } from '../../../src/core/infra/repositories/ApiConfig' import { TestConstants } from '../../testHelpers/TestConstants' import { registerFileViaApi, uploadFileViaApi } from '../../testHelpers/files/filesHelper' -import { DatasetsRepository } from '../../../src/datasets/infra/repositories/DatasetsRepository' import { ReadError } from '../../../src/core/domain/repositories/ReadError' import { FileSearchCriteria, FileAccessStatus, FileOrderCriteria } from '../../../src/files/domain/models/FileCriteria' -import { DatasetNotNumberedVersion, Dataset } from '../../../src/datasets' +import { + DatasetNotNumberedVersion, + Dataset, + CreatedDatasetIdentifiers, + createDataset +} from '../../../src/datasets' import { File } from '../../../src/files/domain/models/File' import { FileCounts } from '../../../src/files/domain/models/FileCounts' import { FileDownloadSizeMode } from '../../../src' import { deaccessionDatasetViaApi, publishDatasetViaApi, - waitForNoLocks + waitForNoLocks, + deletePublishedDatasetViaApi } from '../../testHelpers/datasets/datasetHelper' describe('FilesRepository', () => { const sut: FilesRepository = new FilesRepository() + let testDatasetIds: CreatedDatasetIdentifiers + const testTextFile1Name = 'test-file-1.txt' const testTextFile2Name = 'test-file-2.txt' const testTextFile3Name = 'test-file-3.txt' @@ -35,43 +42,45 @@ describe('FilesRepository', () => { const latestDatasetVersionId = DatasetNotNumberedVersion.LATEST - const datasetRepository = new DatasetsRepository() - let testFileId: number let testFilePersistentId: string + beforeAll(async () => { ApiConfig.init( TestConstants.TEST_API_URL, DataverseApiAuthMechanism.API_KEY, process.env.TEST_API_KEY ) + try { + testDatasetIds = await createDataset.execute(TestConstants.TEST_NEW_DATASET_DTO) + } catch (error) { + throw new Error('Tests beforeAll(): Error while creating test dataset') + } // Uploading test file 1 with some categories - const uploadFileResponse = await uploadFileViaApi( - TestConstants.TEST_CREATED_DATASET_1_ID, - testTextFile1Name, - { categories: [testCategoryName] } - ) + const uploadFileResponse = await uploadFileViaApi(testDatasetIds.numericId, testTextFile1Name, { + categories: [testCategoryName] + }) .then() .catch((e) => { console.log(e) throw new Error(`Tests beforeAll(): Error while uploading file ${testTextFile1Name}`) }) // Uploading test file 2 - await uploadFileViaApi(TestConstants.TEST_CREATED_DATASET_1_ID, testTextFile2Name) + await uploadFileViaApi(testDatasetIds.numericId, testTextFile2Name) .then() .catch((e) => { console.log(e) throw new Error(`Tests beforeAll(): Error while uploading file ${testTextFile2Name}`) }) // Uploading test file 3 - await uploadFileViaApi(TestConstants.TEST_CREATED_DATASET_1_ID, testTextFile3Name) + await uploadFileViaApi(testDatasetIds.numericId, testTextFile3Name) .then() .catch((e) => { console.log(e) throw new Error(`Tests beforeAll(): Error while uploading file ${testTextFile3Name}`) }) // Uploading test file 4 - await uploadFileViaApi(TestConstants.TEST_CREATED_DATASET_1_ID, testTabFile4Name) + await uploadFileViaApi(testDatasetIds.numericId, testTabFile4Name) .then() .catch((e) => { console.log(e) @@ -80,7 +89,7 @@ describe('FilesRepository', () => { // Registering test file 1 await registerFileViaApi(uploadFileResponse.data.data.files[0].dataFile.id) const filesSubset = await sut.getDatasetFiles( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, FileOrderCriteria.NAME_AZ @@ -89,6 +98,14 @@ describe('FilesRepository', () => { testFilePersistentId = filesSubset.files[0].persistentId }) + afterAll(async () => { + try { + await deletePublishedDatasetViaApi(testDatasetIds.persistentId) + } catch (error) { + throw new Error('Tests afterAll(): Error while deleting test dataset') + } + }) + describe('getDatasetFiles', () => { const testFileCriteria = new FileSearchCriteria() .withContentType('text/plain') @@ -97,7 +114,7 @@ describe('FilesRepository', () => { describe('by numeric id', () => { test('should return all files filtering by dataset id and version id', async () => { const actual = await sut.getDatasetFiles( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, FileOrderCriteria.NAME_AZ @@ -113,7 +130,7 @@ describe('FilesRepository', () => { test('should return correct files filtering by dataset id, version id, and paginating', async () => { const actual = await sut.getDatasetFiles( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, FileOrderCriteria.NAME_AZ, @@ -129,7 +146,7 @@ describe('FilesRepository', () => { test('should return correct files filtering by dataset id, version id, and applying newest file criteria', async () => { const actual = await sut.getDatasetFiles( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, FileOrderCriteria.NEWEST, @@ -164,13 +181,8 @@ describe('FilesRepository', () => { describe('by persistent id', () => { test('should return all files filtering by persistent id and version id', async () => { - const testDataset = await datasetRepository.getDataset( - TestConstants.TEST_CREATED_DATASET_1_ID, - latestDatasetVersionId, - false - ) const actual = await sut.getDatasetFiles( - testDataset.persistentId, + testDatasetIds.persistentId, latestDatasetVersionId, false, FileOrderCriteria.NAME_AZ @@ -185,13 +197,8 @@ describe('FilesRepository', () => { }) test('should return correct files filtering by persistent id, version id, and paginating', async () => { - const testDataset = await datasetRepository.getDataset( - TestConstants.TEST_CREATED_DATASET_1_ID, - latestDatasetVersionId, - false - ) const actual = await sut.getDatasetFiles( - testDataset.persistentId, + testDatasetIds.persistentId, latestDatasetVersionId, false, FileOrderCriteria.NAME_AZ, @@ -206,13 +213,8 @@ describe('FilesRepository', () => { }) test('should return correct files filtering by persistent id, version id, and applying newest file criteria', async () => { - const testDataset = await datasetRepository.getDataset( - TestConstants.TEST_CREATED_DATASET_1_ID, - latestDatasetVersionId, - false - ) const actual = await sut.getDatasetFiles( - testDataset.persistentId, + testDatasetIds.persistentId, latestDatasetVersionId, false, FileOrderCriteria.NEWEST, @@ -275,7 +277,7 @@ describe('FilesRepository', () => { test('should return file count filtering by numeric id', async () => { const actual = await sut.getDatasetFileCounts( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false ) @@ -312,7 +314,7 @@ describe('FilesRepository', () => { } const testCriteria = new FileSearchCriteria().withCategoryName(testCategoryName) const actual = await sut.getDatasetFileCounts( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, testCriteria @@ -325,13 +327,8 @@ describe('FilesRepository', () => { }) test('should return file count filtering by persistent id', async () => { - const testDataset = await datasetRepository.getDataset( - TestConstants.TEST_CREATED_DATASET_1_ID, - latestDatasetVersionId, - false - ) const actual = await sut.getDatasetFileCounts( - testDataset.persistentId, + testDatasetIds.persistentId, latestDatasetVersionId, false ) @@ -350,7 +347,7 @@ describe('FilesRepository', () => { test('should return total download size filtering by numeric id and ignoring original tabular size', async () => { const actual = await sut.getDatasetFilesTotalDownloadSize( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, FileDownloadSizeMode.ORIGINAL @@ -359,13 +356,8 @@ describe('FilesRepository', () => { }) test('should return total download size filtering by persistent id and ignoring original tabular size', async () => { - const testDataset = await datasetRepository.getDataset( - TestConstants.TEST_CREATED_DATASET_1_ID, - latestDatasetVersionId, - false - ) const actual = await sut.getDatasetFilesTotalDownloadSize( - testDataset.persistentId, + testDatasetIds.persistentId, latestDatasetVersionId, false, FileDownloadSizeMode.ORIGINAL @@ -377,7 +369,7 @@ describe('FilesRepository', () => { const expectedTotalDownloadSizeForCriteria = 12 // 12 bytes const testCriteria = new FileSearchCriteria().withCategoryName(testCategoryName) const actual = await sut.getDatasetFilesTotalDownloadSize( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, FileDownloadSizeMode.ORIGINAL, @@ -390,7 +382,7 @@ describe('FilesRepository', () => { describe('getFileDownloadCount', () => { test('should return count filtering by file id and version id', async () => { const currentTestFilesSubset = await sut.getDatasetFiles( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, FileOrderCriteria.NAME_AZ @@ -410,7 +402,7 @@ describe('FilesRepository', () => { describe('getFileUserPermissions', () => { test('should return user permissions filtering by file id and version id', async () => { const currentTestFilesSubset = await sut.getDatasetFiles( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, FileOrderCriteria.NAME_AZ @@ -433,7 +425,7 @@ describe('FilesRepository', () => { describe('getFileDataTables', () => { test('should return data tables filtering by tabular file id and version id', async () => { const currentTestFilesSubset = await sut.getDatasetFiles( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, FileOrderCriteria.NAME_AZ @@ -445,7 +437,7 @@ describe('FilesRepository', () => { test('should return error when file is not tabular and version id', async () => { const currentTestFilesSubset = await sut.getDatasetFiles( - TestConstants.TEST_CREATED_DATASET_1_ID, + testDatasetIds.numericId, latestDatasetVersionId, false, FileOrderCriteria.NAME_AZ @@ -495,7 +487,7 @@ describe('FilesRepository', () => { ] expect(actual[0].name).toBe(testTextFile1Name) - expect(actual[1].id).toBe(TestConstants.TEST_CREATED_DATASET_1_ID) + expect(actual[1].id).toBe(testDatasetIds.numericId) }) test('should return error when file does not exist', async () => { @@ -552,19 +544,19 @@ describe('FilesRepository', () => { }) test('should return citation when dataset is deaccessioned', async () => { - await publishDatasetViaApi(TestConstants.TEST_CREATED_DATASET_1_ID) + await publishDatasetViaApi(testDatasetIds.numericId) .then() .catch(() => { throw new Error('Error while publishing test Dataset') }) - await waitForNoLocks(TestConstants.TEST_CREATED_DATASET_1_ID, 10) + await waitForNoLocks(testDatasetIds.numericId, 10) .then() .catch(() => { throw new Error('Error while waiting for no locks') }) - await deaccessionDatasetViaApi(TestConstants.TEST_CREATED_DATASET_1_ID, '1.0') + await deaccessionDatasetViaApi(testDatasetIds.numericId, '1.0') .then() .catch(() => { throw new Error('Error while deaccessioning test Dataset') diff --git a/test/testHelpers/TestConstants.ts b/test/testHelpers/TestConstants.ts index 37d59b6e..602443b5 100644 --- a/test/testHelpers/TestConstants.ts +++ b/test/testHelpers/TestConstants.ts @@ -1,4 +1,4 @@ -import { ROOT_COLLECTION_ALIAS } from '../../src/collections/domain/models/Collection' +import { NewDatasetDTO } from '../../src/datasets/domain/dtos/NewDatasetDTO' export class TestConstants { static readonly TEST_API_URL = 'http://localhost:8080/api/v1' @@ -45,13 +45,45 @@ export class TestConstants { 'Content-Type': 'application/json' } } - static readonly TEST_CREATED_DATASET_1_ID = 2 - static readonly TEST_CREATED_DATASET_2_ID = 3 - static readonly TEST_CREATED_DATASET_3_ID = 5 - static readonly TEST_CREATED_DATASET_4_ID = 4 static readonly TEST_DUMMY_COLLECTION_ID = 10001 static readonly TEST_DUMMY_COLLECTION_ALIAS = 'dummyCollectionId' - static readonly TEST_CREATED_COLLECTION_1_ID = 5 - static readonly TEST_CREATED_COLLECTION_1_ALIAS = 'firstCollection' - static readonly TEST_CREATED_COLLECTION_1_ROOT = ROOT_COLLECTION_ALIAS + static readonly TEST_CREATED_COLLECTION_ALIAS_1 = 'testCollection1' + static readonly TEST_CREATED_COLLECTION_ALIAS_2 = 'testCollection2' + static readonly TEST_NEW_DATASET_DTO: NewDatasetDTO = { + license: { + name: 'CC0 1.0', + uri: 'http://creativecommons.org/publicdomain/zero/1.0', + iconUri: 'https://licensebuttons.net/p/zero/1.0/88x31.png' + }, + metadataBlockValues: [ + { + name: 'citation', + fields: { + title: 'Dataset created using the createDataset use case', + author: [ + { + authorName: 'Admin, Dataverse', + authorAffiliation: 'Dataverse.org' + }, + { + authorName: 'Owner, Dataverse', + authorAffiliation: 'Dataversedemo.org' + } + ], + datasetContact: [ + { + datasetContactEmail: 'finch@mailinator.com', + datasetContactName: 'Finch, Fiona' + } + ], + dsDescription: [ + { + dsDescriptionValue: 'This is the description of the dataset.' + } + ], + subject: ['Medicine, Health and Life Sciences'] + } + } + ] + } } diff --git a/test/testHelpers/collections/collectionHelper.ts b/test/testHelpers/collections/collectionHelper.ts index 54fce423..9819bb1d 100644 --- a/test/testHelpers/collections/collectionHelper.ts +++ b/test/testHelpers/collections/collectionHelper.ts @@ -1,13 +1,23 @@ import { Collection } from '../../../src/collections' import { DvObjectType } from '../../../src' import { CollectionPayload } from '../../../src/collections/infra/repositories/transformers/CollectionPayload' +import { TestConstants } from '../TestConstants' +import axios from 'axios' +import collectionJson1 from './test-collection-1.json' +import collectionJson2 from './test-collection-2.json' const COLLECTION_ID = 11111 const COLLECTION_ALIAS_STR = 'secondCollection' const COLLECTION_NAME_STR = 'Laboratory Research' const COLLECTION_AFFILIATION_STR = 'Laboratory Research Corporation' + const COLLECTION_DESCRIPTION_HTML = 'This is an example collection used for testing.' const COLLECTION_DESCRIPTION_MARKDOWN = 'This is an **example** collection used for testing.' + +const DATAVERSE_API_REQUEST_HEADERS = { + headers: { 'Content-Type': 'application/json', 'X-Dataverse-Key': process.env.TEST_API_KEY } +} + export const createCollectionModel = (): Collection => { const collectionModel: Collection = { id: COLLECTION_ID, @@ -31,3 +41,30 @@ export const createCollectionPayload = (): CollectionPayload => { } return collectionPayload } + +export async function createCollectionViaApi(collectionAlias: string): Promise { + try { + return await axios + .post( + `${TestConstants.TEST_API_URL}/dataverses/root`, + collectionAlias == TestConstants.TEST_CREATED_COLLECTION_ALIAS_1 + ? collectionJson1 + : collectionJson2, + DATAVERSE_API_REQUEST_HEADERS + ) + .then((response) => response.data.data) + } catch (error) { + throw new Error(`Error while creating test collection ${collectionAlias}`) + } +} + +export async function deleteCollectionViaApi(collectionAlias: string): Promise { + try { + return await axios.delete( + `${TestConstants.TEST_API_URL}/dataverses/${collectionAlias}`, + DATAVERSE_API_REQUEST_HEADERS + ) + } catch (error) { + throw new Error(`Error while deleting test collection ${collectionAlias}`) + } +} diff --git a/test/testHelpers/collections/test-collection-1.json b/test/testHelpers/collections/test-collection-1.json index f23d819c..e3449bf7 100644 --- a/test/testHelpers/collections/test-collection-1.json +++ b/test/testHelpers/collections/test-collection-1.json @@ -1,6 +1,5 @@ { - "id": 4, - "alias": "firstCollection", + "alias": "testCollection1", "name": "Scientific Research", "dataverseContacts": [ { diff --git a/test/testHelpers/collections/test-collection-2.json b/test/testHelpers/collections/test-collection-2.json new file mode 100644 index 00000000..e0cfaf60 --- /dev/null +++ b/test/testHelpers/collections/test-collection-2.json @@ -0,0 +1,15 @@ +{ + "alias": "testCollection2", + "name": "Scientific Research", + "dataverseContacts": [ + { + "contactEmail": "pi@example.edu" + }, + { + "contactEmail": "student@example.edu" + } + ], + "affiliation": "Scientific Research University", + "description": "We do all the science.", + "dataverseType": "LABORATORY" +} diff --git a/test/testHelpers/datasets/datasetHelper.ts b/test/testHelpers/datasets/datasetHelper.ts index c276d4e5..14aab6e7 100644 --- a/test/testHelpers/datasets/datasetHelper.ts +++ b/test/testHelpers/datasets/datasetHelper.ts @@ -202,6 +202,30 @@ export const createDatasetVersionPayload = ( return datasetPayload } +export const deleteUnpublishedDatasetViaApi = async (datasetId: number): Promise => { + try { + return await axios.delete( + `${TestConstants.TEST_API_URL}/datasets/${datasetId}`, + DATAVERSE_API_REQUEST_HEADERS + ) + } catch (error) { + throw new Error(`Error while deleting unpublished test dataset ${datasetId}`) + } +} + +export const deletePublishedDatasetViaApi = async ( + datasetPersistentId: string +): Promise => { + try { + return await axios.delete( + `${TestConstants.TEST_API_URL}/datasets/:persistentId/destroy?persistentId=${datasetPersistentId}`, + DATAVERSE_API_REQUEST_HEADERS + ) + } catch (error) { + throw new Error(`Error while deleting published test dataset ${datasetPersistentId}`) + } +} + export const createDatasetLicenseModel = (withIconUri = true): DatasetLicense => { const datasetLicense: DatasetLicense = { name: 'CC0 1.0', @@ -214,31 +238,43 @@ export const createDatasetLicenseModel = (withIconUri = true): DatasetLicense => } export const publishDatasetViaApi = async (datasetId: number): Promise => { - return await axios.post( - `${TestConstants.TEST_API_URL}/datasets/${datasetId}/actions/:publish?type=major`, - {}, - DATAVERSE_API_REQUEST_HEADERS - ) + try { + return await axios.post( + `${TestConstants.TEST_API_URL}/datasets/${datasetId}/actions/:publish?type=major`, + {}, + DATAVERSE_API_REQUEST_HEADERS + ) + } catch (error) { + throw new Error(`Error while publishing test dataset ${datasetId}`) + } } export const deaccessionDatasetViaApi = async ( datasetId: number, versionId: string ): Promise => { - const data = { deaccessionReason: 'Test reason.' } - return await axios.post( - `${TestConstants.TEST_API_URL}/datasets/${datasetId}/versions/${versionId}/deaccession`, - JSON.stringify(data), - DATAVERSE_API_REQUEST_HEADERS - ) + try { + const data = { deaccessionReason: 'Test reason.' } + return await axios.post( + `${TestConstants.TEST_API_URL}/datasets/${datasetId}/versions/${versionId}/deaccession`, + JSON.stringify(data), + DATAVERSE_API_REQUEST_HEADERS + ) + } catch (error) { + throw new Error(`Error while deaccessioning test dataset ${datasetId}`) + } } export const createPrivateUrlViaApi = async (datasetId: number): Promise => { - return await axios.post( - `${TestConstants.TEST_API_URL}/datasets/${datasetId}/privateUrl`, - {}, - DATAVERSE_API_REQUEST_HEADERS - ) + try { + return await axios.post( + `${TestConstants.TEST_API_URL}/datasets/${datasetId}/privateUrl`, + {}, + DATAVERSE_API_REQUEST_HEADERS + ) + } catch (error) { + throw new Error(`Error while creating private URL for dataset ${datasetId}`) + } } export const waitForNoLocks = async ( @@ -271,3 +307,36 @@ export const waitForNoLocks = async ( throw new Error('Max retries reached.') } } + +export async function waitForDatasetsIndexedInSolr( + expectedNumberOfIndexedDatasets: number, + collectionAlias: string +): Promise { + let datasetsIndexed = false + let retry = 0 + while (!datasetsIndexed && retry < 10) { + await axios + .get( + `${TestConstants.TEST_API_URL}/search?q=*&type=dataset&subtree=${collectionAlias}`, + DATAVERSE_API_REQUEST_HEADERS + ) + .then((response) => { + const nDatasets = response.data.data.items.length + if (nDatasets === expectedNumberOfIndexedDatasets) { + datasetsIndexed = true + } + }) + .catch((error) => { + console.error( + `Error while waiting for datasets indexing in Solr: [${error.response.status}]${ + error.response.data ? ` ${error.response.data.message}` : '' + }` + ) + }) + await new Promise((resolve) => setTimeout(resolve, 1000)) + retry++ + } + if (!datasetsIndexed) { + throw new Error('Timeout reached while waiting for datasets indexing in Solr') + } +} diff --git a/test/testHelpers/datasets/test-dataset-1.json b/test/testHelpers/datasets/test-dataset-1.json deleted file mode 100644 index 10c93200..00000000 --- a/test/testHelpers/datasets/test-dataset-1.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "datasetVersion": { - "license": { - "name": "CC0 1.0", - "uri": "http://creativecommons.org/publicdomain/zero/1.0", - "iconUri": "https://licensebuttons.net/p/zero/1.0/88x31.png" - }, - "metadataBlocks": { - "citation": { - "fields": [ - { - "value": "First Dataset", - "typeClass": "primitive", - "multiple": false, - "typeName": "title" - }, - { - "value": [ - { - "authorName": { - "value": "Finch, Fiona", - "typeClass": "primitive", - "multiple": false, - "typeName": "authorName" - }, - "authorAffiliation": { - "value": "Birds Inc.", - "typeClass": "primitive", - "multiple": false, - "typeName": "authorAffiliation" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "author" - }, - { - "value": [ - { - "datasetContactEmail": { - "typeClass": "primitive", - "multiple": false, - "typeName": "datasetContactEmail", - "value": "finch@mailinator.com" - }, - "datasetContactName": { - "typeClass": "primitive", - "multiple": false, - "typeName": "datasetContactName", - "value": "Finch, Fiona" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "datasetContact" - }, - { - "value": [ - { - "dsDescriptionValue": { - "value": "This is the description of the first dataset.", - "multiple": false, - "typeClass": "primitive", - "typeName": "dsDescriptionValue" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "dsDescription" - }, - { - "value": ["Medicine, Health and Life Sciences"], - "typeClass": "controlledVocabulary", - "multiple": true, - "typeName": "subject" - } - ], - "displayName": "Citation Metadata" - } - } - } -} diff --git a/test/testHelpers/datasets/test-dataset-2.json b/test/testHelpers/datasets/test-dataset-2.json deleted file mode 100644 index 7cfce6bb..00000000 --- a/test/testHelpers/datasets/test-dataset-2.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "datasetVersion": { - "license": { - "name": "CC0 1.0", - "uri": "http://creativecommons.org/publicdomain/zero/1.0", - "iconUri": "https://licensebuttons.net/p/zero/1.0/88x31.png" - }, - "metadataBlocks": { - "citation": { - "fields": [ - { - "value": "Second Dataset", - "typeClass": "primitive", - "multiple": false, - "typeName": "title" - }, - { - "value": [ - { - "authorName": { - "value": "Finch, Fiona", - "typeClass": "primitive", - "multiple": false, - "typeName": "authorName" - }, - "authorAffiliation": { - "value": "Birds Inc.", - "typeClass": "primitive", - "multiple": false, - "typeName": "authorAffiliation" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "author" - }, - { - "value": [ - { - "datasetContactEmail": { - "typeClass": "primitive", - "multiple": false, - "typeName": "datasetContactEmail", - "value": "finch@mailinator.com" - }, - "datasetContactName": { - "typeClass": "primitive", - "multiple": false, - "typeName": "datasetContactName", - "value": "Finch, Fiona" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "datasetContact" - }, - { - "value": [ - { - "dsDescriptionValue": { - "value": "This is the description of the second dataset.", - "multiple": false, - "typeClass": "primitive", - "typeName": "dsDescriptionValue" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "dsDescription" - }, - { - "value": ["Medicine, Health and Life Sciences"], - "typeClass": "controlledVocabulary", - "multiple": true, - "typeName": "subject" - } - ], - "displayName": "Citation Metadata" - } - } - } -} diff --git a/test/testHelpers/datasets/test-dataset-3.json b/test/testHelpers/datasets/test-dataset-3.json deleted file mode 100644 index 4f867c90..00000000 --- a/test/testHelpers/datasets/test-dataset-3.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "datasetVersion": { - "license": { - "name": "CC0 1.0", - "uri": "http://creativecommons.org/publicdomain/zero/1.0", - "iconUri": "https://licensebuttons.net/p/zero/1.0/88x31.png" - }, - "metadataBlocks": { - "citation": { - "fields": [ - { - "value": "Third Dataset", - "typeClass": "primitive", - "multiple": false, - "typeName": "title" - }, - { - "value": [ - { - "authorName": { - "value": "Finch, Fiona", - "typeClass": "primitive", - "multiple": false, - "typeName": "authorName" - }, - "authorAffiliation": { - "value": "Birds Inc.", - "typeClass": "primitive", - "multiple": false, - "typeName": "authorAffiliation" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "author" - }, - { - "value": [ - { - "datasetContactEmail": { - "typeClass": "primitive", - "multiple": false, - "typeName": "datasetContactEmail", - "value": "finch@mailinator.com" - }, - "datasetContactName": { - "typeClass": "primitive", - "multiple": false, - "typeName": "datasetContactName", - "value": "Finch, Fiona" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "datasetContact" - }, - { - "value": [ - { - "dsDescriptionValue": { - "value": "This is the description of the third dataset.", - "multiple": false, - "typeClass": "primitive", - "typeName": "dsDescriptionValue" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "dsDescription" - }, - { - "value": ["Medicine, Health and Life Sciences"], - "typeClass": "controlledVocabulary", - "multiple": true, - "typeName": "subject" - } - ], - "displayName": "Citation Metadata" - } - } - } -} diff --git a/test/testHelpers/datasets/test-dataset-4.json b/test/testHelpers/datasets/test-dataset-4.json deleted file mode 100644 index 9ae58df5..00000000 --- a/test/testHelpers/datasets/test-dataset-4.json +++ /dev/null @@ -1,85 +0,0 @@ -{ - "datasetVersion": { - "license": { - "name": "CC0 1.0", - "uri": "http://creativecommons.org/publicdomain/zero/1.0", - "iconUri": "https://licensebuttons.net/p/zero/1.0/88x31.png" - }, - "metadataBlocks": { - "citation": { - "fields": [ - { - "value": "Fourth Dataset", - "typeClass": "primitive", - "multiple": false, - "typeName": "title" - }, - { - "value": [ - { - "authorName": { - "value": "Finch, Fiona", - "typeClass": "primitive", - "multiple": false, - "typeName": "authorName" - }, - "authorAffiliation": { - "value": "Birds Inc.", - "typeClass": "primitive", - "multiple": false, - "typeName": "authorAffiliation" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "author" - }, - { - "value": [ - { - "datasetContactEmail": { - "typeClass": "primitive", - "multiple": false, - "typeName": "datasetContactEmail", - "value": "finch@mailinator.com" - }, - "datasetContactName": { - "typeClass": "primitive", - "multiple": false, - "typeName": "datasetContactName", - "value": "Finch, Fiona" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "datasetContact" - }, - { - "value": [ - { - "dsDescriptionValue": { - "value": "This is the description of the third dataset.", - "multiple": false, - "typeClass": "primitive", - "typeName": "dsDescriptionValue" - } - } - ], - "typeClass": "compound", - "multiple": true, - "typeName": "dsDescription" - }, - { - "value": ["Medicine, Health and Life Sciences"], - "typeClass": "controlledVocabulary", - "multiple": true, - "typeName": "subject" - } - ], - "displayName": "Citation Metadata" - } - } - } -} diff --git a/test/unit/collections/CollectionsRepository.test.ts b/test/unit/collections/CollectionsRepository.test.ts index 8e8ed6d9..0c716556 100644 --- a/test/unit/collections/CollectionsRepository.test.ts +++ b/test/unit/collections/CollectionsRepository.test.ts @@ -10,6 +10,7 @@ import { } from '../../testHelpers/collections/collectionHelper' import { TestConstants } from '../../testHelpers/TestConstants' import { ReadError } from '../../../src' +import { ROOT_COLLECTION_ALIAS } from '../../../src/collections/domain/models/Collection' describe('CollectionsRepository', () => { const sut: CollectionsRepository = new CollectionsRepository() @@ -85,7 +86,7 @@ describe('CollectionsRepository', () => { describe('by default root id', () => { test('should return a Collection when no collection id, using ROOT instead is successful', async () => { jest.spyOn(axios, 'get').mockResolvedValue(testCollectionSuccessfulResponse) - const expectedApiEndpoint = `${TestConstants.TEST_API_URL}/dataverses/${TestConstants.TEST_CREATED_COLLECTION_1_ROOT}` + const expectedApiEndpoint = `${TestConstants.TEST_API_URL}/dataverses/${ROOT_COLLECTION_ALIAS}` // API Key auth const actual = await sut.getCollection() @@ -96,7 +97,7 @@ describe('CollectionsRepository', () => { test('should return error on repository read error', async () => { jest.spyOn(axios, 'get').mockRejectedValue(TestConstants.TEST_ERROR_RESPONSE) - const expectedApiEndpoint = `${TestConstants.TEST_API_URL}/dataverses/${TestConstants.TEST_CREATED_COLLECTION_1_ROOT}` + const expectedApiEndpoint = `${TestConstants.TEST_API_URL}/dataverses/${ROOT_COLLECTION_ALIAS}` let error = undefined as unknown as ReadError