Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(#123): Enhance Automated Tests for CHT & OpenMRS Endpoints in Mediator #152

Draft
wants to merge 4 commits into
base: openmrs-mediator
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions mediator/test/cht-resource-factories.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { randomUUID } from 'crypto';
import { Factory } from 'rosie';

const PlaceFactory = Factory.define('place')
export const PlaceFactory = Factory.define('place')
.option('placeId', randomUUID())
.attr('name', 'CHP Branch One')
.attr('type', 'district_hospital')
.attr('parent', ['placeId'], function (placeId) {
.attr('placeId', ['placeId'], function (placeId) {
return placeId;
});

Expand All @@ -14,28 +14,32 @@ const ContactFactory = Factory.define('contact')
.attr('phone', '+2868917046');

export const UserFactory = Factory.define('user')
.option('placeId')
.option('parentPlace')
.attr('password', 'Dakar1234')
.attr('username', 'maria')
.attr('type', 'chw')
.attr('place', ['placeId'], function (placeId) {
return PlaceFactory.build({}, { placeId });
.attr('place', ['parentPlace'], function (parentPlace) {
return {
"name": "Mary's Area",
"type": "health_center",
"parent": parentPlace
};
})
.attr('contact', function () {
return ContactFactory.build();
});

export const PatientFactory = Factory.define('patient')
.option('placeId')
.option('place')
.attr('name', 'John Test')
.attr('phone', '+2548277217095')
.attr('date_of_birth', '1980-06-06')
.attr('sex', 'male')
.attr('type', 'person')
.attr('role', 'patient')
.attr('contact_type', 'patient')
.attr('place', ['placeId'], function (placeId) {
return placeId;
.attr('place', ['place'], function (place) {
return place;
});

const DocsFieldsFactory = Factory.define('fields')
Expand Down
67 changes: 67 additions & 0 deletions mediator/test/openmrs-resource-factories.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { randomUUID } from 'crypto';
import { Factory } from 'rosie';

export const OpenMRSPatientFactory = new Factory()
.option('placeId')
.attr('resourceType', 'Patient')
.attr('id', () => randomUUID())
.attr('meta', () => ({
versionId: '2',
lastUpdated: new Date().toISOString(),
source: 'cht#rjEgeBRWROBrChB7'
}))
.attr('text', () => ({
status: 'generated',
div: '<div xmlns="http://www.w3.org/1999/xhtml"><div class="hapiHeaderText">OpenMRS <b>PATIENT </b></div><table class="hapiPropertyTable"><tbody><tr><td>Identifier</td><td>52802</td></tr><tr><td>Date of birth</td><td><span>06 June 1980</span></td></tr></tbody></table></div>'
}))
.attr('identifier', () => [
{
id: randomUUID(),
use: 'official',
type: { text: 'CHT Patient ID' },
value: Math.floor(Math.random() * 100000).toString()
},
{
id: randomUUID(),
use: 'secondary',
type: { text: 'CHT Document ID' },
value: randomUUID()
},
{
id: randomUUID(),
use: 'secondary',
type: { text: 'OpenMRS Patient UUID' },
value: randomUUID()
}
])
.attr('name', () => [
{
id: randomUUID(),
family: 'Patient',
given: ['OpenMRS']
}
])
.attr('telecom', () => [
{
id: randomUUID(),
value: '+2548277217095'
}
])
.attr('gender', 'male')
.attr('birthDate', '1980-06-06')
.attr('address', ['placeId'], (placeId) => [
{
id: randomUUID(),
line: ['123 Main St'],
city: 'Nairobi',
country: 'Kenya',
extension: [{
extension: [
{
url: 'http://fhir.openmrs.org/ext/address#address4',
valueString: `FCHV Area [${placeId}]`
}
]
}]
}
]);
104 changes: 75 additions & 29 deletions mediator/test/workflows.spec.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import request from 'supertest';
import { OPENHIM, CHT, FHIR, OPENMRS } from '../config';
import {
UserFactory, PatientFactory, TaskReportFactory
UserFactory, PatientFactory, TaskReportFactory, PlaceFactory
} from './cht-resource-factories';
import {
EndpointFactory as EndpointFactoryBase,
OrganizationFactory as OrganizationFactoryBase,
ServiceRequestFactory as ServiceRequestFactoryBase
} from '../src/middlewares/schemas/tests/fhir-resource-factories';
import { OpenMRSPatientFactory } from './openmrs-resource-factories';

const { generateAuthHeaders } = require('../../configurator/libs/authentication');

jest.setTimeout(50000);
Expand Down Expand Up @@ -68,26 +70,28 @@ const createOpenMRSIdType = async (name: string) => {
}
};

let placeId: string;
const parentPlace = PlaceFactory.build();
let chwUserName: string;
let chwPassword: string;
let contactId: string;
let patientId: string;
let parentPlaceId: string;
let placeId: string;


const configureCHT = async () => {
const createPlaceResponse = await request(CHT.url)
.post('/api/v1/places')
.auth(CHT.username, CHT.password)
.send({ 'name': 'CHP Branch Two', 'type': 'district_hospital' });
.send(parentPlace);

if (createPlaceResponse.status === 200 && createPlaceResponse.body.ok === true) {
placeId = createPlaceResponse.body.id;
parentPlaceId = createPlaceResponse.body.id;
} else {
throw new Error(`CHT place creation failed: Reason ${createPlaceResponse.status}`);
}

const user = UserFactory.build({}, { placeId: placeId });

const user = UserFactory.build({}, { parentPlace: parentPlaceId });
chwUserName = user.username;
chwPassword = user.password;

Expand All @@ -100,6 +104,15 @@ const configureCHT = async () => {
} else {
throw new Error(`CHT user creation failed: Reason ${createUserResponse.status}`);
}

const retrieveChtHealthCenterResponse = await request(CHT.url)
.get('/api/v2/users/maria')
.auth(CHT.username, CHT.password);
if (retrieveChtHealthCenterResponse.status === 200) {
placeId = retrieveChtHealthCenterResponse.body.place[0]._id;
} else {
throw new Error(`CHT health center retrieval failed: Reason ${retrieveChtHealthCenterResponse.status}`);
}
};

describe('Workflows', () => {
Expand All @@ -113,15 +126,14 @@ describe('Workflows', () => {
});

describe('OpenMRS workflow', () => {
it('Should follow the CHT Patient to OpenMRS workflow', async () => {
it('should follow the CHT Patient to OpenMRS workflow', async () => {
const checkMediatorResponse = await request(FHIR.url)
.get('/mediator/')
.auth(FHIR.username, FHIR.password);

expect(checkMediatorResponse.status).toBe(200);
expect(checkMediatorResponse.body.status).toBe('success');

const patient = PatientFactory.build({}, { name: 'OpenMRS patient', placeId: placeId });
const patient = PatientFactory.build({name: 'CHTOpenMRS Patient', phone: '+2548277217095'}, { place: placeId });

const createPatientResponse = await request(CHT.url)
.post('/api/v1/people')
Expand All @@ -132,57 +144,91 @@ describe('Workflows', () => {
expect(createPatientResponse.body.ok).toEqual(true);
patientId = createPatientResponse.body.id;

await new Promise((r) => setTimeout(r, 5000));
await new Promise((r) => setTimeout(r, 10000));

const retrieveFhirPatientIdResponse = await request(FHIR.url)
.get('/fhir/Patient/?identifier=' + patientId)
.auth(FHIR.username, FHIR.password);

expect(retrieveFhirPatientIdResponse.status).toBe(200);
expect(retrieveFhirPatientIdResponse.body.total).toBe(1);

const triggerOpenMrsSyncPatientResponse = await request(FHIR.url)
.get('/mediator/openmrs/sync')
.auth(FHIR.username, FHIR.password)
.send();

expect(triggerOpenMrsSyncPatientResponse.status).toBe(200);

await new Promise((r) => setTimeout(r, 5000));
await new Promise((r) => setTimeout(r, 10000));

const retrieveOpenMrsPatientIdResponse = await request(OPENMRS.url)
.get('/Patient/?identifier=' + patientId)
.auth(OPENMRS.username, OPENMRS.password);

expect(retrieveOpenMrsPatientIdResponse.status).toBe(200);
//this should work after fixing openmrs to have latest fhir omod and cht identifier defined.
expect(retrieveOpenMrsPatientIdResponse.body.total).toBe(1);

//Validate HAPI updated ids

const openMrsPatientId = retrieveOpenMrsPatientIdResponse.body.entry[0].resource.id;
const retrieveUpdatedFhirPatientResponse = await request(FHIR.url)
.get(`/fhir/Patient/${patientId}`)
.auth(FHIR.username, FHIR.password);
expect(retrieveUpdatedFhirPatientResponse.status).toBe(200);
expect(retrieveUpdatedFhirPatientResponse.body.identifier).toEqual(
expect.arrayContaining([
expect.objectContaining({
value: openMrsPatientId,
})
])
);

const searchOpenMrsPatientResponse = await request(OPENMRS.url)
.get(`/Patient/?given=CHTOpenMRS&family=Patient`)
.auth(OPENMRS.username, OPENMRS.password);
expect(searchOpenMrsPatientResponse.status).toBe(200);
expect(searchOpenMrsPatientResponse.body.total).toBe(1);
expect(searchOpenMrsPatientResponse.body.entry[0].resource.id).toBe(openMrsPatientId);
});

//skipping this test because is incomplete.
it.skip('Should follow the OpenMRS Patient to CHT workflow', async () => {
it('should follow the OpenMRS Patient to CHT workflow', async () => {
const checkMediatorResponse = await request(FHIR.url)
.get('/mediator/')
.auth(FHIR.username, FHIR.password);

expect(checkMediatorResponse.status).toBe(200);

//TODO: Create a patient using openMRS api
const openMrsPatient = OpenMRSPatientFactory.build({}, {placeId: parentPlace.placeId});

const createOpenMrsPatientResponse = await request(OPENMRS.url)
.post('/Patient')
.auth(OPENMRS.username, OPENMRS.password)
.send(openMrsPatient);

expect(createOpenMrsPatientResponse.status).toBe(201);
expect(createOpenMrsPatientResponse.body).toHaveProperty('id');

const openMrsPatientId = createOpenMrsPatientResponse.body.id;

await new Promise((r) => setTimeout(r, 10000));

const triggerOpenMrsSyncPatientResponse = await request('https://localhost:5002')
.get('/mediator/openmrs/sync')
.auth(OPENMRS.username, OPENMRS.password)
.send();
expect(triggerOpenMrsSyncPatientResponse.status).toBe(200);

await new Promise((r) => setTimeout(r, 20000));

const retrieveFhirPatientIdResponse = await request(FHIR.url)
.get('/fhir/Patient/?identifier=' + patientId)
.get('/fhir/Patient/?identifier=' + openMrsPatientId)
.auth(FHIR.username, FHIR.password);

expect(retrieveFhirPatientIdResponse.status).toBe(200);
//expect(retrieveFhirPatientIdResponse.body.total).toBe(1);
expect(retrieveFhirPatientIdResponse.body.total).toBe(1);

const chtPatientId = retrieveFhirPatientIdResponse.body.entry[0].resource.identifier[1].value;

//TODO: retrieve and validate patient from CHT api
//trigger openmrs sync
//validate id
const retrieveChtPatientResponse = await request(CHT.url)
.get('/api/v1/person/' + chtPatientId)
.auth(CHT.username, CHT.password);
expect(retrieveChtPatientResponse.status).toBe(200);
});

});

describe('Loss To Follow-Up (LTFU) workflow', () => {
Expand Down Expand Up @@ -231,7 +277,7 @@ describe('Workflows', () => {
expect(retrieveOrganizationResponse.status).toBe(200);
expect(retrieveOrganizationResponse.body.total).toBe(1);

const patient = PatientFactory.build({}, { name: 'LTFU patient', placeId: placeId });
const patient = PatientFactory.build({}, { name: 'LTFU patient', place: placeId });

const createPatientResponse = await request(CHT.url)
.post('/api/v1/people')
Expand Down Expand Up @@ -262,7 +308,7 @@ describe('Workflows', () => {
expect(sendMediatorServiceRequestResponse.status).toBe(201);
encounterUrl = sendMediatorServiceRequestResponse.body.criteria;

const taskReport = TaskReportFactory.build({}, { placeId, contactId, patientId });
const taskReport = TaskReportFactory.build({}, { placeId: placeId, contactId, patientId });

const submitChtTaskResponse = await request(CHT.url)
.post('/medic/_bulk_docs')
Expand Down
Loading