Skip to content

Commit

Permalink
Fix most tests
Browse files Browse the repository at this point in the history
  • Loading branch information
NickPhura committed Jan 12, 2024
1 parent 5bbe6ec commit d713b8b
Show file tree
Hide file tree
Showing 9 changed files with 271 additions and 1,017 deletions.
858 changes: 0 additions & 858 deletions api/src/paths/artifact/intake.test.ts

This file was deleted.

104 changes: 93 additions & 11 deletions api/src/paths/submission/intake.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,15 +83,48 @@ describe('intake', () => {
const dbConnectionObj = getMockDBConnection();

sinon.stub(db, 'getDBConnection').returns(dbConnectionObj);
sinon.stub(keycloakUtils, 'getServiceClientSystemUser').returns({} as unknown as SystemUser);

const serviceClientSystemUser: SystemUser = {
system_user_id: 3,
user_identifier: 'sims',
user_guid: 'service-account-sims',
user_identity_source_id: 5,
record_effective_date: '2024-01-01',
record_end_date: null,
create_user: 1,
create_date: '2024-01-01',
update_user: null,
update_date: null,
revision_count: 0
};

sinon.stub(keycloakUtils, 'getServiceClientSystemUser').returns(serviceClientSystemUser);

const validateSubmissionFeaturesStub = sinon
.stub(ValidationService.prototype, 'validateSubmissionFeatures')
.resolves(true);

const submissionId = 1;

const insertSubmissionRecordWithPotentialConflictStub = sinon
.stub(SubmissionService.prototype, 'insertSubmissionRecordWithPotentialConflict')
.resolves({ submission_id: 1 });
.resolves({
submission_id: submissionId,
uuid: '123-456-789',
source_id: '123',
security_review_timestamp: '2023-12-12',
submitted_timestamp: '2023-12-12',
system_user_id: 3,
source_system: 'SIMS',
name: 'name',
description: 'description',
publish_timestamp: '2023-12-12',
create_date: '2023-12-12',
create_user: 1,
update_date: null,
update_user: null,
revision_count: 0
});

const insertSubmissionFeatureRecordsStub = sinon
.stub(SubmissionService.prototype, 'insertSubmissionFeatureRecords')
Expand All @@ -101,25 +134,74 @@ describe('intake', () => {
.stub(SearchIndexService.prototype, 'indexFeaturesBySubmissionId')
.resolves();

const findSubmissionFeaturesStub = sinon.stub(SubmissionService.prototype, 'findSubmissionFeatures').resolves([
{
submission_feature_id: 2,
submission_id: submissionId,
feature_type_id: 3,
uuid: '321-645-978',
source_id: '4',
data: {
filename: 'test-file.txt'
},
parent_submission_feature_id: null,
record_effective_date: '',
record_end_date: null,
create_date: '',
create_user: 1,
update_date: null,
update_user: null,
revision_count: 1
}
]);

const requestHandler = intake.submissionIntake();

const { mockReq, mockRes, mockNext } = getRequestHandlerMocks();

mockReq.body = {
id: '123-456-789',
type: 'submission',
properties: { additionalInformation: 'test' },
const feature1 = {
id: '2',
type: 'dataset',
properties: {
name: 'dataset two'
},
features: []
};

mockReq.body = {
id: '564-987-789',
name: 'test submission',
description: 'a test submission',
features: [feature1]
};

await requestHandler(mockReq, mockRes, mockNext);

expect(validateSubmissionFeaturesStub).to.have.been.calledOnce;
expect(insertSubmissionRecordWithPotentialConflictStub).to.have.been.calledOnce;
expect(insertSubmissionFeatureRecordsStub).to.have.been.calledOnce;
expect(indexFeaturesBySubmissionIdStub).to.have.been.calledOnce;
expect(validateSubmissionFeaturesStub).to.have.been.calledOnceWith([feature1]);
expect(insertSubmissionRecordWithPotentialConflictStub).to.have.been.calledOnceWith(
'564-987-789',
'test submission',
'a test submission',
serviceClientSystemUser.system_user_id,
serviceClientSystemUser.user_identifier
);
expect(insertSubmissionFeatureRecordsStub).to.have.been.calledOnceWith(submissionId, [feature1]);
expect(indexFeaturesBySubmissionIdStub).to.have.been.calledOnceWith(submissionId);
expect(findSubmissionFeaturesStub).to.have.been.calledOnceWith({
submissionId: submissionId,
featureTypeNames: ['artifact']
});

expect(mockRes.statusValue).to.eql(200);
expect(mockRes.jsonValue).to.eql({ submission_id: 1 });
expect(mockRes.jsonValue).to.eql({
submission_uuid: '123-456-789',
artifact_upload_keys: [
{
artifact_filename: 'test-file.txt',
artifact_upload_key: '321-645-978'
}
]
});
});
});
});
34 changes: 22 additions & 12 deletions api/src/repositories/code-repository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { QueryResult } from 'pg';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import { getMockDBConnection } from '../__mocks__/db';
import { CodeRepository, IAllCodeSets, ICode } from './code-repository';
import { CodeRepository, FeaturePropertyCode, FeatureTypeCode } from './code-repository';

