From 572061b3cfa4fb9c69211ac58a53ff4978c72ded Mon Sep 17 00:00:00 2001 From: Michael Hoennig Date: Tue, 30 Jan 2024 10:50:35 +0100 Subject: [PATCH] cleanup via ContextBasedTestWithCleanup and some fixes --- README.md | 2 +- .../HsOfficeBankAccountRepository.java | 2 +- .../db/changelog/230-hs-office-partner.sql | 2 +- .../changelog/233-hs-office-partner-rbac.sql | 13 +- .../238-hs-office-partner-test-data.sql | 2 +- ...eBankAccountRepositoryIntegrationTest.java | 31 +--- ...fficeContactRepositoryIntegrationTest.java | 27 +-- .../hs/office/migration/ImportOfficeData.java | 2 +- ...OfficePartnerControllerAcceptanceTest.java | 108 ++++++------ ...fficePartnerRepositoryIntegrationTest.java | 113 ++++++------- ...sOfficePersonControllerAcceptanceTest.java | 1 - ...OfficePersonRepositoryIntegrationTest.java | 25 +-- ...eRelationshipControllerAcceptanceTest.java | 5 +- ...ceSepaMandateControllerAcceptanceTest.java | 7 +- ...eSepaMandateRepositoryIntegrationTest.java | 21 +-- .../test/ContextBasedTestWithCleanup.java | 156 ++++++++++++++---- 16 files changed, 271 insertions(+), 246 deletions(-) diff --git a/README.md b/README.md index b77f9957..04827ba3 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ To be able to build and run the Java Spring Boot application, you need the follo - Docker 20.x (on MacOS you also need *Docker Desktop* or similar) or Podman - optionally: PostgreSQL Server 15.5-bookworm (see instructions below to install and run in Docker) -- The matching Java JDK at will be automatically installed by Gradle toolchain support. +- The matching Java JDK at will be automatically installed by Gradle toolchain support to `~/.gradle/jdks/`. - You also might need an IDE (e.g. *IntelliJ IDEA* or *Eclipse* or *VS Code* with *[STS](https://spring.io/tools)* and a GUI Frontend for *PostgreSQL* like *Postbird*. If you have at least Docker and the Java JDK installed in appropriate versions and in your `PATH`, then you can start like this: diff --git a/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepository.java b/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepository.java index 92b12960..e3b397f5 100644 --- a/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepository.java +++ b/src/main/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepository.java @@ -19,7 +19,7 @@ public interface HsOfficeBankAccountRepository extends Repository findByOptionalHolderLike(String holder); - List findByIbanOrderByIban(String iban); + List findByIbanOrderByIbanAsc(String iban); S save(S entity); diff --git a/src/main/resources/db/changelog/230-hs-office-partner.sql b/src/main/resources/db/changelog/230-hs-office-partner.sql index c623d1bf..c8abe38d 100644 --- a/src/main/resources/db/changelog/230-hs-office-partner.sql +++ b/src/main/resources/db/changelog/230-hs-office-partner.sql @@ -32,7 +32,7 @@ call create_journal('hs_office_partner_details'); create table hs_office_partner ( uuid uuid unique references RbacObject (uuid) initially deferred, - partnerNumber numeric(5), + partnerNumber numeric(5) unique not null, partnerRoleUuid uuid not null references hs_office_relationship(uuid) on delete cascade, personUuid uuid not null references hs_office_person(uuid), -- TODO: remove, replaced by partnerRoleUuid contactUuid uuid not null references hs_office_contact(uuid), -- TODO: remove, replaced by partnerRoleUuid diff --git a/src/main/resources/db/changelog/233-hs-office-partner-rbac.sql b/src/main/resources/db/changelog/233-hs-office-partner-rbac.sql index ee3a4882..d4b0105c 100644 --- a/src/main/resources/db/changelog/233-hs-office-partner-rbac.sql +++ b/src/main/resources/db/changelog/233-hs-office-partner-rbac.sql @@ -120,14 +120,14 @@ begin if OLD.partnerRoleUuid <> NEW.partnerRoleUuid then select * from hs_office_relationship as r where r.uuid = OLD.partnerRoleUuid into oldPartnerRole; - call revokeRoleFromRole(hsOfficeRelationshipTenant(oldPerson), hsOfficePartnerAdmin(OLD)); - call grantRoleToRole(hsOfficeRelationshipTenant(newPerson), hsOfficePartnerAdmin(NEW)); + call revokeRoleFromRole(hsOfficeRelationshipTenant(oldPartnerRole), hsOfficePartnerAdmin(OLD)); + call grantRoleToRole(hsOfficeRelationshipTenant(newPartnerRole), hsOfficePartnerAdmin(NEW)); - call revokeRoleFromRole(hsOfficePartnerAgent(OLD), hsOfficeRelationshipAdmin(oldPerson)); - call grantRoleToRole(hsOfficePartnerAgent(NEW), hsOfficeRelationshipAdmin(newPerson)); + call revokeRoleFromRole(hsOfficePartnerAgent(OLD), hsOfficeRelationshipAdmin(oldPartnerRole)); + call grantRoleToRole(hsOfficePartnerAgent(NEW), hsOfficeRelationshipAdmin(newPartnerRole)); - call revokeRoleFromRole(hsOfficeRelationshipGuest(oldPerson), hsOfficePartnerTenant(OLD)); - call grantRoleToRole(hsOfficeRelationshipGuest(newPerson), hsOfficePartnerTenant(NEW)); + call revokeRoleFromRole(hsOfficeRelationshipGuest(oldPartnerRole), hsOfficePartnerTenant(OLD)); + call grantRoleToRole(hsOfficeRelationshipGuest(newPartnerRole), hsOfficePartnerTenant(NEW)); end if; if OLD.personUuid <> NEW.personUuid then @@ -204,7 +204,6 @@ call generateRbacRestrictedView('hs_office_partner', personUuid = new.personUuid, contactUuid = new.contactUuid $updates$); --- partnerRoleUuid = new.partnerRoleUuid, --// diff --git a/src/main/resources/db/changelog/238-hs-office-partner-test-data.sql b/src/main/resources/db/changelog/238-hs-office-partner-test-data.sql index 9f5de04d..146f2f1d 100644 --- a/src/main/resources/db/changelog/238-hs-office-partner-test-data.sql +++ b/src/main/resources/db/changelog/238-hs-office-partner-test-data.sql @@ -63,7 +63,7 @@ begin else insert into hs_office_partner_details (uuid, registrationOffice, registrationNumber) - values (uuid_generate_v4(), 'Hamburg', '12345') + values (uuid_generate_v4(), 'Hamburg', 'RegNo123456789') returning uuid into relatedDetailsUuid; end if; diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java index 6046d55a..d7e75aec 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/bankaccount/HsOfficeBankAccountRepositoryIntegrationTest.java @@ -7,8 +7,6 @@ import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; import net.hostsharing.test.Array; import net.hostsharing.test.JpaAttempt; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -61,8 +59,8 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC final var count = bankAccountRepo.count(); // when - final var result = attempt(em, () -> bankAccountRepo.save( - hsOfficeBankAccount("some temp acc A", "DE37500105177419788228", ""))); + final var result = attempt(em, () -> toCleanup(bankAccountRepo.save( + hsOfficeBankAccount("some temp acc A", "DE37500105177419788228", "")))); // then result.assertSuccessful(); @@ -78,8 +76,8 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC final var count = bankAccountRepo.count(); // when - final var result = attempt(em, () -> bankAccountRepo.save( - hsOfficeBankAccount("some temp acc B", "DE49500105174516484892", "INGDDEFFXXX"))); + final var result = attempt(em, () -> toCleanup(bankAccountRepo.save( + hsOfficeBankAccount("some temp acc B", "DE49500105174516484892", "INGDDEFFXXX")))); // then result.assertSuccessful(); @@ -96,8 +94,8 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC final var initialGrantNames = grantDisplaysOf(rawGrantRepo.findAll()); // when - attempt(em, () -> bankAccountRepo.save( - hsOfficeBankAccount("some temp acc C", "DE25500105176934832579", "INGDDEFFXXX")) + attempt(em, () -> toCleanup(bankAccountRepo.save( + hsOfficeBankAccount("some temp acc C", "DE25500105176934832579", "INGDDEFFXXX"))) ).assertSuccessful(); // then @@ -174,7 +172,7 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC context("superuser-alex@hostsharing.net", null); // when - final var result = bankAccountRepo.findByIbanOrderByIban("DE02120300000000202051"); + final var result = bankAccountRepo.findByIbanOrderByIbanAsc("DE02120300000000202051"); // then exactlyTheseBankAccountsAreReturned(result, "First GmbH"); @@ -187,7 +185,7 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC // when: context("selfregistered-user-drew@hostsharing.org"); - final var result = bankAccountRepo.findByIbanOrderByIban(givenBankAccount.getIban()); + final var result = bankAccountRepo.findByIbanOrderByIbanAsc(givenBankAccount.getIban()); // then: exactlyTheseBankAccountsAreReturned(result, givenBankAccount.getHolder()); @@ -271,7 +269,7 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC Supplier entitySupplier) { return jpaAttempt.transacted(() -> { context(createdByUser); - return bankAccountRepo.save(entitySupplier.get()); + return toCleanup(bankAccountRepo.save(entitySupplier.get())); }).assertSuccessful().returnedValue(); } @@ -293,17 +291,6 @@ class HsOfficeBankAccountRepositoryIntegrationTest extends ContextBasedTestWithC "[creating bankaccount test-data Second e.K., hs_office_bankaccount, INSERT]"); } - @BeforeEach - @AfterEach - void cleanup() { - context("superuser-alex@hostsharing.net", null); - final var result = bankAccountRepo.findByOptionalHolderLike("some temp acc"); - result.forEach(tempPerson -> { - System.out.println("DELETING temporary bankaccount: " + tempPerson.getHolder()); - bankAccountRepo.deleteByUuid(tempPerson.getUuid()); - }); - } - private HsOfficeBankAccountEntity givenSomeTemporaryBankAccount(final String createdByUser) { final var random = RandomStringUtils.randomAlphabetic(3); return givenSomeTemporaryBankAccount(createdByUser, () -> diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRepositoryIntegrationTest.java index 02a875ae..a44ed46f 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/contact/HsOfficeContactRepositoryIntegrationTest.java @@ -7,8 +7,6 @@ import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; import net.hostsharing.test.Array; import net.hostsharing.test.JpaAttempt; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -62,8 +60,8 @@ class HsOfficeContactRepositoryIntegrationTest extends ContextBasedTestWithClean // when - final var result = attempt(em, () -> contactRepo.save( - hsOfficeContact("a new contact", "contact-admin@www.example.com"))); + final var result = attempt(em, () -> toCleanup(contactRepo.save( + hsOfficeContact("a new contact", "contact-admin@www.example.com")))); // then result.assertSuccessful(); @@ -79,8 +77,8 @@ class HsOfficeContactRepositoryIntegrationTest extends ContextBasedTestWithClean final var count = contactRepo.count(); // when - final var result = attempt(em, () -> contactRepo.save( - hsOfficeContact("another new contact", "another-new-contact@example.com"))); + final var result = attempt(em, () -> toCleanup(contactRepo.save( + hsOfficeContact("another new contact", "another-new-contact@example.com")))); // then result.assertSuccessful(); @@ -97,8 +95,8 @@ class HsOfficeContactRepositoryIntegrationTest extends ContextBasedTestWithClean final var initialGrantNames = grantDisplaysOf(rawGrantRepo.findAll()); // when - attempt(em, () -> contactRepo.save( - hsOfficeContact("another new contact", "another-new-contact@example.com")) + attempt(em, () -> toCleanup(contactRepo.save( + hsOfficeContact("another new contact", "another-new-contact@example.com"))) ).assumeSuccessful(); // then @@ -278,21 +276,10 @@ class HsOfficeContactRepositoryIntegrationTest extends ContextBasedTestWithClean Supplier entitySupplier) { return jpaAttempt.transacted(() -> { context(createdByUser); - return contactRepo.save(entitySupplier.get()); + return toCleanup(contactRepo.save(entitySupplier.get())); }).assumeSuccessful().returnedValue(); } - @BeforeEach - @AfterEach - void cleanup() { - context("superuser-alex@hostsharing.net", null); - final var result = contactRepo.findContactByOptionalLabelLike("some temporary contact"); - result.forEach(tempPerson -> { - System.out.println("DELETING temporary contact: " + tempPerson.getLabel()); - contactRepo.deleteByUuid(tempPerson.getUuid()); - }); - } - private HsOfficeContactEntity givenSomeTemporaryContact(final String createdByUser) { final var random = RandomStringUtils.randomAlphabetic(12); return givenSomeTemporaryContact(createdByUser, () -> diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/migration/ImportOfficeData.java b/src/test/java/net/hostsharing/hsadminng/hs/office/migration/ImportOfficeData.java index b0aa2c9e..377a415f 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/migration/ImportOfficeData.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/migration/ImportOfficeData.java @@ -1179,7 +1179,7 @@ class OrderedDependedTestsExtension implements TestWatcher, BeforeEachCallback { } @Override - public void beforeEach(final ExtensionContext extensionContext) throws Exception { + public void beforeEach(final ExtensionContext extensionContext) { assumeThat(previousTestsPassed).isTrue(); } } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerAcceptanceTest.java index eff9dc61..2b91f0fe 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerControllerAcceptanceTest.java @@ -19,7 +19,6 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; import org.springframework.transaction.annotation.Transactional; -import java.util.List; import java.util.UUID; import static net.hostsharing.test.IsValidUuidMatcher.isUuidValid; @@ -70,7 +69,15 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu .then().log().all().assertThat() .statusCode(200) .contentType("application/json") - .body("", hasSize(5)); + .body("", lenientlyEquals(""" + [ + { partnerNumber: 10001 }, + { partnerNumber: 10002 }, + { partnerNumber: 10003 }, + { partnerNumber: 10004 }, + { partnerNumber: 10010 } + ] + """)); // @formatter:on } } @@ -94,7 +101,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu .contentType(ContentType.JSON) .body(""" { - "partnerNumber": "12345", + "partnerNumber": "20002", "partnerRole": { "relAnchorUuid": "%s", "relHolderUuid": "%s", @@ -120,6 +127,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu .statusCode(201) .contentType(ContentType.JSON) .body("uuid", isUuidValid()) + .body("partnerNumber", is(20002)) .body("details.registrationOffice", is("Temp Registergericht Aurich")) .body("details.registrationNumber", is("111111")) .body("contact.label", is(givenContact.getLabel())) @@ -146,7 +154,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu .contentType(ContentType.JSON) .body(""" { - "partnerNumber": "12345", + "partnerNumber": "20003", "partnerRole": { "relAnchorUuid": "%s", "relHolderUuid": "%s", @@ -184,7 +192,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu .contentType(ContentType.JSON) .body(""" { - "partnerNumber": "12345", + "partnerNumber": "20004", "partnerRole": { "relAnchorUuid": "%s", "relHolderUuid": "%s", @@ -286,27 +294,27 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu void globalAdmin_withoutAssumedRole_canPatchAllPropertiesOfArbitraryPartner() { context.define("superuser-alex@hostsharing.net"); - final var givenPartner = givenSomeTemporaryPartnerBessler(); + final var givenPartner = givenSomeTemporaryPartnerBessler(20011); final var givenPerson = personRepo.findPersonByOptionalNameLike("Third").get(0); final var givenContact = contactRepo.findContactByOptionalLabelLike("fourth").get(0); - final var location = RestAssured // @formatter:off + RestAssured // @formatter:off .given() .header("current-user", "superuser-alex@hostsharing.net") .contentType(ContentType.JSON) .body(""" - { - "partnerNumber": "12345", - "contactUuid": "%s", - "personUuid": "%s", - "details": { - "registrationOffice": "Temp Registergericht Aurich", - "registrationNumber": "222222", - "birthName": "Maja Schmidt", - "birthday": "1938-04-08", - "dateOfDeath": "2022-01-12" - } - } + { + "partnerNumber": "20011", + "contactUuid": "%s", + "personUuid": "%s", + "details": { + "registrationOffice": "Temp Registergericht Aurich", + "registrationNumber": "222222", + "birthName": "Maja Schmidt", + "birthday": "1938-04-08", + "dateOfDeath": "2022-01-12" + } + } """.formatted(givenContact.getUuid(), givenPerson.getUuid())) .port(port) .when() @@ -314,8 +322,8 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu .then().assertThat() .statusCode(200) .contentType(ContentType.JSON) - .body("uuid", isUuidValid()) - .body("partnerNumber", is(givenPartner.getPartnerNumber())) + .body("uuid", is(givenPartner.getUuid().toString())) // not patched! + .body("partnerNumber", is(givenPartner.getPartnerNumber())) // not patched! .body("details.registrationNumber", is("222222")) .body("contact.label", is(givenContact.getLabel())) .body("person.tradeName", is(givenPerson.getTradeName())); @@ -324,14 +332,15 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu // finally, the partner is actually updated context.define("superuser-alex@hostsharing.net"); assertThat(partnerRepo.findByUuid(givenPartner.getUuid())).isPresent().get() - .matches(person -> { - assertThat(person.getPerson().getTradeName()).isEqualTo("Third OHG"); - assertThat(person.getContact().getLabel()).isEqualTo("fourth contact"); - assertThat(person.getDetails().getRegistrationOffice()).isEqualTo("Temp Registergericht Aurich"); - assertThat(person.getDetails().getRegistrationNumber()).isEqualTo("222222"); - assertThat(person.getDetails().getBirthName()).isEqualTo("Maja Schmidt"); - assertThat(person.getDetails().getBirthday()).isEqualTo("1938-04-08"); - assertThat(person.getDetails().getDateOfDeath()).isEqualTo("2022-01-12"); + .matches(partner -> { + assertThat(partner.getPartnerNumber()).isEqualTo(givenPartner.getPartnerNumber()); + assertThat(partner.getPerson().getTradeName()).isEqualTo("Third OHG"); + assertThat(partner.getContact().getLabel()).isEqualTo("fourth contact"); + assertThat(partner.getDetails().getRegistrationOffice()).isEqualTo("Temp Registergericht Aurich"); + assertThat(partner.getDetails().getRegistrationNumber()).isEqualTo("222222"); + assertThat(partner.getDetails().getBirthName()).isEqualTo("Maja Schmidt"); + assertThat(partner.getDetails().getBirthday()).isEqualTo("1938-04-08"); + assertThat(partner.getDetails().getDateOfDeath()).isEqualTo("2022-01-12"); return true; }); } @@ -340,7 +349,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu void globalAdmin_withoutAssumedRole_canPatchPartialPropertiesOfArbitraryPartner() { context.define("superuser-alex@hostsharing.net"); - final var givenPartner = givenSomeTemporaryPartnerBessler(); + final var givenPartner = givenSomeTemporaryPartnerBessler(20012); final var location = RestAssured // @formatter:off .given() @@ -391,7 +400,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu @Test void globalAdmin_withoutAssumedRole_canDeleteArbitraryPartner() { context.define("superuser-alex@hostsharing.net"); - final var givenPartner = givenSomeTemporaryPartnerBessler(); + final var givenPartner = givenSomeTemporaryPartnerBessler(20013); RestAssured // @formatter:off .given() @@ -411,7 +420,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu @Accepts({ "Partner:X(Access Control)" }) void contactAdminUser_canNotDeleteRelatedPartner() { context.define("superuser-alex@hostsharing.net"); - final var givenPartner = givenSomeTemporaryPartnerBessler(); + final var givenPartner = givenSomeTemporaryPartnerBessler(20014); assertThat(givenPartner.getContact().getLabel()).isEqualTo("fourth contact"); RestAssured // @formatter:off @@ -431,7 +440,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu @Accepts({ "Partner:X(Access Control)" }) void normalUser_canNotDeleteUnrelatedPartner() { context.define("superuser-alex@hostsharing.net"); - final var givenPartner = givenSomeTemporaryPartnerBessler(); + final var givenPartner = givenSomeTemporaryPartnerBessler(20015); assertThat(givenPartner.getContact().getLabel()).isEqualTo("fourth contact"); RestAssured // @formatter:off @@ -448,7 +457,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu } } - private HsOfficePartnerEntity givenSomeTemporaryPartnerBessler() { + private HsOfficePartnerEntity givenSomeTemporaryPartnerBessler(final Integer partnerNumber) { return jpaAttempt.transacted(() -> { context.define("superuser-alex@hostsharing.net"); final var givenMandantPerson = personRepo.findPersonByOptionalNameLike("Hostsharing eG").get(0); @@ -465,6 +474,7 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu final var newPartner = HsOfficePartnerEntity.builder() .partnerRole(partnerRole) + .partnerNumber(partnerNumber) .person(givenPerson) .contact(givenContact) .details(HsOfficePartnerDetailsEntity.builder() @@ -478,33 +488,9 @@ class HsOfficePartnerControllerAcceptanceTest extends ContextBasedTestWithCleanu } @AfterEach - @SuppressWarnings("unchecked") void cleanup() { - final var deleted = jpaAttempt.transacted(() -> { - context.define("superuser-alex@hostsharing.net", null); - final var tempPartnerUuids = (List)em.createNativeQuery(""" - select uuid from hs_office_partner p - where p.detailsuuid in ( - select d.uuid from hs_office_partner_details d - where d.registrationoffice like 'Temp %') - """) - .getResultList(); - tempPartnerUuids.forEach(partnerUuid -> { - final var tempPartner = partnerRepo.findByUuid(partnerUuid).orElseThrow(); - em.remove(tempPartner); - em.remove(tempPartner.getPartnerRole()); - }); - }).assertSuccessful().returnedValue(); - - final var remaining = jpaAttempt.transacted(() -> { - em.createNativeQuery(""" - select count(p) from hs_office_partner p - where p.detailsuuid in ( - select d.uuid from hs_office_partner_details d - where d.registrationoffice like 'Temp %') - """) - .getSingleResult(); - }).assertSuccessful().returnedValue(); - System.err.println("@AfterEach" + ": " + deleted + " records deleted, " + remaining + " remaining"); + cleanupAllNew(HsOfficePartnerEntity.class); + cleanupAllNew(HsOfficePartnerDetailsEntity.class); + cleanupAllNew(HsOfficeRelationshipEntity.class); } } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java index ebfc755b..743a0ce5 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/partner/HsOfficePartnerRepositoryIntegrationTest.java @@ -88,13 +88,14 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean // when final var result = attempt(em, () -> { - final var newPartner = toCleanup(HsOfficePartnerEntity.builder() + final var newPartner = HsOfficePartnerEntity.builder() + .partnerNumber(20031) .partnerRole(partnerRole) .person(givenPartnerPerson) .contact(givenContact) .details(HsOfficePartnerDetailsEntity.builder() .build()) - .build()); + .build(); return partnerRepo.save(newPartner); }); @@ -130,13 +131,13 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean .build(); relationshipRepo.save(newRelationship); - final var newPartner = toCleanup(HsOfficePartnerEntity.builder() - .partnerNumber(22222) + final var newPartner = HsOfficePartnerEntity.builder() + .partnerNumber(20032) .partnerRole(newRelationship) .person(givenPartnerPerson) .contact(givenContact) .details(HsOfficePartnerDetailsEntity.builder().build()) - .build()); + .build(); return partnerRepo.save(newPartner); }).assertSuccessful(); @@ -146,11 +147,11 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean "hs_office_relationship#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler.admin", "hs_office_relationship#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler.owner", "hs_office_relationship#HostsharingeG-with-PARTNER-ErbenBesslerMelBessler.tenant", - "hs_office_partner#22222:ErbenBesslerMelBessler-fourthcontact.admin", - "hs_office_partner#22222:ErbenBesslerMelBessler-fourthcontact.agent", - "hs_office_partner#22222:ErbenBesslerMelBessler-fourthcontact.owner", - "hs_office_partner#22222:ErbenBesslerMelBessler-fourthcontact.tenant", - "hs_office_partner#22222:ErbenBesslerMelBessler-fourthcontact.guest")); + "hs_office_partner#20032:ErbenBesslerMelBessler-fourthcontact.admin", + "hs_office_partner#20032:ErbenBesslerMelBessler-fourthcontact.agent", + "hs_office_partner#20032:ErbenBesslerMelBessler-fourthcontact.owner", + "hs_office_partner#20032:ErbenBesslerMelBessler-fourthcontact.tenant", + "hs_office_partner#20032:ErbenBesslerMelBessler-fourthcontact.guest")); assertThat(grantDisplaysOf(rawGrantRepo.findAll())) .map(s -> s.replace("ErbenBesslerMelBessler", "EBess")) .map(s -> s.replace("fourthcontact", "4th")) @@ -158,9 +159,11 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean .containsExactlyInAnyOrder(Array.fromFormatted( initialGrantNames, // relationship - TODO: check and cleanup - "{ grant role relationship#HostsharingeG-with-PARTNER-EBess.tenant to role partner#22222:EBess-4th.admin by system and assume }", - "{ grant role relationship#HostsharingeG-with-PARTNER-EBess.tenant to role partner#22222:EBess-4th.tenant by system and assume }", - "{ grant role partner#22222:EBess-4th.agent to role relationship#HostsharingeG-with-PARTNER-EBess.admin by system and assume }", + "{ grant role person#HostsharingeG.tenant to role person#EBess.admin by system and assume }", + "{ grant role person#EBess.tenant to role person#HostsharingeG.admin by system and assume }", + "{ grant role relationship#HostsharingeG-with-PARTNER-EBess.tenant to role partner#20032:EBess-4th.admin by system and assume }", + "{ grant role relationship#HostsharingeG-with-PARTNER-EBess.tenant to role partner#20032:EBess-4th.tenant by system and assume }", + "{ grant role partner#20032:EBess-4th.agent to role relationship#HostsharingeG-with-PARTNER-EBess.admin by system and assume }", "{ grant role relationship#HostsharingeG-with-PARTNER-EBess.owner to role global#global.admin by system and assume }", "{ grant role relationship#HostsharingeG-with-PARTNER-EBess.tenant to role contact#4th.admin by system and assume }", "{ grant role relationship#HostsharingeG-with-PARTNER-EBess.tenant to role person#EBess.admin by system and assume }", @@ -176,31 +179,31 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean "{ grant role person#HostsharingeG.tenant to role relationship#HostsharingeG-with-PARTNER-EBess.tenant by system and assume }", // owner - "{ grant perm * on partner#22222:EBess-4th to role partner#22222:EBess-4th.owner by system and assume }", - "{ grant perm * on partner_details#22222:EBess-4th-details to role partner#22222:EBess-4th.owner by system and assume }", - "{ grant role partner#22222:EBess-4th.owner to role global#global.admin by system and assume }", + "{ grant perm * on partner#20032:EBess-4th to role partner#20032:EBess-4th.owner by system and assume }", + "{ grant perm * on partner_details#20032:EBess-4th-details to role partner#20032:EBess-4th.owner by system and assume }", + "{ grant role partner#20032:EBess-4th.owner to role global#global.admin by system and assume }", // admin - "{ grant perm edit on partner#22222:EBess-4th to role partner#22222:EBess-4th.admin by system and assume }", - "{ grant perm edit on partner_details#22222:EBess-4th-details to role partner#22222:EBess-4th.admin by system and assume }", - "{ grant role partner#22222:EBess-4th.admin to role partner#22222:EBess-4th.owner by system and assume }", - "{ grant role person#EBess.tenant to role partner#22222:EBess-4th.admin by system and assume }", - "{ grant role contact#4th.tenant to role partner#22222:EBess-4th.admin by system and assume }", + "{ grant perm edit on partner#20032:EBess-4th to role partner#20032:EBess-4th.admin by system and assume }", + "{ grant perm edit on partner_details#20032:EBess-4th-details to role partner#20032:EBess-4th.admin by system and assume }", + "{ grant role partner#20032:EBess-4th.admin to role partner#20032:EBess-4th.owner by system and assume }", + "{ grant role person#EBess.tenant to role partner#20032:EBess-4th.admin by system and assume }", + "{ grant role contact#4th.tenant to role partner#20032:EBess-4th.admin by system and assume }", // agent - "{ grant perm view on partner_details#22222:EBess-4th-details to role partner#22222:EBess-4th.agent by system and assume }", - "{ grant role partner#22222:EBess-4th.agent to role partner#22222:EBess-4th.admin by system and assume }", - "{ grant role partner#22222:EBess-4th.agent to role person#EBess.admin by system and assume }", - "{ grant role partner#22222:EBess-4th.agent to role contact#4th.admin by system and assume }", + "{ grant perm view on partner_details#20032:EBess-4th-details to role partner#20032:EBess-4th.agent by system and assume }", + "{ grant role partner#20032:EBess-4th.agent to role partner#20032:EBess-4th.admin by system and assume }", + "{ grant role partner#20032:EBess-4th.agent to role person#EBess.admin by system and assume }", + "{ grant role partner#20032:EBess-4th.agent to role contact#4th.admin by system and assume }", // tenant - "{ grant role partner#22222:EBess-4th.tenant to role partner#22222:EBess-4th.agent by system and assume }", - "{ grant role person#EBess.guest to role partner#22222:EBess-4th.tenant by system and assume }", - "{ grant role contact#4th.guest to role partner#22222:EBess-4th.tenant by system and assume }", + "{ grant role partner#20032:EBess-4th.tenant to role partner#20032:EBess-4th.agent by system and assume }", + "{ grant role person#EBess.guest to role partner#20032:EBess-4th.tenant by system and assume }", + "{ grant role contact#4th.guest to role partner#20032:EBess-4th.tenant by system and assume }", // guest - "{ grant perm view on partner#22222:EBess-4th to role partner#22222:EBess-4th.guest by system and assume }", - "{ grant role partner#22222:EBess-4th.guest to role partner#22222:EBess-4th.tenant by system and assume }", + "{ grant perm view on partner#20032:EBess-4th to role partner#20032:EBess-4th.guest by system and assume }", + "{ grant role partner#20032:EBess-4th.guest to role partner#20032:EBess-4th.tenant by system and assume }", null)); } @@ -285,10 +288,10 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean public void hostsharingAdmin_withoutAssumedRole_canUpdateArbitraryPartner() { // given context("superuser-alex@hostsharing.net"); - final var givenPartner = givenSomeTemporaryPartnerBessler(22222, "Erben Bessler", "fifth contact"); + final var givenPartner = givenSomeTemporaryPartnerBessler(20032, "Erben Bessler", "fifth contact"); assertThatPartnerIsVisibleForUserWithRole( givenPartner, - "hs_office_partner#22222:ErbenBesslerMelBessler-fifthcontact.admin"); + "hs_office_partner#20032:ErbenBesslerMelBessler-fifthcontact.admin"); assertThatPartnerActuallyInDatabase(givenPartner); context("superuser-alex@hostsharing.net"); final var givenNewPerson = personRepo.findPersonByOptionalNameLike("Third OHG").get(0); @@ -299,7 +302,7 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean context("superuser-alex@hostsharing.net"); givenPartner.setContact(givenNewContact); givenPartner.setPerson(givenNewPerson); - return toCleanup(partnerRepo.save(givenPartner)); + return partnerRepo.save(givenPartner); }); // then @@ -321,20 +324,20 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean public void partnerAgent_canNotUpdateRelatedPartner() { // given context("superuser-alex@hostsharing.net"); - final var givenPartner = givenSomeTemporaryPartnerBessler(22222, "Erben Bessler", "ninth"); + final var givenPartner = givenSomeTemporaryPartnerBessler(20032, "Erben Bessler", "ninth"); final var newPartnerRole = em.createNativeQuery( "select uuid from hs_office_relationship where uuid=:partnerRoleUuid") .setParameter("partnerRoleUuid", givenPartner.getPartnerRole().getUuid()) .getSingleResult(); assertThatPartnerIsVisibleForUserWithRole( givenPartner, - "hs_office_partner#22222:ErbenBesslerMelBessler-ninthcontact.agent"); + "hs_office_partner#20032:ErbenBesslerMelBessler-ninthcontact.agent"); assertThatPartnerActuallyInDatabase(givenPartner); // when final var result = jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net", - "hs_office_partner#22222:ErbenBesslerMelBessler-ninthcontact.agent"); + "hs_office_partner#20032:ErbenBesslerMelBessler-ninthcontact.agent"); givenPartner.getDetails().setBirthName("new birthname"); return partnerRepo.save(givenPartner); }); @@ -376,7 +379,7 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean public void globalAdmin_withoutAssumedRole_canDeleteAnyPartner() { // given context("superuser-alex@hostsharing.net", null); - final var givenPartner = givenSomeTemporaryPartnerBessler(22222, "Erben Bessler", "tenth"); + final var givenPartner = givenSomeTemporaryPartnerBessler(20032, "Erben Bessler", "tenth"); // when final var result = jpaAttempt.transacted(() -> { @@ -396,7 +399,7 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean public void nonGlobalAdmin_canNotDeleteTheirRelatedPartner() { // given context("superuser-alex@hostsharing.net", null); - final var givenPartner = givenSomeTemporaryPartnerBessler(22222, "Erben Bessler", "eleventh"); + final var givenPartner = givenSomeTemporaryPartnerBessler(20032, "Erben Bessler", "eleventh"); // when final var result = jpaAttempt.transacted(() -> { @@ -422,18 +425,20 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean context("superuser-alex@hostsharing.net"); final var initialRoleNames = Array.from(roleNamesOf(rawRoleRepo.findAll())); final var initialGrantNames = Array.from(grantDisplaysOf(rawGrantRepo.findAll())); - final var givenPartner = givenSomeTemporaryPartnerBessler(22222, "Erben Bessler", "twelfth"); + final var givenPartner = givenSomeTemporaryPartnerBessler(20032, "Erben Bessler", "twelfth"); // when final var result = jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net"); - return relationshipRepo.deleteByUuid(givenPartner.getPartnerRole().getUuid()); -// return partnerRepo.deleteByUuid(givenPartner.getUuid()); + // TODO: should deleting a partner automatically delete the PARTNER relationship? (same for debitor) + // TODO: why did the test cleanup check does not notice this, if missing? + return partnerRepo.deleteByUuid(givenPartner.getUuid()) + + relationshipRepo.deleteByUuid(givenPartner.getPartnerRole().getUuid()); }); // then result.assertSuccessful(); - assertThat(result.returnedValue()).isEqualTo(1); + assertThat(result.returnedValue()).isEqualTo(2); // partner+relationship assertThat(roleNamesOf(rawRoleRepo.findAll())).containsExactlyInAnyOrder(initialRoleNames); assertThat(grantDisplaysOf(rawGrantRepo.findAll())).containsExactlyInAnyOrder(initialGrantNames); } @@ -457,16 +462,6 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean "[creating partner test-data Seconde.K.-secondcontact, hs_office_partner, INSERT]"); } - @AfterEach - void cleanup() { - context("superuser-alex@hostsharing.net", null); - tempPartners.forEach(tempPartner -> { - System.out.println("DELETING temporary partner: " + tempPartner.toString()); - relationshipRepo.deleteByUuid(tempPartner.getPartnerRole().getUuid()); - partnerRepo.deleteByUuid(tempPartner.getUuid()); - }); - } - private HsOfficePartnerEntity givenSomeTemporaryPartnerBessler( final Integer partnerNumber, final String person, final String contact) { return jpaAttempt.transacted(() -> { @@ -492,17 +487,10 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean .details(HsOfficePartnerDetailsEntity.builder().build()) .build(); - toCleanup(newPartner); - return partnerRepo.save(newPartner); }).assertSuccessful().returnedValue(); } - private HsOfficePartnerEntity toCleanup(final HsOfficePartnerEntity tempPartner) { - tempPartners.add(tempPartner); - return tempPartner; - } - void exactlyThesePartnersAreReturned(final List actualResult, final String... partnerNames) { assertThat(actualResult) .extracting(partnerEntity -> partnerEntity.toString()) @@ -514,4 +502,11 @@ class HsOfficePartnerRepositoryIntegrationTest extends ContextBasedTestWithClean .extracting(partnerEntity -> partnerEntity.toString()) .contains(partnerNames); } + + @AfterEach + void cleanup() { + cleanupAllNew(HsOfficePartnerEntity.class); + cleanupAllNew(HsOfficePartnerDetailsEntity.class); + cleanupAllNew(HsOfficeRelationshipEntity.class); + } } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonControllerAcceptanceTest.java index fb713951..78b9c290 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonControllerAcceptanceTest.java @@ -8,7 +8,6 @@ import net.hostsharing.hsadminng.hs.office.test.ContextBasedTestWithCleanup; import net.hostsharing.test.Accepts; import net.hostsharing.test.JpaAttempt; import org.apache.commons.lang3.RandomStringUtils; -import org.json.JSONException; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java index 5e5d97e2..b1db3275 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/person/HsOfficePersonRepositoryIntegrationTest.java @@ -7,7 +7,6 @@ import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; import net.hostsharing.test.Array; import net.hostsharing.test.JpaAttempt; import org.apache.commons.lang3.RandomStringUtils; -import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -61,8 +60,8 @@ class HsOfficePersonRepositoryIntegrationTest extends ContextBasedTestWithCleanu // when - final var result = attempt(em, () -> personRepo.save( - hsOfficePerson("a new person"))); + final var result = attempt(em, () -> toCleanup(personRepo.save( + hsOfficePerson("a new person")))); // then result.assertSuccessful(); @@ -78,8 +77,8 @@ class HsOfficePersonRepositoryIntegrationTest extends ContextBasedTestWithCleanu final var count = personRepo.count(); // when - final var result = attempt(em, () -> personRepo.save( - hsOfficePerson("another new person"))); + final var result = attempt(em, () -> toCleanup(personRepo.save( + hsOfficePerson("another new person")))); // then result.assertSuccessful(); @@ -97,8 +96,8 @@ class HsOfficePersonRepositoryIntegrationTest extends ContextBasedTestWithCleanu final var initialGrantNames = grantDisplaysOf(rawGrantRepo.findAll()); // when - attempt(em, () -> personRepo.save( - hsOfficePerson("another new person")) + attempt(em, () -> toCleanup(personRepo.save( + hsOfficePerson("another new person"))) ).assumeSuccessful(); // then @@ -276,22 +275,12 @@ class HsOfficePersonRepositoryIntegrationTest extends ContextBasedTestWithCleanu "[creating person test-data Second e.K., Smith, Peter, hs_office_person, INSERT]"); } - @AfterEach - void cleanup() { - context("superuser-alex@hostsharing.net", null); - final var result = personRepo.findPersonByOptionalNameLike("some temporary person"); - result.forEach(tempPerson -> { - System.out.println("DELETING temporary person: " + tempPerson.toShortString()); - personRepo.deleteByUuid(tempPerson.getUuid()); - }); - } - private HsOfficePersonEntity givenSomeTemporaryPerson( final String createdByUser, Supplier entitySupplier) { return jpaAttempt.transacted(() -> { context(createdByUser); - return personRepo.save(entitySupplier.get()); + return toCleanup(personRepo.save(entitySupplier.get())); }).assumeSuccessful().returnedValue(); } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/relationship/HsOfficeRelationshipControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/relationship/HsOfficeRelationshipControllerAcceptanceTest.java index b24c6877..8f9e9147 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/relationship/HsOfficeRelationshipControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/relationship/HsOfficeRelationshipControllerAcceptanceTest.java @@ -464,16 +464,15 @@ class HsOfficeRelationshipControllerAcceptanceTest extends ContextBasedTestWithC final var givenHolderPerson = personRepo.findPersonByOptionalNameLike("Winkler").get(0); final var givenContact = contactRepo.findContactByOptionalLabelLike("seventh contact").get(0); final var newRelationship = HsOfficeRelationshipEntity.builder() - .uuid(UUID.randomUUID()) .relType(HsOfficeRelationshipType.REPRESENTATIVE) .relAnchor(givenAnchorPerson) .relHolder(givenHolderPerson) .contact(givenContact) .build(); - toCleanup(HsOfficeRelationshipEntity.class, newRelationship.getUuid()); + assertThat(toCleanup(relationshipRepo.save(newRelationship))).isEqualTo(newRelationship); - return relationshipRepo.save(newRelationship); + return newRelationship; }).assertSuccessful().returnedValue(); } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateControllerAcceptanceTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateControllerAcceptanceTest.java index a914ba52..67a731de 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateControllerAcceptanceTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateControllerAcceptanceTest.java @@ -4,7 +4,6 @@ import com.vladmihalcea.hibernate.type.range.Range; import io.restassured.RestAssured; import io.restassured.http.ContentType; import net.hostsharing.hsadminng.HsadminNgApplication; -import net.hostsharing.hsadminng.context.Context; import net.hostsharing.hsadminng.hs.office.bankaccount.HsOfficeBankAccountRepository; import net.hostsharing.hsadminng.hs.office.debitor.HsOfficeDebitorRepository; import net.hostsharing.hsadminng.hs.office.test.ContextBasedTestWithCleanup; @@ -118,7 +117,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl context.define("superuser-alex@hostsharing.net"); final var givenDebitor = debitorRepo.findDebitorByOptionalNameLike("Third").get(0); - final var givenBankAccount = bankAccountRepo.findByIbanOrderByIban("DE02200505501015871393").get(0); + final var givenBankAccount = bankAccountRepo.findByIbanOrderByIbanAsc("DE02200505501015871393").get(0); final var location = RestAssured // @formatter:off .given() @@ -160,7 +159,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl context.define("superuser-alex@hostsharing.net"); final var givenDebitor = debitorRepo.findDebitorByOptionalNameLike("Third").get(0); - final var givenBankAccount = bankAccountRepo.findByIbanOrderByIban("DE02200505501015871393").get(0); + final var givenBankAccount = bankAccountRepo.findByIbanOrderByIbanAsc("DE02200505501015871393").get(0); final var location = RestAssured // @formatter:off .given() @@ -215,7 +214,7 @@ class HsOfficeSepaMandateControllerAcceptanceTest extends ContextBasedTestWithCl context.define("superuser-alex@hostsharing.net"); final var givenDebitorUuid = UUID.fromString("00000000-0000-0000-0000-000000000000"); - final var givenBankAccount = bankAccountRepo.findByIbanOrderByIban("DE02200505501015871393").get(0); + final var givenBankAccount = bankAccountRepo.findByIbanOrderByIbanAsc("DE02200505501015871393").get(0); final var location = RestAssured // @formatter:off .given() diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java b/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java index 5c87dedd..9cdc31e7 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/sepamandate/HsOfficeSepaMandateRepositoryIntegrationTest.java @@ -9,8 +9,6 @@ import net.hostsharing.hsadminng.rbac.rbacgrant.RawRbacGrantRepository; import net.hostsharing.hsadminng.rbac.rbacrole.RawRbacRoleRepository; import net.hostsharing.test.Array; import net.hostsharing.test.JpaAttempt; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -18,7 +16,6 @@ import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Import; import org.springframework.orm.jpa.JpaSystemException; -import org.springframework.transaction.annotation.Transactional; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; @@ -81,7 +78,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC .validity(Range.closedOpen( LocalDate.parse("2020-01-01"), LocalDate.parse("2023-01-01"))) .build(); - return sepaMandateRepo.save(newSepaMandate); + return toCleanup(sepaMandateRepo.save(newSepaMandate)); }); // then @@ -114,7 +111,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC .validity(Range.closedOpen( LocalDate.parse("2020-01-01"), LocalDate.parse("2023-01-01"))) .build(); - return sepaMandateRepo.save(newSepaMandate); + return toCleanup(sepaMandateRepo.save(newSepaMandate)); }); // then @@ -251,7 +248,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC givenSepaMandate.setAgreement(LocalDate.parse("2019-05-13")); givenSepaMandate.setValidity(Range.closedOpen( LocalDate.parse("2019-05-17"), LocalDate.parse("2023-01-01"))); - return sepaMandateRepo.save(givenSepaMandate); + return toCleanup(sepaMandateRepo.save(givenSepaMandate)); }); // then @@ -279,7 +276,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC context("superuser-alex@hostsharing.net", "hs_office_bankaccount#AnitaBessler.admin"); givenSepaMandate.setValidity(Range.closedOpen( givenSepaMandate.getValidity().lower(), newValidityEnd)); - return sepaMandateRepo.save(givenSepaMandate); + return toCleanup(sepaMandateRepo.save(givenSepaMandate)); }); // then @@ -404,14 +401,6 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC "[creating SEPA-mandate test-data Seconde.K., hs_office_sepamandate, INSERT]"); } - @BeforeEach - @AfterEach - @Transactional - void cleanup() { - context("superuser-alex@hostsharing.net", null); - em.createQuery("DELETE FROM HsOfficeSepaMandateEntity WHERE reference like 'temp ref%'").executeUpdate(); - } - private HsOfficeSepaMandateEntity givenSomeTemporarySepaMandateBessler(final String bankAccountHolder) { return jpaAttempt.transacted(() -> { context("superuser-alex@hostsharing.net"); @@ -426,7 +415,7 @@ class HsOfficeSepaMandateRepositoryIntegrationTest extends ContextBasedTestWithC LocalDate.parse("2020-01-01"), LocalDate.parse("2023-01-01"))) .build(); - return sepaMandateRepo.save(newSepaMandate); + return toCleanup(sepaMandateRepo.save(newSepaMandate)); }).assertSuccessful().returnedValue(); } diff --git a/src/test/java/net/hostsharing/hsadminng/hs/office/test/ContextBasedTestWithCleanup.java b/src/test/java/net/hostsharing/hsadminng/hs/office/test/ContextBasedTestWithCleanup.java index 96b53200..7dd488e4 100644 --- a/src/test/java/net/hostsharing/hsadminng/hs/office/test/ContextBasedTestWithCleanup.java +++ b/src/test/java/net/hostsharing/hsadminng/hs/office/test/ContextBasedTestWithCleanup.java @@ -2,6 +2,8 @@ package net.hostsharing.hsadminng.hs.office.test; import net.hostsharing.hsadminng.context.ContextBasedTest; import net.hostsharing.hsadminng.hs.office.migration.HasUuid; +import net.hostsharing.hsadminng.rbac.rbacgrant.RbacGrantEntity; +import net.hostsharing.hsadminng.rbac.rbacgrant.RbacGrantRepository; import net.hostsharing.hsadminng.rbac.rbacrole.RbacRoleEntity; import net.hostsharing.hsadminng.rbac.rbacrole.RbacRoleRepository; import net.hostsharing.test.JpaAttempt; @@ -9,83 +11,177 @@ import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.repository.Repository; -import jakarta.persistence.EntityManager; -import jakarta.persistence.PersistenceContext; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.UUID; +import jakarta.persistence.*; +import java.util.*; import static java.util.stream.Collectors.toSet; -import static org.apache.commons.collections4.SetUtils.*; +import static org.apache.commons.collections4.SetUtils.difference; +import static org.apache.commons.collections4.SetUtils.emptySet; import static org.assertj.core.api.Assertions.assertThat; public abstract class ContextBasedTestWithCleanup extends ContextBasedTest { - private static final boolean SLOW_BUT_COMPARING_ROLE_NAMES = true; + private static final boolean SLOW_DETAILED_DEBUG_MODE = true; @PersistenceContext protected EntityManager em; + @Autowired + RbacGrantRepository rbacGrantRepo; + @Autowired RbacRoleRepository rbacRoleRepo; + @Autowired + RbacObjectRepository rbacObjectRepo; + @Autowired JpaAttempt jpaAttempt; - private Map> entitiesToCleanup = new HashMap<>(); + private TreeMap> entitiesToCleanup = new TreeMap<>(); - private long objectCountBefore; + private static Long objectCountBefore = null; + private Set rbacObjectsBefore; private Set rbacRolesBefore; + private Set rbacGrantsBefore; public UUID toCleanup(final Class entityClass, final UUID uuidToCleanup) { + System.out.println("toCleanup(" + entityClass.getSimpleName() + ", " + uuidToCleanup); entitiesToCleanup.put(uuidToCleanup, entityClass); return uuidToCleanup; } + public E toCleanup(final E entity) { + System.out.println("toCleanup(" + entity.getClass() + ", " + entity.getUuid()); + entitiesToCleanup.put(entity.getUuid(), entity.getClass()); + return entity; + } + + + protected void cleanupAllNew(final Class entityClass) { + final var tableName = entityClass.getAnnotation(Table.class).name(); + final var rvTableName = tableName.endsWith("_rv") + ? tableName.substring(0, tableName.length()-"_rv".length()) + : tableName; + + allRbacObjects().stream() + .filter(o -> o.startsWith(rvTableName+":")) + .filter(o -> !rbacObjectsBefore.contains(o)) + .forEach(o -> + jpaAttempt.transacted(() -> { + context.define("superuser-alex@hostsharing.net", null); + final UUID uuid = UUID.fromString(o.split(":")[1]); + System.out.println("DELETING new " + entityClass.getSimpleName() + "#" + uuid); + em.remove(em.getReference(entityClass, uuid)); + })); //.assertSuccessful()); + } + @BeforeEach - //@Transactional -- TODO: check why this does not work but jpaAttempt.transacted does work - void retrieveExistingRoles() { + //@Transactional -- TODO: check why this does not work but jpaAttempt.transacted does work + void retrieveExistingData() { jpaAttempt.transacted(() -> { context.define("superuser-alex@hostsharing.net", null); - objectCountBefore = rbacRoleRepo.count(); + + if ( objectCountBefore != null ) { + assertThat(objectCountBefore = rbacObjectRepo.count()) + .as("not all business objects got cleaned up by the previous test") + .isEqualTo(objectCountBefore); + } else { + objectCountBefore = rbacObjectRepo.count(); + } + + rbacObjectsBefore = allRbacObjects(); rbacRolesBefore = allRbacRoles(); + rbacGrantsBefore = allRbacGrants(); }); + + System.out.println("TOTAL OBJECT COUNT (before): " + objectCountBefore); } @AfterEach void cleanup() { - jpaAttempt.transacted(() -> { - entitiesToCleanup.forEach((uuid, entityClass) -> { + entitiesToCleanup.forEach((uuid, entityClass) -> { + final var caughtException = jpaAttempt.transacted(() -> { context.define("superuser-alex@hostsharing.net", null); - System.out.println("DELETING temporary " + uuid + ": " + uuid); + System.out.println("DELETING temporary " + entityClass.getSimpleName() + "#" + uuid); em.remove(em.getReference(entityClass, uuid)); - }); - }); //.assertSuccessful(); + }).caughtException(); + if (caughtException != null) { + System.out.println( + "FAILED DELETING temporary " + entityClass.getSimpleName() + "#" + uuid + ": " + caughtException); + } + }); jpaAttempt.transacted(() -> { context.define("superuser-alex@hostsharing.net", null); - if ( rbacRoleRepo.count() != objectCountBefore) { - final var rbacRolesAfter = allRbacRoles(); - final var missingRbacRoles = difference(rbacRolesBefore, rbacRolesAfter); - final var spuriousRbacRoles = difference(rbacRolesAfter, rbacRolesBefore); - assertThat(spuriousRbacRoles).isEqualTo(missingRbacRoles); // only true if both are empty - - // if the diff does not appear in IntelliJ IDEA, go to "Help/Edit Custom VM Options" and increase the threshold: - // -Didea.junit.message.length.threshold=1000000 - assertThat(rbacRoleRepo.count()).as("not all RBAC roles got cleaned up (most likely because not all business objects got cleaned up)").isEqualTo(objectCountBefore); + if (SLOW_DETAILED_DEBUG_MODE) { + assertEqual(rbacObjectsBefore, allRbacObjects()); + assertEqual(rbacRolesBefore, allRbacRoles()); + assertEqual(rbacGrantsBefore, allRbacGrants()); } - }).assertSuccessful(); + assertThat(rbacObjectRepo.count()).as("not all business objects got cleaned up (by current test)") + .isEqualTo(objectCountBefore); + }); //.assertSuccessful(); + } + + private void assertEqual(final Set before, final Set after) { + assertThat(difference(before, after)).as("missing entities (deleted initial test data)").isEmpty(); + assertThat(difference(after, before)).as("spurious entities (temporary test data not cleaned up)").isEmpty(); + } + + @NotNull + private Set allRbacGrants() { + if (SLOW_DETAILED_DEBUG_MODE) { + return rbacGrantRepo.findAll().stream() + .map(RbacGrantEntity::toDisplay) + .collect(toSet()); + } + return emptySet(); } @NotNull private Set allRbacRoles() { - if (SLOW_BUT_COMPARING_ROLE_NAMES) { + if (SLOW_DETAILED_DEBUG_MODE) { return rbacRoleRepo.findAll().stream() - .map(RbacRoleEntity::getRoleName).sorted() + .map(RbacRoleEntity::getRoleName) + .collect(toSet()); + } + return emptySet(); + } + + @NotNull + private Set allRbacObjects() { + if (SLOW_DETAILED_DEBUG_MODE) { + return rbacObjectRepo.findAll().stream() + .map(Object::toString) .collect(toSet()); } return emptySet(); } } + +interface RbacObjectRepository extends Repository { + + long count(); + + List findAll(); +} + +@Entity +@Table(name = "rbacobject") +class RbacObjectEntity { + + @Id + @GeneratedValue + private UUID uuid; + + @Column(name = "objecttable") + private String objectTable; + + @Override + public String toString() { + return objectTable + ":" + uuid; + } +}