From 59542aa37088a4dedaa5d3e1fae3dbf04ea2379c Mon Sep 17 00:00:00 2001 From: Joe Fong Date: Mon, 19 Jun 2023 09:41:48 +0100 Subject: [PATCH 1/5] temp save jdbc connection poc --- build.gradle | 1 + .../prm/deduction/e2e/TestConfiguration.java | 9 +++++++++ .../e2e/tests/RepositoryE2ETests.java | 20 +++++++++++++++++++ .../prm/deduction/e2e/utility/TestUtils.java | 17 ++++++++++++++++ 4 files changed, 47 insertions(+) diff --git a/build.gradle b/build.gradle index 015508e7..5cf8247d 100644 --- a/build.gradle +++ b/build.gradle @@ -52,6 +52,7 @@ configurations { } dependencies { + implementation 'org.postgresql:postgresql:42.5.4' groovyScript localGroovy() } diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java b/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java index 9021fab7..7ed10048 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java @@ -93,6 +93,15 @@ public String getEhrRepoE2EApiKey() { return awsConfigurationClient.getParamValue(String.format("/repo/%s/user-input/api-keys/ehr-repo/e2e-test", getEnvironmentName())); } + public String getEhrOutPostgresDbConnString() { + String hostname = awsConfigurationClient.getParamValue(String.format("/repo/%s/output/prm-repo-ehr-out-service/db-host", getEnvironmentName())); + String password = awsConfigurationClient.getParamValue(String.format("/repo/%s/user-input/ehr-out-service-db-password", getEnvironmentName())); + String username = awsConfigurationClient.getParamValue(String.format("/repo/%s/user-input/ehr-out-service-db-username", getEnvironmentName())); + String dbname = awsConfigurationClient.getParamValue(String.format("/repo/%s/output/prm-repo-ehr-out-service/db-name", getEnvironmentName())); + String port = "5432"; + return "jdbc:postgresql://" + hostname + ":" + port + "/" + dbname + "?user=" + username + "&password=" + password; + } + public String getRepoOdsCode() { return awsConfigurationClient.getParamValue(String.format("/repo/%s/user-input/external/repository-ods-code", getEnvironmentName())); } diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java b/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java index b987aacf..c4f8007e 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java @@ -33,6 +33,10 @@ import uk.nhs.prm.deduction.e2e.utility.Resources; import uk.nhs.prm.deduction.e2e.utility.TestUtils; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; @@ -280,6 +284,22 @@ void shouldVerifyThatALargeEhrXMLIsUnchanged() { }); } + @Test + void tryConnectToPostgresDb() throws SQLException { + Connection conn = getRemoteConnection(config); + assert conn != null; + Statement statement = conn.createStatement(); + String selectSql = "SELECT COUNT(*) FROM acknowledgements WHERE message_id = '7e6c9590-fa4b-11ed-808b-ac162d1f16f0';"; + ResultSet resultSet = statement.executeQuery(selectSql); + LOGGER.info(" ========= HERE ==========="); + assertTrue(resultSet.next()); + LOGGER.info("got count: {}", resultSet.getInt("count")); + + int numberOfMatchingRow = resultSet.getInt("count"); + + assertThat(numberOfMatchingRow).isEqualTo(1); + } + @Test void shouldReceivingAndTrackAllLargeEhrFragments_DevAndTest() { var largeEhrAtEmisWithRepoMof = Patient.largeEhrAtEmisWithRepoMof(config); diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/utility/TestUtils.java b/src/test/java/uk/nhs/prm/deduction/e2e/utility/TestUtils.java index e59a07b0..4cbce3b0 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/utility/TestUtils.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/utility/TestUtils.java @@ -7,9 +7,13 @@ import org.w3c.dom.Node; import org.xmlunit.builder.DiffBuilder; import org.xmlunit.diff.*; +import uk.nhs.prm.deduction.e2e.TestConfiguration; import uk.nhs.prm.deduction.e2e.transfer_tracker_db.TrackerDb; import uk.nhs.prm.deduction.e2e.transfer_tracker_db.TransferTrackerDbMessage; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.List; @@ -161,4 +165,17 @@ public static LargeEhrTestFiles prepareTestFilesForLargeEhr( return new LargeEhrTestFiles(largeEhrCore, largeEhrFragment1, largeEhrFragment2, ehrRequest, continueRequest); } + + + public static Connection getRemoteConnection(TestConfiguration config) { + try { + String jdbcUrl = config.getEhrOutPostgresDbConnString(); + LOGGER.trace("Getting remote connection with connection string from environment variables."); + Connection conn = DriverManager.getConnection(jdbcUrl); + LOGGER.info("Remote connection successful."); + return conn; + } + catch (SQLException e) { LOGGER.warn(e.toString());} + return null; + } } From 00baaed9496a3fc94d02c14433c2b883ed35bad0 Mon Sep 17 00:00:00 2001 From: Joe Fong Date: Wed, 21 Jun 2023 10:59:09 +0100 Subject: [PATCH 2/5] use JOOQ for querying db --- build.gradle | 5 +- .../e2e/ehroutdb/DefaultCatalog.java | 44 ++ .../nhs/prm/deduction/e2e/ehroutdb/Keys.java | 45 ++ .../prm/deduction/e2e/ehroutdb/Public.java | 53 +++ .../prm/deduction/e2e/ehroutdb/Tables.java | 20 + .../e2e/ehroutdb/tables/Acknowledgements.java | 177 ++++++++ .../records/AcknowledgementsRecord.java | 406 ++++++++++++++++++ .../e2e/tests/RepositoryE2ETests.java | 36 +- 8 files changed, 773 insertions(+), 13 deletions(-) create mode 100644 src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/DefaultCatalog.java create mode 100644 src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Keys.java create mode 100644 src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Public.java create mode 100644 src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Tables.java create mode 100644 src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/tables/Acknowledgements.java create mode 100644 src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/tables/records/AcknowledgementsRecord.java diff --git a/build.gradle b/build.gradle index 5cf8247d..8c49d84a 100644 --- a/build.gradle +++ b/build.gradle @@ -33,6 +33,10 @@ dependencies { testImplementation 'com.google.code.gson:gson:2.10.1' testImplementation 'org.xmlunit:xmlunit-core:2.9.1' testImplementation 'org.xmlunit:xmlunit-matchers:2.9.1' + implementation 'org.jooq:jooq-codegen:3.13.4' + implementation 'org.jooq:jooq-meta:3.13.4' + implementation 'org.jooq:jooq:3.13.4' + implementation 'org.postgresql:postgresql:42.5.4' testCompileOnly 'org.projectlombok:lombok:1.18.24' testAnnotationProcessor 'org.projectlombok:lombok' @@ -52,7 +56,6 @@ configurations { } dependencies { - implementation 'org.postgresql:postgresql:42.5.4' groovyScript localGroovy() } diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/DefaultCatalog.java b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/DefaultCatalog.java new file mode 100644 index 00000000..ea7d0257 --- /dev/null +++ b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/DefaultCatalog.java @@ -0,0 +1,44 @@ +/* + * This file is generated by jOOQ. + */ +package uk.nhs.prm.deduction.e2e.ehroutdb; + + +import java.util.Arrays; +import java.util.List; + +import org.jooq.Schema; +import org.jooq.impl.CatalogImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class DefaultCatalog extends CatalogImpl { + + private static final long serialVersionUID = -845055540; + + /** + * The reference instance of DEFAULT_CATALOG + */ + public static final DefaultCatalog DEFAULT_CATALOG = new DefaultCatalog(); + + /** + * The schema public. + */ + public final Public PUBLIC = Public.PUBLIC; + + /** + * No further instances allowed + */ + private DefaultCatalog() { + super(""); + } + + @Override + public final List getSchemas() { + return Arrays.asList( + Public.PUBLIC); + } +} diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Keys.java b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Keys.java new file mode 100644 index 00000000..af819041 --- /dev/null +++ b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Keys.java @@ -0,0 +1,45 @@ +/* + * This file is generated by jOOQ. + */ +package uk.nhs.prm.deduction.e2e.ehroutdb; + + +import org.jooq.TableField; +import org.jooq.UniqueKey; +import org.jooq.impl.Internal; + +import uk.nhs.prm.deduction.e2e.ehroutdb.tables.Acknowledgements; +import uk.nhs.prm.deduction.e2e.ehroutdb.tables.records.AcknowledgementsRecord; + + +/** + * A class modelling foreign key relationships and constraints of tables of + * the public schema. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class Keys { + + // ------------------------------------------------------------------------- + // IDENTITY definitions + // ------------------------------------------------------------------------- + + + // ------------------------------------------------------------------------- + // UNIQUE and PRIMARY KEY definitions + // ------------------------------------------------------------------------- + + public static final UniqueKey ACKNOWLEDGEMENTS_PKEY = UniqueKeys0.ACKNOWLEDGEMENTS_PKEY; + + // ------------------------------------------------------------------------- + // FOREIGN KEY definitions + // ------------------------------------------------------------------------- + + + // ------------------------------------------------------------------------- + // [#1459] distribute members to avoid static initialisers > 64kb + // ------------------------------------------------------------------------- + + private static class UniqueKeys0 { + public static final UniqueKey ACKNOWLEDGEMENTS_PKEY = Internal.createUniqueKey(Acknowledgements.ACKNOWLEDGEMENTS, "acknowledgements_pkey", new TableField[] { Acknowledgements.ACKNOWLEDGEMENTS.MESSAGE_ID }, true); + } +} diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Public.java b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Public.java new file mode 100644 index 00000000..a25d0d26 --- /dev/null +++ b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Public.java @@ -0,0 +1,53 @@ +/* + * This file is generated by jOOQ. + */ +package uk.nhs.prm.deduction.e2e.ehroutdb; + + +import java.util.Arrays; +import java.util.List; + +import org.jooq.Catalog; +import org.jooq.Table; +import org.jooq.impl.SchemaImpl; + +import uk.nhs.prm.deduction.e2e.ehroutdb.tables.Acknowledgements; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class Public extends SchemaImpl { + + private static final long serialVersionUID = 1436157980; + + /** + * The reference instance of public + */ + public static final Public PUBLIC = new Public(); + + /** + * The table public.acknowledgements. + */ + public final Acknowledgements ACKNOWLEDGEMENTS = Acknowledgements.ACKNOWLEDGEMENTS; + + /** + * No further instances allowed + */ + private Public() { + super("public", null); + } + + + @Override + public Catalog getCatalog() { + return DefaultCatalog.DEFAULT_CATALOG; + } + + @Override + public final List> getTables() { + return Arrays.>asList( + Acknowledgements.ACKNOWLEDGEMENTS); + } +} diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Tables.java b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Tables.java new file mode 100644 index 00000000..ececb610 --- /dev/null +++ b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/Tables.java @@ -0,0 +1,20 @@ +/* + * This file is generated by jOOQ. + */ +package uk.nhs.prm.deduction.e2e.ehroutdb; + + +import uk.nhs.prm.deduction.e2e.ehroutdb.tables.Acknowledgements; + + +/** + * Convenience access to all tables in public + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class Tables { + + /** + * The table public.acknowledgements. + */ + public static final Acknowledgements ACKNOWLEDGEMENTS = Acknowledgements.ACKNOWLEDGEMENTS; +} diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/tables/Acknowledgements.java b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/tables/Acknowledgements.java new file mode 100644 index 00000000..4ee45668 --- /dev/null +++ b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/tables/Acknowledgements.java @@ -0,0 +1,177 @@ +/* + * This file is generated by jOOQ. + */ +package uk.nhs.prm.deduction.e2e.ehroutdb.tables; + + +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +import uk.nhs.prm.deduction.e2e.ehroutdb.Keys; +import uk.nhs.prm.deduction.e2e.ehroutdb.Public; +import uk.nhs.prm.deduction.e2e.ehroutdb.tables.records.AcknowledgementsRecord; +import org.jooq.Field; +import org.jooq.ForeignKey; +import org.jooq.Name; +import org.jooq.Record; +import org.jooq.Row9; +import org.jooq.Schema; +import org.jooq.Table; +import org.jooq.TableField; +import org.jooq.TableOptions; +import org.jooq.UniqueKey; +import org.jooq.impl.DSL; +import org.jooq.impl.TableImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class Acknowledgements extends TableImpl { + + private static final long serialVersionUID = -1409465028; + + /** + * The reference instance of public.acknowledgements + */ + public static final Acknowledgements ACKNOWLEDGEMENTS = new Acknowledgements(); + + /** + * The class holding records for this type + */ + @Override + public Class getRecordType() { + return AcknowledgementsRecord.class; + } + + /** + * The column public.acknowledgements.message_id. + */ + public final TableField MESSAGE_ID = createField(DSL.name("message_id"), org.jooq.impl.SQLDataType.UUID.nullable(false), this, ""); + + /** + * The column public.acknowledgements.acknowledgement_type_code. + */ + public final TableField ACKNOWLEDGEMENT_TYPE_CODE = createField(DSL.name("acknowledgement_type_code"), org.jooq.impl.SQLDataType.VARCHAR(255).nullable(false), this, ""); + + /** + * The column public.acknowledgements.acknowledgement_detail. + */ + public final TableField ACKNOWLEDGEMENT_DETAIL = createField(DSL.name("acknowledgement_detail"), org.jooq.impl.SQLDataType.VARCHAR(255).nullable(false), this, ""); + + /** + * The column public.acknowledgements.service. + */ + public final TableField SERVICE = createField(DSL.name("service"), org.jooq.impl.SQLDataType.VARCHAR(255).nullable(false), this, ""); + + /** + * The column public.acknowledgements.referenced_message_id. + */ + public final TableField REFERENCED_MESSAGE_ID = createField(DSL.name("referenced_message_id"), org.jooq.impl.SQLDataType.VARCHAR(255).nullable(false), this, ""); + + /** + * The column public.acknowledgements.message_ref. + */ + public final TableField MESSAGE_REF = createField(DSL.name("message_ref"), org.jooq.impl.SQLDataType.VARCHAR(255).nullable(false), this, ""); + + /** + * The column public.acknowledgements.created_at. + */ + public final TableField CREATED_AT = createField(DSL.name("created_at"), org.jooq.impl.SQLDataType.TIMESTAMPWITHTIMEZONE.nullable(false), this, ""); + + /** + * The column public.acknowledgements.updated_at. + */ + public final TableField UPDATED_AT = createField(DSL.name("updated_at"), org.jooq.impl.SQLDataType.TIMESTAMPWITHTIMEZONE.nullable(false), this, ""); + + /** + * The column public.acknowledgements.deleted_at. + */ + public final TableField DELETED_AT = createField(DSL.name("deleted_at"), org.jooq.impl.SQLDataType.TIMESTAMPWITHTIMEZONE, this, ""); + + /** + * Create a public.acknowledgements table reference + */ + public Acknowledgements() { + this(DSL.name("acknowledgements"), null); + } + + /** + * Create an aliased public.acknowledgements table reference + */ + public Acknowledgements(String alias) { + this(DSL.name(alias), ACKNOWLEDGEMENTS); + } + + /** + * Create an aliased public.acknowledgements table reference + */ + public Acknowledgements(Name alias) { + this(alias, ACKNOWLEDGEMENTS); + } + + private Acknowledgements(Name alias, Table aliased) { + this(alias, aliased, null); + } + + private Acknowledgements(Name alias, Table aliased, Field[] parameters) { + super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table()); + } + + public Acknowledgements(Table child, ForeignKey key) { + super(child, key, ACKNOWLEDGEMENTS); + } + + @Override + public Schema getSchema() { + return Public.PUBLIC; + } + + @Override + public UniqueKey getPrimaryKey() { + return Keys.ACKNOWLEDGEMENTS_PKEY; + } + + @Override + public List> getKeys() { + return Arrays.>asList(Keys.ACKNOWLEDGEMENTS_PKEY); + } + + @Override + public Acknowledgements as(String alias) { + return new Acknowledgements(DSL.name(alias), this); + } + + @Override + public Acknowledgements as(Name alias) { + return new Acknowledgements(alias, this); + } + + /** + * Rename this table + */ + @Override + public Acknowledgements rename(String name) { + return new Acknowledgements(DSL.name(name), null); + } + + /** + * Rename this table + */ + @Override + public Acknowledgements rename(Name name) { + return new Acknowledgements(name, null); + } + + // ------------------------------------------------------------------------- + // Row9 type methods + // ------------------------------------------------------------------------- + + @Override + public Row9 fieldsRow() { + return (Row9) super.fieldsRow(); + } +} diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/tables/records/AcknowledgementsRecord.java b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/tables/records/AcknowledgementsRecord.java new file mode 100644 index 00000000..d8422456 --- /dev/null +++ b/src/test/java/uk/nhs/prm/deduction/e2e/ehroutdb/tables/records/AcknowledgementsRecord.java @@ -0,0 +1,406 @@ +/* + * This file is generated by jOOQ. + */ +package uk.nhs.prm.deduction.e2e.ehroutdb.tables.records; + + +import java.time.OffsetDateTime; +import java.util.UUID; + +import org.jooq.Field; +import org.jooq.Record1; +import org.jooq.Record9; +import org.jooq.Row9; +import org.jooq.impl.UpdatableRecordImpl; + +import uk.nhs.prm.deduction.e2e.ehroutdb.tables.Acknowledgements; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes" }) +public class AcknowledgementsRecord extends UpdatableRecordImpl implements Record9 { + + private static final long serialVersionUID = 2054103351; + + /** + * Setter for public.acknowledgements.message_id. + */ + public void setMessageId(UUID value) { + set(0, value); + } + + /** + * Getter for public.acknowledgements.message_id. + */ + public UUID getMessageId() { + return (UUID) get(0); + } + + /** + * Setter for public.acknowledgements.acknowledgement_type_code. + */ + public void setAcknowledgementTypeCode(String value) { + set(1, value); + } + + /** + * Getter for public.acknowledgements.acknowledgement_type_code. + */ + public String getAcknowledgementTypeCode() { + return (String) get(1); + } + + /** + * Setter for public.acknowledgements.acknowledgement_detail. + */ + public void setAcknowledgementDetail(String value) { + set(2, value); + } + + /** + * Getter for public.acknowledgements.acknowledgement_detail. + */ + public String getAcknowledgementDetail() { + return (String) get(2); + } + + /** + * Setter for public.acknowledgements.service. + */ + public void setService(String value) { + set(3, value); + } + + /** + * Getter for public.acknowledgements.service. + */ + public String getService() { + return (String) get(3); + } + + /** + * Setter for public.acknowledgements.referenced_message_id. + */ + public void setReferencedMessageId(String value) { + set(4, value); + } + + /** + * Getter for public.acknowledgements.referenced_message_id. + */ + public String getReferencedMessageId() { + return (String) get(4); + } + + /** + * Setter for public.acknowledgements.message_ref. + */ + public void setMessageRef(String value) { + set(5, value); + } + + /** + * Getter for public.acknowledgements.message_ref. + */ + public String getMessageRef() { + return (String) get(5); + } + + /** + * Setter for public.acknowledgements.created_at. + */ + public void setCreatedAt(OffsetDateTime value) { + set(6, value); + } + + /** + * Getter for public.acknowledgements.created_at. + */ + public OffsetDateTime getCreatedAt() { + return (OffsetDateTime) get(6); + } + + /** + * Setter for public.acknowledgements.updated_at. + */ + public void setUpdatedAt(OffsetDateTime value) { + set(7, value); + } + + /** + * Getter for public.acknowledgements.updated_at. + */ + public OffsetDateTime getUpdatedAt() { + return (OffsetDateTime) get(7); + } + + /** + * Setter for public.acknowledgements.deleted_at. + */ + public void setDeletedAt(OffsetDateTime value) { + set(8, value); + } + + /** + * Getter for public.acknowledgements.deleted_at. + */ + public OffsetDateTime getDeletedAt() { + return (OffsetDateTime) get(8); + } + + // ------------------------------------------------------------------------- + // Primary key information + // ------------------------------------------------------------------------- + + @Override + public Record1 key() { + return (Record1) super.key(); + } + + // ------------------------------------------------------------------------- + // Record9 type implementation + // ------------------------------------------------------------------------- + + @Override + public Row9 fieldsRow() { + return (Row9) super.fieldsRow(); + } + + @Override + public Row9 valuesRow() { + return (Row9) super.valuesRow(); + } + + @Override + public Field field1() { + return Acknowledgements.ACKNOWLEDGEMENTS.MESSAGE_ID; + } + + @Override + public Field field2() { + return Acknowledgements.ACKNOWLEDGEMENTS.ACKNOWLEDGEMENT_TYPE_CODE; + } + + @Override + public Field field3() { + return Acknowledgements.ACKNOWLEDGEMENTS.ACKNOWLEDGEMENT_DETAIL; + } + + @Override + public Field field4() { + return Acknowledgements.ACKNOWLEDGEMENTS.SERVICE; + } + + @Override + public Field field5() { + return Acknowledgements.ACKNOWLEDGEMENTS.REFERENCED_MESSAGE_ID; + } + + @Override + public Field field6() { + return Acknowledgements.ACKNOWLEDGEMENTS.MESSAGE_REF; + } + + @Override + public Field field7() { + return Acknowledgements.ACKNOWLEDGEMENTS.CREATED_AT; + } + + @Override + public Field field8() { + return Acknowledgements.ACKNOWLEDGEMENTS.UPDATED_AT; + } + + @Override + public Field field9() { + return Acknowledgements.ACKNOWLEDGEMENTS.DELETED_AT; + } + + @Override + public UUID component1() { + return getMessageId(); + } + + @Override + public String component2() { + return getAcknowledgementTypeCode(); + } + + @Override + public String component3() { + return getAcknowledgementDetail(); + } + + @Override + public String component4() { + return getService(); + } + + @Override + public String component5() { + return getReferencedMessageId(); + } + + @Override + public String component6() { + return getMessageRef(); + } + + @Override + public OffsetDateTime component7() { + return getCreatedAt(); + } + + @Override + public OffsetDateTime component8() { + return getUpdatedAt(); + } + + @Override + public OffsetDateTime component9() { + return getDeletedAt(); + } + + @Override + public UUID value1() { + return getMessageId(); + } + + @Override + public String value2() { + return getAcknowledgementTypeCode(); + } + + @Override + public String value3() { + return getAcknowledgementDetail(); + } + + @Override + public String value4() { + return getService(); + } + + @Override + public String value5() { + return getReferencedMessageId(); + } + + @Override + public String value6() { + return getMessageRef(); + } + + @Override + public OffsetDateTime value7() { + return getCreatedAt(); + } + + @Override + public OffsetDateTime value8() { + return getUpdatedAt(); + } + + @Override + public OffsetDateTime value9() { + return getDeletedAt(); + } + + @Override + public AcknowledgementsRecord value1(UUID value) { + setMessageId(value); + return this; + } + + @Override + public AcknowledgementsRecord value2(String value) { + setAcknowledgementTypeCode(value); + return this; + } + + @Override + public AcknowledgementsRecord value3(String value) { + setAcknowledgementDetail(value); + return this; + } + + @Override + public AcknowledgementsRecord value4(String value) { + setService(value); + return this; + } + + @Override + public AcknowledgementsRecord value5(String value) { + setReferencedMessageId(value); + return this; + } + + @Override + public AcknowledgementsRecord value6(String value) { + setMessageRef(value); + return this; + } + + @Override + public AcknowledgementsRecord value7(OffsetDateTime value) { + setCreatedAt(value); + return this; + } + + @Override + public AcknowledgementsRecord value8(OffsetDateTime value) { + setUpdatedAt(value); + return this; + } + + @Override + public AcknowledgementsRecord value9(OffsetDateTime value) { + setDeletedAt(value); + return this; + } + + @Override + public AcknowledgementsRecord values(UUID value1, String value2, String value3, String value4, String value5, String value6, OffsetDateTime value7, OffsetDateTime value8, OffsetDateTime value9) { + value1(value1); + value2(value2); + value3(value3); + value4(value4); + value5(value5); + value6(value6); + value7(value7); + value8(value8); + value9(value9); + return this; + } + + // ------------------------------------------------------------------------- + // Constructors + // ------------------------------------------------------------------------- + + /** + * Create a detached AcknowledgementsRecord + */ + public AcknowledgementsRecord() { + super(Acknowledgements.ACKNOWLEDGEMENTS); + } + + /** + * Create a detached, initialised AcknowledgementsRecord + */ + public AcknowledgementsRecord(UUID messageId, String acknowledgementTypeCode, String acknowledgementDetail, String service, String referencedMessageId, String messageRef, OffsetDateTime createdAt, OffsetDateTime updatedAt, OffsetDateTime deletedAt) { + super(Acknowledgements.ACKNOWLEDGEMENTS); + + set(0, messageId); + set(1, acknowledgementTypeCode); + set(2, acknowledgementDetail); + set(3, service); + set(4, referencedMessageId); + set(5, messageRef); + set(6, createdAt); + set(7, updatedAt); + set(8, deletedAt); + } +} diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java b/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java index c4f8007e..470c77cc 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java @@ -2,6 +2,12 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; +import org.jooq.DSLContext; +import org.jooq.Result; +import org.jooq.Results; +import org.jooq.SQLDialect; +import org.jooq.codegen.GenerationTool; +import org.jooq.impl.DSL; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -13,9 +19,10 @@ import org.junit.jupiter.params.provider.MethodSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import org.xmlunit.diff.*; +import org.xmlunit.diff.Diff; import uk.nhs.prm.deduction.e2e.TestConfiguration; import uk.nhs.prm.deduction.e2e.ehr_transfer.*; +import uk.nhs.prm.deduction.e2e.ehroutdb.tables.Acknowledgements; import uk.nhs.prm.deduction.e2e.end_of_transfer_service.EndOfTransferMofUpdatedMessageQueue; import uk.nhs.prm.deduction.e2e.models.Gp2GpSystem; import uk.nhs.prm.deduction.e2e.models.RepoIncomingMessageBuilder; @@ -27,16 +34,14 @@ import uk.nhs.prm.deduction.e2e.queue.ThinlyWrappedSqsClient; import uk.nhs.prm.deduction.e2e.queue.activemq.ForceXercesParserSoLogbackDoesNotBlowUpWhenUsingSwiftMqClient; import uk.nhs.prm.deduction.e2e.queue.activemq.SimpleAmqpQueue; -import uk.nhs.prm.deduction.e2e.transfer_tracker_db.TransferTrackerDbClient; import uk.nhs.prm.deduction.e2e.transfer_tracker_db.TrackerDb; +import uk.nhs.prm.deduction.e2e.transfer_tracker_db.TransferTrackerDbClient; import uk.nhs.prm.deduction.e2e.utility.LargeEhrTestFiles; import uk.nhs.prm.deduction.e2e.utility.Resources; import uk.nhs.prm.deduction.e2e.utility.TestUtils; import java.sql.Connection; -import java.sql.ResultSet; import java.sql.SQLException; -import java.sql.Statement; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; @@ -48,8 +53,10 @@ import static java.util.stream.Collectors.toList; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import static org.springframework.test.util.AssertionErrors.assertFalse; import static uk.nhs.prm.deduction.e2e.utility.TestUtils.*; +import static uk.nhs.prm.deduction.e2e.ehroutdb.tables.Acknowledgements.*; @SpringBootTest(classes = { RepositoryE2ETests.class, @@ -288,16 +295,21 @@ void shouldVerifyThatALargeEhrXMLIsUnchanged() { void tryConnectToPostgresDb() throws SQLException { Connection conn = getRemoteConnection(config); assert conn != null; - Statement statement = conn.createStatement(); - String selectSql = "SELECT COUNT(*) FROM acknowledgements WHERE message_id = '7e6c9590-fa4b-11ed-808b-ac162d1f16f0';"; - ResultSet resultSet = statement.executeQuery(selectSql); - LOGGER.info(" ========= HERE ==========="); - assertTrue(resultSet.next()); - LOGGER.info("got count: {}", resultSet.getInt("count")); + DSLContext context = DSL.using(conn, SQLDialect.POSTGRES); + + String messageId = "3327d3e7-a1e7-4ec5-850b-912db9c8c5dd"; + Result result = context + .select() + .from(ACKNOWLEDGEMENTS) + .where(ACKNOWLEDGEMENTS.MESSAGE_ID.eq(UUID.fromString(messageId))) + .fetch(); + assertThat(result.size()).isEqualTo(1); + String typeCode = result.getValue(0, ACKNOWLEDGEMENTS.ACKNOWLEDGEMENT_TYPE_CODE); + LOGGER.info("typeCode of {} is {}", messageId, typeCode); + assertThat(typeCode).isEqualTo("AR"); - int numberOfMatchingRow = resultSet.getInt("count"); + conn.close(); - assertThat(numberOfMatchingRow).isEqualTo(1); } @Test From 85b65aa68d9fe383650bf778501954a165708cc9 Mon Sep 17 00:00:00 2001 From: Joe Fong Date: Wed, 21 Jun 2023 13:29:11 +0100 Subject: [PATCH 3/5] refactor test postgresdb connection --- .../prm/deduction/e2e/TestConfiguration.java | 2 +- .../e2e/tests/RepositoryE2ETests.java | 47 +++++++++++-------- .../prm/deduction/e2e/utility/TestUtils.java | 13 +---- 3 files changed, 30 insertions(+), 32 deletions(-) diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java b/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java index 7ed10048..230e698d 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java @@ -93,7 +93,7 @@ public String getEhrRepoE2EApiKey() { return awsConfigurationClient.getParamValue(String.format("/repo/%s/user-input/api-keys/ehr-repo/e2e-test", getEnvironmentName())); } - public String getEhrOutPostgresDbConnString() { + public String getEhrOutPostgresJdbcUrl() { String hostname = awsConfigurationClient.getParamValue(String.format("/repo/%s/output/prm-repo-ehr-out-service/db-host", getEnvironmentName())); String password = awsConfigurationClient.getParamValue(String.format("/repo/%s/user-input/ehr-out-service-db-password", getEnvironmentName())); String username = awsConfigurationClient.getParamValue(String.format("/repo/%s/user-input/ehr-out-service-db-username", getEnvironmentName())); diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java b/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java index 470c77cc..27c9e7d7 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java @@ -3,10 +3,10 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jooq.DSLContext; +import org.jooq.Record; import org.jooq.Result; -import org.jooq.Results; import org.jooq.SQLDialect; -import org.jooq.codegen.GenerationTool; +import org.jooq.exception.DataAccessException; import org.jooq.impl.DSL; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Disabled; @@ -57,6 +57,7 @@ import static org.springframework.test.util.AssertionErrors.assertFalse; import static uk.nhs.prm.deduction.e2e.utility.TestUtils.*; import static uk.nhs.prm.deduction.e2e.ehroutdb.tables.Acknowledgements.*; +import static org.assertj.core.api.ListAssert.*; @SpringBootTest(classes = { RepositoryE2ETests.class, @@ -292,24 +293,30 @@ void shouldVerifyThatALargeEhrXMLIsUnchanged() { } @Test - void tryConnectToPostgresDb() throws SQLException { - Connection conn = getRemoteConnection(config); - assert conn != null; - DSLContext context = DSL.using(conn, SQLDialect.POSTGRES); - - String messageId = "3327d3e7-a1e7-4ec5-850b-912db9c8c5dd"; - Result result = context - .select() - .from(ACKNOWLEDGEMENTS) - .where(ACKNOWLEDGEMENTS.MESSAGE_ID.eq(UUID.fromString(messageId))) - .fetch(); - assertThat(result.size()).isEqualTo(1); - String typeCode = result.getValue(0, ACKNOWLEDGEMENTS.ACKNOWLEDGEMENT_TYPE_CODE); - LOGGER.info("typeCode of {} is {}", messageId, typeCode); - assertThat(typeCode).isEqualTo("AR"); - - conn.close(); - + void tryConnectToPostgresDb() { + try(Connection connection = getRemoteConnection(config)) { + // given + String messageId = "3327d3e7-a1e7-4ec5-850b-912db9c8c5dd"; + + // when + connection.setReadOnly(true); // we've got no reason to write to the database for these E2E tests + DSLContext context = DSL.using(connection, SQLDialect.POSTGRES); + Result result = context + .select() + .from(ACKNOWLEDGEMENTS) + .where(ACKNOWLEDGEMENTS.MESSAGE_ID.eq(UUID.fromString(messageId))) + .fetch(); + + String typeCode = result.getValue(0, ACKNOWLEDGEMENTS.ACKNOWLEDGEMENT_TYPE_CODE); + + // then + assertTrue(result.isNotEmpty()); + assertThat(typeCode).isEqualTo("AR"); + LOGGER.info("The acknowledgement typeCode of {} is {}.", messageId, typeCode); + } catch (DataAccessException | SQLException exception) { + LOGGER.error(exception.getMessage()); + fail(); + } } @Test diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/utility/TestUtils.java b/src/test/java/uk/nhs/prm/deduction/e2e/utility/TestUtils.java index 4cbce3b0..2a4b254f 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/utility/TestUtils.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/utility/TestUtils.java @@ -166,16 +166,7 @@ public static LargeEhrTestFiles prepareTestFilesForLargeEhr( return new LargeEhrTestFiles(largeEhrCore, largeEhrFragment1, largeEhrFragment2, ehrRequest, continueRequest); } - - public static Connection getRemoteConnection(TestConfiguration config) { - try { - String jdbcUrl = config.getEhrOutPostgresDbConnString(); - LOGGER.trace("Getting remote connection with connection string from environment variables."); - Connection conn = DriverManager.getConnection(jdbcUrl); - LOGGER.info("Remote connection successful."); - return conn; - } - catch (SQLException e) { LOGGER.warn(e.toString());} - return null; + public static Connection getRemoteConnection(TestConfiguration config) throws SQLException { + return DriverManager.getConnection(config.getEhrOutPostgresJdbcUrl()); } } From f59bd5a99a22d3169f89718ad36e9f6549619524 Mon Sep 17 00:00:00 2001 From: Mohammad Iqbal Date: Fri, 23 Jun 2023 13:46:59 +0100 Subject: [PATCH 4/5] [PRMT-3411] Added E2E tests for expecting acknowledgments to be stored in ehr-out DB --- build.gradle | 8 +- .../e2e/ehr_out_db/Acknowledgement.java | 32 --- .../ehr_out_db/AcknowledgementRepository.java | 14 - .../e2e/ehr_out_db/EhrOutDbConfiguration.java | 53 ---- .../e2e/queue/QueueMessageHelper.java | 2 +- .../deduction/e2e/tests/EhrOutE2ETests.java | 247 ++++++++++++++++++ .../e2e/tests/RepositoryE2ETests.java | 49 +--- .../MCCI_IN010000UK13_NEGATIVE | 1 + .../MCCI_IN010000UK13_POSITIVE | 1 + src/test/resources/ehr/large-ehr-fragment-1 | 2 +- src/test/resources/ehr/large-ehr-fragment-2 | 2 +- tasks | 2 +- 12 files changed, 264 insertions(+), 149 deletions(-) delete mode 100644 src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/Acknowledgement.java delete mode 100644 src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/AcknowledgementRepository.java delete mode 100644 src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/EhrOutDbConfiguration.java create mode 100644 src/test/java/uk/nhs/prm/deduction/e2e/tests/EhrOutE2ETests.java create mode 100644 src/test/resources/acknowledgement/MCCI_IN010000UK13_NEGATIVE create mode 100644 src/test/resources/acknowledgement/MCCI_IN010000UK13_POSITIVE diff --git a/build.gradle b/build.gradle index 39c4cc0a..60719747 100644 --- a/build.gradle +++ b/build.gradle @@ -35,10 +35,10 @@ dependencies { testImplementation 'com.google.code.gson:gson:2.10.1' testImplementation 'org.xmlunit:xmlunit-core:2.9.1' testImplementation 'org.xmlunit:xmlunit-matchers:2.9.1' - implementation 'org.jooq:jooq-codegen:3.13.4' - implementation 'org.jooq:jooq-meta:3.13.4' - implementation 'org.jooq:jooq:3.13.4' - implementation 'org.postgresql:postgresql:42.5.4' + testImplementation 'org.jooq:jooq-codegen:3.13.4' + testImplementation 'org.jooq:jooq-meta:3.13.4' + testImplementation 'org.jooq:jooq:3.13.4' + testImplementation 'org.postgresql:postgresql:42.5.4' testCompileOnly 'org.projectlombok:lombok:1.18.24' testAnnotationProcessor 'org.projectlombok:lombok' diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/Acknowledgement.java b/src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/Acknowledgement.java deleted file mode 100644 index 17c3fb3e..00000000 --- a/src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/Acknowledgement.java +++ /dev/null @@ -1,32 +0,0 @@ -package uk.nhs.prm.deduction.e2e.ehr_out_db; - -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import org.hibernate.annotations.Type; - -import javax.persistence.Entity; -import javax.persistence.Id; -import javax.persistence.Table; -import java.time.LocalDateTime; -import java.util.UUID; - - -@Entity -@Getter -@NoArgsConstructor -@AllArgsConstructor -@Table(name = "acknowledgements") -public class Acknowledgement { - @Id - @Type(type="pg-uuid") - private UUID messageId; - private String acknowledgementTypeCode; - private String acknowledgementDetail; - private String service; - private String referencedMessageId; - private String messageRef; - private LocalDateTime createdAt; - private LocalDateTime updatedAt; - private LocalDateTime deletedAt; -} \ No newline at end of file diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/AcknowledgementRepository.java b/src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/AcknowledgementRepository.java deleted file mode 100644 index ff051175..00000000 --- a/src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/AcknowledgementRepository.java +++ /dev/null @@ -1,14 +0,0 @@ -package uk.nhs.prm.deduction.e2e.ehr_out_db; - -import org.springframework.data.repository.NoRepositoryBean; -import org.springframework.data.repository.Repository; - -import java.util.List; -import java.util.Optional; -import java.util.UUID; - -@NoRepositoryBean -public interface AcknowledgementRepository extends Repository { - Optional findByMessageId(UUID id); - List findAll(); -} \ No newline at end of file diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/EhrOutDbConfiguration.java b/src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/EhrOutDbConfiguration.java deleted file mode 100644 index e7b45a90..00000000 --- a/src/test/java/uk/nhs/prm/deduction/e2e/ehr_out_db/EhrOutDbConfiguration.java +++ /dev/null @@ -1,53 +0,0 @@ -package uk.nhs.prm.deduction.e2e.ehr_out_db; - -import lombok.AllArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.jdbc.DataSourceBuilder; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import uk.nhs.prm.deduction.e2e.client.RoleAssumingAwsConfigurationClient; - -import javax.sql.DataSource; -import java.util.Map; - -@Slf4j -@Configuration -@AllArgsConstructor(onConstructor = @__(@Autowired)) -public class EhrOutDbConfiguration { - @Value("${NHS_ENVIRONMENT}") - private final String environment; - private final RoleAssumingAwsConfigurationClient roleAssumingAwsConfigurationClient; - private final Map parameters = Map.of( - "DATABASE_HOST", getAwsParameterStoreValue("/repo/%s/output/prm-repo-ehr-out-service/db-host"), - "DATABASE_NAME", getAwsParameterStoreValue("/repo/%s/output/prm-repo-ehr-out-service/db-name"), - "DATABASE_USERNAME", getAwsParameterStoreValue("/repo/%s/user-input/ehr-out-service-db-username"), - "DATABASE_PASSWORD", getAwsParameterStoreValue("/repo/%s/user-input/ehr-out-service-db-password") - ); - - @Bean - public DataSource getDataSource() { - return DataSourceBuilder.create() - .driverClassName("org.postgresql.Driver") - .url(getJdbcUrl()) - .username(parameters.get("DATABASE_USERNAME")) - .password(parameters.get("DATABASE_PASSWORD")) - .build(); - } - - private String getJdbcUrl() { - return String.format("jdbc:postgresql://%s:5432/%s", - parameters.get("DATABASE_HOST"), - parameters.get("DATABASE_NAME")); - } - - private String getAwsParameterStoreValue(String parameterName) { - try { - return roleAssumingAwsConfigurationClient.getParamValue(String.format(parameterName, environment)); - } catch (NullPointerException exception) { - log.error(exception.getMessage()); - throw exception; - } - } -} diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/queue/QueueMessageHelper.java b/src/test/java/uk/nhs/prm/deduction/e2e/queue/QueueMessageHelper.java index 2244169c..91ed5cad 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/queue/QueueMessageHelper.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/queue/QueueMessageHelper.java @@ -108,7 +108,7 @@ private List findMessagesOnQueue(int visibilityTimeout) { private SqsMessage findMessageContaining(String substring) { List allMessages = thinlyWrappedSqsClient.readThroughMessages(this.queueUri, 180); for (SqsMessage message : allMessages) { - log(String.format("just finding message, checking conversationId: %s", this.queueUri)); + log(String.format("Finding message with substring %s on queue: %s", substring, this.queueUri)); if (message.contains(substring)) { return message; } diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/tests/EhrOutE2ETests.java b/src/test/java/uk/nhs/prm/deduction/e2e/tests/EhrOutE2ETests.java new file mode 100644 index 00000000..2fc07b5a --- /dev/null +++ b/src/test/java/uk/nhs/prm/deduction/e2e/tests/EhrOutE2ETests.java @@ -0,0 +1,247 @@ +package uk.nhs.prm.deduction.e2e.tests; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; +import org.jooq.DSLContext; +import org.jooq.Record; +import org.jooq.Result; +import org.jooq.SQLDialect; +import org.jooq.exception.DataAccessException; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import uk.nhs.prm.deduction.e2e.TestConfiguration; +import uk.nhs.prm.deduction.e2e.client.RoleAssumingAwsConfigurationClient; +import uk.nhs.prm.deduction.e2e.ehr_transfer.*; +import uk.nhs.prm.deduction.e2e.performance.awsauth.AssumeRoleCredentialsProviderFactory; +import uk.nhs.prm.deduction.e2e.performance.awsauth.AutoRefreshingRoleAssumingSqsClient; +import uk.nhs.prm.deduction.e2e.queue.BasicSqsClient; +import uk.nhs.prm.deduction.e2e.queue.SqsMessage; +import uk.nhs.prm.deduction.e2e.queue.ThinlyWrappedSqsClient; +import uk.nhs.prm.deduction.e2e.queue.activemq.SimpleAmqpQueue; +import uk.nhs.prm.deduction.e2e.transfer_tracker_db.TrackerDb; +import uk.nhs.prm.deduction.e2e.transfer_tracker_db.TransferTrackerDbClient; +import uk.nhs.prm.deduction.e2e.utility.LargeEhrTestFiles; +import uk.nhs.prm.deduction.e2e.utility.Resources; +import uk.nhs.prm.deduction.e2e.utility.TestUtils; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import static org.awaitility.Awaitility.await; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; +import static uk.nhs.prm.deduction.e2e.ehroutdb.tables.Acknowledgements.ACKNOWLEDGEMENTS; +import static uk.nhs.prm.deduction.e2e.utility.TestUtils.*; + +@SpringBootTest(classes = { + EhrOutE2ETests.class, + TestConfiguration.class, + ThinlyWrappedSqsClient.class, + BasicSqsClient.class, + AssumeRoleCredentialsProviderFactory.class, + AutoRefreshingRoleAssumingSqsClient.class, + Resources.class, + TrackerDb.class, + Gp2gpMessengerQueue.class, + TransferTrackerDbClient.class, + RoleAssumingAwsConfigurationClient.class +}) +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class EhrOutE2ETests { + private static final Logger LOGGER = LogManager.getLogger(EhrOutE2ETests.class); + private final TrackerDb trackerDb; + private final Gp2gpMessengerQueue gp2gpMessengerQueue; + private final TestConfiguration config; + + @Autowired + public EhrOutE2ETests( + TrackerDb trackerDb, + Gp2gpMessengerQueue gp2gpMessengerQueue, + TestConfiguration config + ) { + this.trackerDb = trackerDb; + this.gp2gpMessengerQueue = gp2gpMessengerQueue; + this.config = config; + } + + @BeforeAll + void init() { + gp2gpMessengerQueue.deleteAllMessages(); + } + + @Test + void shouldPutASmallEHROntoRepoAndSendEHRToMHSOutboundWhenReceivingRequestFromGP() { + // Given + String inboundConversationId = UUID.randomUUID().toString(); + String smallEhrMessageId = UUID.randomUUID().toString(); + String outboundConversationId = UUID.randomUUID().toString(); + String nhsNumberForTestPatient = "9727018440"; + String previousGpForTestPatient = "M85019"; + String asidCodeForTestPatient = "200000000149"; + LOGGER.info(" =============== outboundConversationId: {}", outboundConversationId); + + SimpleAmqpQueue inboundQueueFromMhs = new SimpleAmqpQueue(config); + + String smallEhr = getSmallEhrWithoutLinebreaks(inboundConversationId.toUpperCase(), smallEhrMessageId); + String ehrRequest = getEhrRequest(nhsNumberForTestPatient, previousGpForTestPatient, asidCodeForTestPatient, outboundConversationId); + + // When + // change transfer db status to ACTION:EHR_REQUEST_SENT before putting on inbound queue + // Put the patient into inboundQueueFromMhs as a UK05 message + + addRecordToTrackerDb(trackerDb, inboundConversationId, "", nhsNumberForTestPatient, previousGpForTestPatient, "ACTION:EHR_REQUEST_SENT"); + inboundQueueFromMhs.sendMessage(smallEhr, inboundConversationId); + + LOGGER.info("conversationIdExists: {}",trackerDb.conversationIdExists(inboundConversationId)); + String status = trackerDb.waitForStatusMatching(inboundConversationId, "ACTION:EHR_TRANSFER_TO_REPO_COMPLETE"); + LOGGER.info("tracker db status: {}", status); + + // Send an EHR request from inboundQueueFromMhs + inboundQueueFromMhs.sendMessage(ehrRequest, outboundConversationId); + + // Then + SqsMessage gp2gpMessage = gp2gpMessengerQueue.getMessageContaining(outboundConversationId); + + String gp2gpMessengerPayload = getPayloadOptional(gp2gpMessage.body()).orElseThrow(); + String smallEhrPayload = getPayloadOptional(smallEhr).orElseThrow(); + LOGGER.info("Payload from gp2gpMessenger: {}", gp2gpMessengerPayload); + LOGGER.info("Payload from smallEhr: {}", smallEhrPayload); + + assertThat(gp2gpMessage).isNotNull(); + assertTrue(gp2gpMessage.contains("RCMR_IN030000UK06")); + assertTrue(gp2gpMessengerPayload.contains(nhsNumberForTestPatient)); + + // clear up the queue after test in order not to interfere with other tests + gp2gpMessengerQueue.deleteMessage(gp2gpMessage); + } + + @Test + void shouldPutALargeEHROntoRepoAndSendEHRToMHSOutboundWhenReceivingRequestFromGP() { + // given + String inboundConversationId = UUID.randomUUID().toString(); + String outboundConversationId = UUID.randomUUID().toString(); + LOGGER.info(" =============== outboundConversationId: {}", outboundConversationId); + + String largeEhrCoreMessageId = UUID.randomUUID().toString(); + String fragment1MessageId = UUID.randomUUID().toString(); + String fragment2MessageId = UUID.randomUUID().toString(); + + String nhsNumberForTestPatient = "9727018157"; + String previousGpForTestPatient = "N82668"; + String newGpForTestPatient = "M85019"; + + SimpleAmqpQueue inboundQueueFromMhs = new SimpleAmqpQueue(config); + + LargeEhrTestFiles largeEhrTestFiles = TestUtils.prepareTestFilesForLargeEhr( + inboundConversationId, + outboundConversationId, + largeEhrCoreMessageId, + fragment1MessageId, + fragment2MessageId, + newGpForTestPatient, + nhsNumberForTestPatient + ); + + String largeEhrCore = largeEhrTestFiles.largeEhrCore; + String largeEhrFragment1 = largeEhrTestFiles.largeEhrFragment1; + String largeEhrFragment2 = largeEhrTestFiles.largeEhrFragment2; + String ehrRequest = largeEhrTestFiles.ehrRequest; + String continueRequest = largeEhrTestFiles.continueRequest; + + addRecordToTrackerDb(trackerDb, inboundConversationId, largeEhrCoreMessageId, nhsNumberForTestPatient, previousGpForTestPatient, "ACTION:EHR_REQUEST_SENT"); + + // when + inboundQueueFromMhs.sendMessage(largeEhrCore, inboundConversationId); + LOGGER.info("conversationIdExists: {}",trackerDb.conversationIdExists(inboundConversationId)); + String status = trackerDb.waitForStatusMatching(inboundConversationId, "ACTION:LARGE_EHR_CONTINUE_REQUEST_SENT"); + LOGGER.info("tracker db status: {}", status); + + LOGGER.info("fragment 1 message id: {}", fragment1MessageId); + LOGGER.info("fragment 2 message id: {}", fragment2MessageId); + + inboundQueueFromMhs.sendMessage(largeEhrFragment1, inboundConversationId); + inboundQueueFromMhs.sendMessage(largeEhrFragment2, inboundConversationId); + + status = trackerDb.waitForStatusMatching(inboundConversationId, "ACTION:EHR_TRANSFER_TO_REPO_COMPLETE"); + LOGGER.info("tracker db status: {}", status); + + // Put a EHR request to inboundQueueFromMhs + inboundQueueFromMhs.sendMessage(ehrRequest, outboundConversationId); + + // Then + // assert gp2gpMessenger queue got a message of UK06 + SqsMessage gp2gpMessageUK06 = gp2gpMessengerQueue.getMessageContaining(outboundConversationId); + + assertThat(gp2gpMessageUK06).isNotNull(); + assertThat(gp2gpMessageUK06.contains("RCMR_IN030000UK06")).isTrue(); + + // Put a continue request to inboundQueueFromMhs + inboundQueueFromMhs.sendMessage(continueRequest, outboundConversationId); + + // get all message fragments from gp2gp-messenger observability queue and compare with inbound fragments + List allFragments = gp2gpMessengerQueue.getAllMessageContaining("COPC_IN000001UK01"); + + assertThat(allFragments.size()).isEqualTo(2); + + allFragments.forEach(fragment -> assertThat(fragment.contains(outboundConversationId)).isTrue()); + + // clear up the queue after test in order not to interfere with other tests + gp2gpMessengerQueue.deleteMessage(gp2gpMessageUK06); + allFragments.forEach(gp2gpMessengerQueue::deleteMessage); + } + + @ParameterizedTest + @ValueSource(strings = {"MCCI_IN010000UK13_POSITIVE", "MCCI_IN010000UK13_NEGATIVE"}) + void shouldPutAcksOnMHSInboundAndUpdateEhrOutDbStatus(String acknowledgement) { + // given + String ackMessageId = UUID.randomUUID().toString(); + String ackConversationId = UUID.randomUUID().toString(); + String ackMessage = Resources.readTestResourceFile("acknowledgement/" + acknowledgement).replaceAll( + "__MESSAGE_ID__", ackMessageId + ); + + SimpleAmqpQueue inboundQueueFromMhs = new SimpleAmqpQueue(config); + + // when + inboundQueueFromMhs.sendMessage(ackMessage, ackConversationId); + + try(Connection connection = getRemoteConnection(config)) { + connection.setReadOnly(true); // we've got no reason to write to the database for these E2E tests + DSLContext context = DSL.using(connection, SQLDialect.POSTGRES); + + Result result = await().atMost(30, TimeUnit.SECONDS) + .with().pollInterval(2, TimeUnit.SECONDS) + .until(() -> getRecords(ackMessageId, context), Result::isNotEmpty); + + // then + assertTrue(result.isNotEmpty()); + + String typeCode = result.getValue(0, ACKNOWLEDGEMENTS.ACKNOWLEDGEMENT_TYPE_CODE); + String expectedTypeCode = acknowledgement.contains("POSITIVE") ? "AA" : "AR"; + assertThat(typeCode).isEqualTo(expectedTypeCode); + + LOGGER.info("The acknowledgement typeCode of {} is {}.", ackMessageId, typeCode); + } catch (DataAccessException | SQLException exception) { + LOGGER.error(exception.getMessage()); + fail(); + } + } + + private static Result getRecords(String ackMessageId, DSLContext context) { + return context + .select() + .from(ACKNOWLEDGEMENTS) + .where(ACKNOWLEDGEMENTS.MESSAGE_ID.eq(UUID.fromString(ackMessageId))) + .fetch(); + } +} diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java b/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java index 27c9e7d7..9b2bd6de 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/tests/RepositoryE2ETests.java @@ -2,16 +2,7 @@ import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; -import org.jooq.DSLContext; -import org.jooq.Record; -import org.jooq.Result; -import org.jooq.SQLDialect; -import org.jooq.exception.DataAccessException; -import org.jooq.impl.DSL; -import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.*; import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.params.ParameterizedTest; @@ -22,7 +13,6 @@ import org.xmlunit.diff.Diff; import uk.nhs.prm.deduction.e2e.TestConfiguration; import uk.nhs.prm.deduction.e2e.ehr_transfer.*; -import uk.nhs.prm.deduction.e2e.ehroutdb.tables.Acknowledgements; import uk.nhs.prm.deduction.e2e.end_of_transfer_service.EndOfTransferMofUpdatedMessageQueue; import uk.nhs.prm.deduction.e2e.models.Gp2GpSystem; import uk.nhs.prm.deduction.e2e.models.RepoIncomingMessageBuilder; @@ -40,8 +30,6 @@ import uk.nhs.prm.deduction.e2e.utility.Resources; import uk.nhs.prm.deduction.e2e.utility.TestUtils; -import java.sql.Connection; -import java.sql.SQLException; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; @@ -53,11 +41,8 @@ import static java.util.stream.Collectors.toList; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; import static org.springframework.test.util.AssertionErrors.assertFalse; import static uk.nhs.prm.deduction.e2e.utility.TestUtils.*; -import static uk.nhs.prm.deduction.e2e.ehroutdb.tables.Acknowledgements.*; -import static org.assertj.core.api.ListAssert.*; @SpringBootTest(classes = { RepositoryE2ETests.class, @@ -201,6 +186,9 @@ void shouldVerifyThatASmallEhrXMLIsUnchanged() { Diff myDiff = comparePayloads(gp2gpMessengerPayload, smallEhrPayload); assertFalse(myDiff.toString(), myDiff.hasDifferences()); + + // clear up the queue after test in order not to interfere with other tests + gp2gpMessengerQueue.deleteMessage(gp2gpMessage); } @Test @@ -290,33 +278,10 @@ void shouldVerifyThatALargeEhrXMLIsUnchanged() { assertTrue(identicalWithFragment1 || identicalWithFragment2); }); - } - @Test - void tryConnectToPostgresDb() { - try(Connection connection = getRemoteConnection(config)) { - // given - String messageId = "3327d3e7-a1e7-4ec5-850b-912db9c8c5dd"; - - // when - connection.setReadOnly(true); // we've got no reason to write to the database for these E2E tests - DSLContext context = DSL.using(connection, SQLDialect.POSTGRES); - Result result = context - .select() - .from(ACKNOWLEDGEMENTS) - .where(ACKNOWLEDGEMENTS.MESSAGE_ID.eq(UUID.fromString(messageId))) - .fetch(); - - String typeCode = result.getValue(0, ACKNOWLEDGEMENTS.ACKNOWLEDGEMENT_TYPE_CODE); - - // then - assertTrue(result.isNotEmpty()); - assertThat(typeCode).isEqualTo("AR"); - LOGGER.info("The acknowledgement typeCode of {} is {}.", messageId, typeCode); - } catch (DataAccessException | SQLException exception) { - LOGGER.error(exception.getMessage()); - fail(); - } + // clear up the queue after test in order not to interfere with other tests + gp2gpMessengerQueue.deleteMessage(gp2gpMessageUK06); + allFragments.forEach(gp2gpMessengerQueue::deleteMessage); } @Test diff --git a/src/test/resources/acknowledgement/MCCI_IN010000UK13_NEGATIVE b/src/test/resources/acknowledgement/MCCI_IN010000UK13_NEGATIVE new file mode 100644 index 00000000..2e5d902c --- /dev/null +++ b/src/test/resources/acknowledgement/MCCI_IN010000UK13_NEGATIVE @@ -0,0 +1 @@ +{"ebXML": "YGM24-820388B85002-822652d147eed066c0f5600c45DBC31D30-F984-11ED-A4C4-956AA80C6B4Eurn:nhs:names:services:gp2gpMCCI_IN010000UK13__MESSAGE_ID__2023-05-24T16:56:06Z2023-05-24T17:06:06Zalways", "payload": "", "attachments": [], "external_attachments": []} \ No newline at end of file diff --git a/src/test/resources/acknowledgement/MCCI_IN010000UK13_POSITIVE b/src/test/resources/acknowledgement/MCCI_IN010000UK13_POSITIVE new file mode 100644 index 00000000..e6bb9ed0 --- /dev/null +++ b/src/test/resources/acknowledgement/MCCI_IN010000UK13_POSITIVE @@ -0,0 +1 @@ +{"ebXML": "YGM24-820388B85002-822652d147eed066c0f5600c45EF967FA0-FECA-11ED-9213-8B066C12C492urn:nhs:names:services:gp2gpMCCI_IN010000UK13__MESSAGE_ID__2023-05-30T10:34:53Z2023-05-30T10:44:53Zalways", "payload": "", "attachments": [], "external_attachments": []} \ No newline at end of file diff --git a/src/test/resources/ehr/large-ehr-fragment-1 b/src/test/resources/ehr/large-ehr-fragment-1 index c6028786..89ac9e5f 100644 --- a/src/test/resources/ehr/large-ehr-fragment-1 +++ b/src/test/resources/ehr/large-ehr-fragment-1 @@ -1 +1 @@ -{"ebXML": "5XZ-821385B85002-822652b462b787b8b228b75c8f71118F7D-59CE-4552-B7AE-45A6801F4334urn:nhs:names:services:gp2gpCOPC_IN000001UK013DBFC9EB-32FA-444F-B996-AB680D64148E2022-09-30T12:59:53.848Z2022-09-30T19:14:53.848ZCOPC_IN000001UK01Filename=\"EDB676C8-9416-43FB-9F40-CF8CACFB5EFB_e_0.jpg\" ContentType=image/jpeg Compressed=No LargeAttachment=No OriginalBase64=No Length=4718592Filename=\"EDB676C8-9416-43FB-9F40-CF8CACFB5EFB_e_1.jpg\" ContentType=image/jpeg Compressed=No LargeAttachment=No OriginalBase64=No Length=2568316", "payload": "01B85002N82668Attachment: EDB676C8-9416-43FB-9F40-CF8CACFB5EFB_e_0.jpg3DBFC9EB-32FA-444F-B996-AB680D64148E", "attachments": [{"payload": "", "is_base64": true, "content_id": "Attachment1@e-mis.com/EMISWeb/GP2GP2.2A", "content_type": "image/jpeg"}]} \ No newline at end of file +{"ebXML": "5XZ-821385B85002-822652b462b787b8b228b75c8f71118F7D-59CE-4552-B7AE-45A6801F4334urn:nhs:names:services:gp2gpCOPC_IN000001UK013DBFC9EB-32FA-444F-B996-AB680D64148E2022-09-30T12:59:53.848Z2022-09-30T19:14:53.848ZCOPC_IN000001UK01Filename=\"EDB676C8-9416-43FB-9F40-CF8CACFB5EFB_e_0.jpg\" ContentType=image/jpeg Compressed=No LargeAttachment=No OriginalBase64=No Length=4718592Filename=\"EDB676C8-9416-43FB-9F40-CF8CACFB5EFB_e_1.jpg\" ContentType=image/jpeg Compressed=No LargeAttachment=No OriginalBase64=No Length=2568316", "payload": "01B85002N82668Attachment: EDB676C8-9416-43FB-9F40-CF8CACFB5EFB_e_0.jpg3DBFC9EB-32FA-444F-B996-AB680D64148E", "attachments": [{"payload": "dGVzdF9wYXlsb2FkCg==", "is_base64": true, "content_id": "Attachment1@e-mis.com/EMISWeb/GP2GP2.2A", "content_type": "image/jpeg"}]} \ No newline at end of file diff --git a/src/test/resources/ehr/large-ehr-fragment-2 b/src/test/resources/ehr/large-ehr-fragment-2 index 55758a02..db50a622 100644 --- a/src/test/resources/ehr/large-ehr-fragment-2 +++ b/src/test/resources/ehr/large-ehr-fragment-2 @@ -1 +1 @@ -{"ebXML": "5XZ-821385B85002-822652b462b787b8b228b75c8f71118F7D-59CE-4552-B7AE-45A6801F4334urn:nhs:names:services:gp2gpCOPC_IN000001UK0103CBFB18-0F7E-4BB6-B9EF-46AF564D3B9C2022-09-30T12:59:58.708Z2022-09-30T19:14:58.708ZCOPC_IN000001UK01EDB676C8-9416-43FB-9F40-CF8CACFB5EFB_e_1.jpg", "payload": "01B85002N82668Attachment: EDB676C8-9416-43FB-9F40-CF8CACFB5EFB_e_1.jpg03CBFB18-0F7E-4BB6-B9EF-46AF564D3B9C", "attachments": [{"payload": "", "is_base64": true, "content_id": "Attachment1@e-mis.com/EMISWeb/GP2GP2.2A", "content_type": "image/jpeg"}]} \ No newline at end of file +{"ebXML": "5XZ-821385B85002-822652b462b787b8b228b75c8f71118F7D-59CE-4552-B7AE-45A6801F4334urn:nhs:names:services:gp2gpCOPC_IN000001UK0103CBFB18-0F7E-4BB6-B9EF-46AF564D3B9C2022-09-30T12:59:58.708Z2022-09-30T19:14:58.708ZCOPC_IN000001UK01EDB676C8-9416-43FB-9F40-CF8CACFB5EFB_e_1.jpg", "payload": "01B85002N82668Attachment: EDB676C8-9416-43FB-9F40-CF8CACFB5EFB_e_1.jpg03CBFB18-0F7E-4BB6-B9EF-46AF564D3B9C", "attachments": [{"payload": "dGVzdF9wYXlsb2FkCg==", "is_base64": true, "content_id": "Attachment1@e-mis.com/EMISWeb/GP2GP2.2A", "content_type": "image/jpeg"}]} \ No newline at end of file diff --git a/tasks b/tasks index 2ce7009a..6c9843bd 100755 --- a/tasks +++ b/tasks @@ -129,7 +129,7 @@ case "${command}" in dojo "./tasks _test_continuity_e2e" ;; _test_repo_e2e) - gradle test --tests "uk.nhs.prm.deduction.e2e.tests.RepositoryE2ETests" + gradle test --tests "uk.nhs.prm.deduction.e2e.tests.EhrOutE2ETests" --tests "uk.nhs.prm.deduction.e2e.tests.RepositoryE2ETests" ;; test_repo_e2e) check_env From 0d4b5320553bc0180b39b32e19ed5256e57b3701 Mon Sep 17 00:00:00 2001 From: Mohammad Iqbal Date: Tue, 27 Jun 2023 17:03:29 +0100 Subject: [PATCH 5/5] [PRMT-3411] Addressed some pull request comments --- .../prm/deduction/e2e/TestConfiguration.java | 3 +- .../e2e/queue/QueueMessageHelper.java | 31 +++++++++---------- .../deduction/e2e/tests/EhrOutE2ETests.java | 16 ++-------- 3 files changed, 19 insertions(+), 31 deletions(-) diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java b/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java index 230e698d..211d0425 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/TestConfiguration.java @@ -98,8 +98,7 @@ public String getEhrOutPostgresJdbcUrl() { String password = awsConfigurationClient.getParamValue(String.format("/repo/%s/user-input/ehr-out-service-db-password", getEnvironmentName())); String username = awsConfigurationClient.getParamValue(String.format("/repo/%s/user-input/ehr-out-service-db-username", getEnvironmentName())); String dbname = awsConfigurationClient.getParamValue(String.format("/repo/%s/output/prm-repo-ehr-out-service/db-name", getEnvironmentName())); - String port = "5432"; - return "jdbc:postgresql://" + hostname + ":" + port + "/" + dbname + "?user=" + username + "&password=" + password; + return "jdbc:postgresql://" + hostname + ":5432/" + dbname + "?user=" + username + "&password=" + password; } public String getRepoOdsCode() { diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/queue/QueueMessageHelper.java b/src/test/java/uk/nhs/prm/deduction/e2e/queue/QueueMessageHelper.java index 91ed5cad..e49fd409 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/queue/QueueMessageHelper.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/queue/QueueMessageHelper.java @@ -9,6 +9,7 @@ import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; +import java.util.Optional; import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; @@ -44,12 +45,16 @@ public void log(String messageBody) { public SqsMessage getMessageContaining(String substring) { log(String.format("Checking if message is present on : %s", this.queueUri)); - SqsMessage found = await().atMost(120, TimeUnit.SECONDS) + Optional found = await().atMost(120, TimeUnit.SECONDS) .with() .pollInterval(100, TimeUnit.MILLISECONDS) - .until(() -> findMessageContaining(substring), notNullValue()); + .until(() -> findMessageContaining(substring), Optional::isPresent); log(String.format("Found message on : %s", this.queueUri)); - return found; + if (found.isPresent()) { + return found.get(); + } else { + throw new RuntimeException(); + } } public List getAllMessageContaining(String substring) { @@ -58,10 +63,8 @@ public List getAllMessageContaining(String substring) { await().atMost(120, TimeUnit.SECONDS) .with() .pollInterval(100, TimeUnit.MILLISECONDS).untilAsserted(() -> { - SqsMessage found = findMessageContaining(substring); - if (found != null) { - allMessages.add(found); - } + Optional found = findMessageContaining(substring); + found.ifPresent(allMessages::add); assertTrue(allMessages.size() >= 2); }); @@ -105,15 +108,11 @@ private List findMessagesOnQueue(int visibilityTimeout) { return messages.isEmpty() ? null : messages; } - private SqsMessage findMessageContaining(String substring) { - List allMessages = thinlyWrappedSqsClient.readThroughMessages(this.queueUri, 180); - for (SqsMessage message : allMessages) { - log(String.format("Finding message with substring %s on queue: %s", substring, this.queueUri)); - if (message.contains(substring)) { - return message; - } - } - return null; + private Optional findMessageContaining(String substring) { + return thinlyWrappedSqsClient.readThroughMessages(this.queueUri, 180) + .stream() + .filter(message -> message.contains(substring)) + .findFirst(); } public SqsMessage findMessageWithAttribute(String attribute, String expectedValue) { diff --git a/src/test/java/uk/nhs/prm/deduction/e2e/tests/EhrOutE2ETests.java b/src/test/java/uk/nhs/prm/deduction/e2e/tests/EhrOutE2ETests.java index 2fc07b5a..879508f7 100644 --- a/src/test/java/uk/nhs/prm/deduction/e2e/tests/EhrOutE2ETests.java +++ b/src/test/java/uk/nhs/prm/deduction/e2e/tests/EhrOutE2ETests.java @@ -1,5 +1,6 @@ package uk.nhs.prm.deduction.e2e.tests; +import lombok.AllArgsConstructor; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.jooq.DSLContext; @@ -57,23 +58,13 @@ RoleAssumingAwsConfigurationClient.class }) @TestInstance(TestInstance.Lifecycle.PER_CLASS) +@AllArgsConstructor(onConstructor = @__(@Autowired)) public class EhrOutE2ETests { private static final Logger LOGGER = LogManager.getLogger(EhrOutE2ETests.class); private final TrackerDb trackerDb; private final Gp2gpMessengerQueue gp2gpMessengerQueue; private final TestConfiguration config; - @Autowired - public EhrOutE2ETests( - TrackerDb trackerDb, - Gp2gpMessengerQueue gp2gpMessengerQueue, - TestConfiguration config - ) { - this.trackerDb = trackerDb; - this.gp2gpMessengerQueue = gp2gpMessengerQueue; - this.config = config; - } - @BeforeAll void init() { gp2gpMessengerQueue.deleteAllMessages(); @@ -97,9 +88,8 @@ void shouldPutASmallEHROntoRepoAndSendEHRToMHSOutboundWhenReceivingRequestFromGP // When // change transfer db status to ACTION:EHR_REQUEST_SENT before putting on inbound queue - // Put the patient into inboundQueueFromMhs as a UK05 message - addRecordToTrackerDb(trackerDb, inboundConversationId, "", nhsNumberForTestPatient, previousGpForTestPatient, "ACTION:EHR_REQUEST_SENT"); + // Put the patient into inboundQueueFromMhs as a UK05 message inboundQueueFromMhs.sendMessage(smallEhr, inboundConversationId); LOGGER.info("conversationIdExists: {}",trackerDb.conversationIdExists(inboundConversationId));