chai.use(sinonChai);

Expand All @@ -15,9 +15,15 @@ describe('CodeRepository', () => {
});

it('should return rows if succeeds', async () => {
const mockRow: FeatureTypeCode = {
feature_type_id: 1,
feature_type_name: 'dataset',
feature_type_display_name: 'Dataset'
};

const mockQueryResponse = {
rowCount: 1,
rows: [{ id: 1, name: 'name' } as unknown as ICode]
rows: [mockRow]
} as any as Promise<QueryResult<any>>;

const mockDBConnection = getMockDBConnection({
Expand All @@ -28,7 +34,7 @@ describe('CodeRepository', () => {

const result = await codeRepository.getFeatureTypes();

expect(result).to.be.eql([{ id: 1, name: 'name' }]);
expect(result).to.be.eql([mockRow]);
});
});

Expand All @@ -38,16 +44,20 @@ describe('CodeRepository', () => {
});

it('should return rows if succeeds', async () => {
const mockRow: FeatureTypeCode & FeaturePropertyCode = {
feature_type_id: 1,
feature_type_name: 'dataset',
feature_type_display_name: 'Dataset',
feature_property_id: 2,
feature_property_name: 'name',
feature_property_display_name: 'Name',
feature_property_type_id: 3,
feature_property_type_name: 'string'
};

const mockQueryResponse = {
rowCount: 1,
rows: [
{
id: 1,
name: 'name',
display_name: 'display',
type: 'string'
} as unknown as IAllCodeSets['feature_type_with_properties']
]
rows: [mockRow]
} as any as Promise<QueryResult<any>>;

const mockDBConnection = getMockDBConnection({
Expand All @@ -58,7 +68,7 @@ describe('CodeRepository', () => {

const result = await codeRepository.getFeatureTypePropertyCodes();

expect(result).to.be.eql([{ id: 1, name: 'name', display_name: 'display', type: 'string' }]);
expect(result).to.be.eql([mockRow]);
});
});
});
13 changes: 4 additions & 9 deletions api/src/repositories/submission-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1214,7 +1214,7 @@ export class SubmissionRepository extends BaseRepository {
const sqlStatement = SQL`
WITH w_unique_submissions as (
SELECT
DISTINCT ON (submission.uuid) submission.*,
DISTINCT ON (submission.source_id) submission.*,
submission_feature.feature_type_id as root_feature_type_id,
feature_type.name as root_feature_type_name,
${SECURITY_APPLIED_STATUS.PENDING} as security
Expand All @@ -1233,7 +1233,7 @@ export class SubmissionRepository extends BaseRepository {
AND
submission_feature.parent_submission_feature_id IS NULL
ORDER BY
submission.uuid, submission.submission_id DESC
submission.source_id, submission.submission_id DESC
)
SELECT
*
Expand All @@ -1257,7 +1257,7 @@ export class SubmissionRepository extends BaseRepository {
const sqlStatement = SQL`
WITH w_unique_submissions as (
SELECT
DISTINCT ON (submission.uuid) submission.*,
DISTINCT ON (submission.source_id) submission.*,
submission_feature.feature_type_id as root_feature_type_id,
feature_type.name as root_feature_type_name,
CASE
Expand Down Expand Up @@ -1289,7 +1289,7 @@ export class SubmissionRepository extends BaseRepository {
submission_feature.feature_type_id,
feature_type.name
ORDER BY
submission.uuid, submission.submission_id DESC
submission.source_id, submission.submission_id DESC
)
SELECT
*
Expand Down Expand Up @@ -1474,11 +1474,6 @@ export class SubmissionRepository extends BaseRepository {
});
}

console.log('=========================================');
console.log(queryBuilder.toSQL().toNative().sql);
console.log(queryBuilder.toSQL().toNative().bindings);
console.log('---------------------------------------');

const response = await this.connection.knex(queryBuilder, SubmissionFeatureRecord);

return response.rows;
Expand Down
97 changes: 1 addition & 96 deletions api/src/services/artifact-service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,10 @@ import chai, { expect } from 'chai';
import { describe } from 'mocha';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import { HTTPError } from '../errors/http-error';
import { Artifact, ArtifactMetadata, ArtifactRepository } from '../repositories/artifact-repository';
import { Artifact, ArtifactRepository } from '../repositories/artifact-repository';
import { SecurityRepository } from '../repositories/security-repository';
import * as file_utils from '../utils/file-utils';
import { getMockDBConnection } from '../__mocks__/db';
import { ArtifactService } from './artifact-service';
import { SubmissionService } from './submission-service';

chai.use(sinonChai);

Expand Down Expand Up @@ -76,98 +73,6 @@ describe('ArtifactService', () => {
});
});

describe('uploadAndPersistArtifact', () => {
const mockDataPackageId = '64f47e65-f306-410e-82fa-115f9916910b';
const mockArtifactMetadata: ArtifactMetadata = {
title: 'Title',
description: 'Description',
file_name: 'Filename.txt',
file_type: 'Other',
file_size: 1
};
const mockFileUuid = 'aaa47e65-f306-410e-82fa-115f9916910b';
const mockFile = {
originalname: `${mockFileUuid}.zip`
} as unknown as Express.Multer.File;

it('should not insert a record if upload to S3 fails', async () => {
const mockDBConnection = getMockDBConnection({ systemUserId: () => 20 });
const artifactService = new ArtifactService(mockDBConnection);

// const transformRecordStub = sinon
// .stub(SubmissionService.prototype, 'getSourceTransformRecordBySystemUserId')
// .resolves({ source_transform_id: 60 } as unknown as ISourceTransformModel);

// const getOrInsertSubmissionRecordStub =
sinon
.stub(SubmissionService.prototype, 'insertSubmissionRecordWithPotentialConflict')
.resolves({ submission_id: 100 });

// const getNextArtifactIdsStub =
sinon.stub(ArtifactService.prototype, 'getNextArtifactIds').resolves([14]);

const insertRecordStub = sinon.stub(ArtifactService.prototype, 'insertArtifactRecord');

sinon.stub(file_utils, 'uploadFileToS3').rejects(new Error('Test upload failed'));

try {
await artifactService.uploadAndPersistArtifact(mockDataPackageId, mockArtifactMetadata, mockFileUuid, mockFile);
expect.fail();
} catch (actualError) {
// expect(transformRecordStub).to.be.calledWith(20);
expect((actualError as HTTPError).message).to.equal('Test upload failed');
expect(insertRecordStub).to.not.be.called;
}
});

it('should return the artifact ID on success', async () => {
const mockDBConnection = getMockDBConnection({ systemUserId: () => 20 });
const artifactService = new ArtifactService(mockDBConnection);

// const transformRecordStub = sinon
// .stub(SubmissionService.prototype, 'getSourceTransformRecordBySystemUserId')
// .resolves({ source_transform_id: 60 } as unknown as ISourceTransformModel);

const insertSubmissionRecordWithPotentialConflictStub = sinon
.stub(SubmissionService.prototype, 'insertSubmissionRecordWithPotentialConflict')
.resolves({ submission_id: 100 });

const getNextArtifactIdsStub = sinon.stub(ArtifactService.prototype, 'getNextArtifactIds').resolves([14]);

const uploadStub = sinon.stub(file_utils, 'uploadFileToS3').resolves();

const insertRecordStub = sinon
.stub(ArtifactService.prototype, 'insertArtifactRecord')
.resolves({ artifact_id: 14 });

try {
await artifactService.uploadAndPersistArtifact(mockDataPackageId, mockArtifactMetadata, mockFileUuid, mockFile);
expect.fail();
} catch (actualError) {
// expect(transformRecordStub).to.be.calledWith(20);

expect(insertSubmissionRecordWithPotentialConflictStub).to.be.calledWith(mockDataPackageId);
expect(getNextArtifactIdsStub).to.be.calledWith();
expect(uploadStub).to.be.calledWith(
mockFile,
`biohub/datasets/${mockDataPackageId}/artifacts/${14}/${mockFile.originalname}`,
{ filename: mockFile.originalname }
);
expect(insertRecordStub).to.be.calledWith({
title: 'Title',
description: 'Description',
file_name: 'Filename.txt',
file_type: 'Other',
file_size: 1,
artifact_id: 14,
submission_id: 100,
key: `biohub/datasets/${mockDataPackageId}/artifacts/${14}/${mockFile.originalname}`,
uuid: mockFileUuid
});
}
});
});

describe('getArtifactById', () => {
it('should return a single artifact successfully', async () => {
const mockDBConnection = getMockDBConnection();
Expand Down
Loading

0 comments on commit d713b8b

Please sign in to comment.