This commit is contained in:
Michael Hoennig 2024-10-17 16:06:58 +02:00
parent 2b21c742f0
commit 1a52895cda
10 changed files with 310 additions and 196 deletions

View File

@ -1,51 +0,0 @@
package net.hostsharing.hsadminng.hs.office.usecases;
import io.restassured.http.ContentType;
import org.springframework.http.HttpStatus;
class HsOfficeCreatePartnerUseCase extends UseCase {
public HsOfficeCreatePartnerUseCase(final UseCaseTest testSuite) {
super(testSuite);
}
@Override
HttpResponse run() {
httpPost("/api/hs/office/persons", usingJsonBody("""
{
"personType": "LEGAL_PERSON",
"tradeName": "Test AG"
}
"""))
.expecting(HttpStatus.CREATED).expecting(ContentType.JSON)
.keepingAs("person:Test AG.uuid");
httpPost("/api/hs/office/contacts", usingJsonBody("""
{
"caption": "Test AG - Bord of Directors",
"emailAddresses": {
"main": "bord-of-directors@test-ag.example.org"
}
}
"""))
.expecting(HttpStatus.CREATED).expecting(ContentType.JSON)
.keepingAs("contact:Test AG - Bord of Directors.uuid");
return httpPost("/api/hs/office/partners", usingJsonBody("""
{
"partnerNumber": "30003",
"partnerRel": {
"anchorUuid": "${person:Hostsharing eG.uuid}",
"holderUuid": "${person:Test AG.uuid}",
"contactUuid": "${contact:Test AG - Bord of Directors.uuid}"
},
"details": {
"registrationOffice": "Registergericht Hamburg",
"registrationNumber": "1234567"
}
}
"""))
.expecting(HttpStatus.CREATED).expecting(ContentType.JSON);
}
}

View File

@ -1,59 +0,0 @@
package net.hostsharing.hsadminng.hs.office.usecases;
import static io.restassured.http.ContentType.JSON;
import static org.springframework.http.HttpStatus.CREATED;
class HsOfficeDebitorUseCase extends UseCase {
public HsOfficeDebitorUseCase(final UseCaseTest testSuite) {
super(testSuite);
requires("person:Test AG.uuid", () -> new HsOfficeCreatePartnerUseCase(testSuite));
}
@Override
HttpResponse run() {
httpPost("/api/hs/office/bankaccounts", usingJsonBody("""
{
"holder": "Test AG - refund bank account",
"iban": "DE88100900001234567892",
"bic": "BEVODEBB"
}
"""))
.expecting(CREATED).expecting(JSON)
.keepingAs("bankaccount:Test AG - refund bank account.uuid");
httpPost("/api/hs/office/contacts", usingJsonBody("""
{
"caption": "Test AG - billing department",
"emailAddresses": {
"main": "billing@test-ag.example.org"
}
}
"""))
.expecting(CREATED).expecting(JSON)
.keepingAs("contact:Test AG - billing department.uuid");
httpPost("/api/hs/office/debitors", usingJsonBody("""
{
"debitorRel": {
"type": "DEBITOR", // FIXME: should be defaulted to DEBITOR
"anchorUuid": "${person:Test AG.uuid}",
"holderUuid": "${person:Test AG.uuid}",
"contactUuid": "${contact:Test AG - billing department.uuid}"
},
"debitorNumberSuffix": "00",
"billable": "true",
"vatId": "VAT123456",
"vatCountryCode": "DE",
"vatBusiness": true,
"vatReverseCharge": "false",
"refundBankAccountUuid": "${bankaccount:Test AG - refund bank account.uuid}",
"defaultPrefix": "tst"
}
"""))
.expecting(CREATED).expecting(JSON)
.keepingAs("debitor:Test AG - Hauptdebitor.uuid");
return null;
}
}

View File

@ -1,19 +0,0 @@
package net.hostsharing.hsadminng.hs.office.usecases;
import org.springframework.http.HttpStatus;
class HsOfficeDeletePartnerUseCase extends UseCase {
public HsOfficeDeletePartnerUseCase(final UseCaseTest testSuite) {
super(testSuite);
requires("partner:Test AG for deletetion:uuid", () -> new HsOfficeCreatePartnerUseCase(testSuite));
}
@Override
HttpResponse run() {
httpDelete("/api/hs/office/partners/" + uuid("partner:Test AG.uuid"))
.expecting(HttpStatus.NO_CONTENT);
return null;
}
}

View File

@ -1,13 +1,17 @@
package net.hostsharing.hsadminng.hs.office.usecases;
import net.hostsharing.hsadminng.HsadminNgApplication;
import net.hostsharing.hsadminng.hs.office.usecases.debitor.CreateSelfDebitorForPartner;
import net.hostsharing.hsadminng.hs.office.usecases.membership.CreateMembership;
import net.hostsharing.hsadminng.hs.office.usecases.partner.CreatePartner;
import net.hostsharing.hsadminng.hs.office.usecases.partner.DeletePartner;
import net.hostsharing.hsadminng.rbac.test.JpaAttempt;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest(
@ -16,31 +20,41 @@ import org.springframework.boot.test.context.SpringBootTest;
)
@Tag("useCaseTest")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ExtendWith(OrderedDependedTestsExtension.class)
class HsOfficeUseCasesTest extends UseCaseTest {
@Test
@Order(1010)
void shouldCreatePartner() {
new HsOfficeCreatePartnerUseCase(this).run()
.keepingAs("partner:Test AG.uuid");
}
@Test
@Order(1011)
void shouldDeletePartner() {
new HsOfficeDeletePartnerUseCase(this).run();
keep("partner:Test AG.uuid", () ->
new CreatePartner(this)
.given("partnerNumber", 30001)
.given("personType", "LEGAL_PERSON")
.given("tradeName", "Test AG")
.given("contactCaption", "Test AG - Bord of Directors")
.given("emailAddress", "bord-of-directors@test-ag.example.org")
.doRun()
.keepingAs()
);
}
@Test
@Order(1020)
void shouldCreateSelfDebitorForPartner() {
new HsOfficeDebitorUseCase(this).run();
void shouldDeletePartner() {
new DeletePartner(this)
.given("partnerNumber", 31020)
.doRun();
}
@Test
@Order(1030)
@Order(2000)
void shouldCreateSelfDebitorForPartner() {
new CreateSelfDebitorForPartner(this).doRun();
}
@Test
@Order(3000)
@Disabled
void shouldCreateMembershipForPartner() {
new HsOfficeMembershipUseCase(this).run();
new CreateMembership(this).doRun();
}
}

View File

@ -1,11 +1,17 @@
package net.hostsharing.hsadminng.hs.office.usecases;
import com.tngtech.archunit.thirdparty.com.google.common.collect.Streams;
import io.restassured.RestAssured;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import io.restassured.response.ValidatableResponse;
import lombok.SneakyThrows;
import org.apache.commons.collections4.map.LinkedMap;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Map;
import java.util.UUID;
@ -13,49 +19,83 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import static java.nio.file.StandardOpenOption.APPEND;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.TRUNCATE_EXISTING;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assumptions.assumeThat;
import static org.hamcrest.Matchers.startsWith;
public abstract class UseCase {
public abstract class UseCase<T extends UseCase<?>> {
private final UseCaseTest testSuite;
private final Map<String, Supplier<UseCase<?>>> requirements = new LinkedMap<>();
private String nextTitle;
public UseCase(final UseCaseTest testSuite) {
this.testSuite = testSuite;
log();
log("## Testcase " + this.getClass().getSimpleName().replaceAll("([a-z])([A-Z]+)", "$1 $2"));
log("");
}
void requires(final String alias, final Supplier<UseCase> useCaseSupplier) {
public final void requires(final String alias, final Supplier<UseCase<?>> useCaseSupplier) {
if ( !UseCaseTest.aliases.containsKey(alias) ) {
useCaseSupplier.get().run().keepingAs(alias);
requirements.put(alias, useCaseSupplier);
}
}
abstract HttpResponse run();
public void requires(final String alias) {
assumeThat(UseCaseTest.aliases.containsKey(alias))
.as("skipping because alias '" + alias + "' not found, maybe the other test failed?")
.isTrue();
log("depends on ["+alias+"]("+UseCaseTest.aliases.get(alias).useCase().getSimpleName()+".md)");
}
JsonTemplate usingJsonBody(final String jsonTemplate) {
public final HttpResponse doRun() {
requirements.forEach((alias, supplier) -> supplier.get().run().keepingAs(alias));
return run();
}
protected abstract HttpResponse run();
public final UseCase<T> given(final String propName, final Object propValue) {
UseCaseTest.properties.put(propName, propValue);
return this;
}
public final JsonTemplate usingJsonBody(final String jsonTemplate) {
return new JsonTemplate(jsonTemplate);
}
HttpResponse httpPost(final String uriPath, final JsonTemplate bodyJsonTemplate) {
public final void keep(final String alias, final Supplier<HttpResponse> http) {
this.nextTitle = alias; // FIXME: ugly
http.get().keepingAs(alias);
this.nextTitle = null;
}
public final HttpResponse httpPost(final String uriPath, final JsonTemplate bodyJsonTemplate) {
final var body = bodyJsonTemplate.resolvePlaceholders();
final var uri = "http://localhost" + uriPath;
final var response = RestAssured.given()
.header("current-subject", UseCaseTest.RUN_AS_USER)
.contentType(ContentType.JSON)
.body(bodyJsonTemplate.with(UseCaseTest.aliases))
.body(body)
.port(testSuite.port)
.when().post("http://localhost" + uriPath);
return new HttpResponse(response);
.when().post(uri);
return new HttpResponse(HttpMethod.POST, uriPath, body, response);
}
HttpResponse httpDelete(final String uriPath) {
public final HttpResponse httpDelete(final String uriPath) {
final var response = RestAssured.given()
.header("current-subject", UseCaseTest.RUN_AS_USER)
.port(testSuite.port)
.when().delete("http://localhost" + uriPath);
return new HttpResponse(response);
return new HttpResponse(HttpMethod.DELETE, uriPath, null, response);
}
UUID uuid(final String alias) {
return testSuite.aliases.get(alias);
public final UUID uuid(final String alias) {
return UseCaseTest.aliases.get(alias).uuid();
}
static class JsonTemplate {
@ -66,14 +106,26 @@ public abstract class UseCase {
this.template = jsonTemplate;
}
String with(final Map<String, UUID> aliases) {
String resolvePlaceholders() {
var partiallyResolved = new AtomicReference<>(template);
aliases.forEach((k, v) ->
partiallyResolved.set(partiallyResolved.get().replace("${" + k + "}", v.toString())));
Streams.concat(
UseCaseTest.aliases.entrySet().stream().map(e -> Map.entry(e.getKey(), e.getValue().uuid())),
UseCaseTest.properties.entrySet().stream()
).forEach(entry -> partiallyResolved.set(
partiallyResolved.get().replace("${" + entry.getKey() + "}", optionallyQuoted(entry.getValue())))
);
verifyAllPlaceholdersResolved(partiallyResolved.get());
return partiallyResolved.get();
}
private String optionallyQuoted(final Object value) {
return switch (value) {
case Boolean bool -> bool.toString();
case Number number -> number.toString();
default -> "\"" + value + "\"";
};
}
private void verifyAllPlaceholdersResolved(final String remainingTemplate) {
final var pattern = Pattern.compile("\\$\\{[^}]+\\}");
final var matcher = pattern.matcher(remainingTemplate);
@ -87,31 +139,65 @@ public abstract class UseCase {
}
}
class HttpResponse {
public class HttpResponse {
private final ValidatableResponse response;
private final HttpStatus status;
private UUID locationUuid;
public HttpResponse(final Response response) {
this.response = response.then().log().all().assertThat();
public HttpResponse(
final HttpMethod httpMethod,
final String uri,
final String requestBody,
final Response response
) {
final var validatableResponse = response.then();
this.response = validatableResponse.log().all().assertThat();
this.status = HttpStatus.valueOf(response.statusCode());
if (response.statusCode() == HttpStatus.CREATED.value()) {
final var location = validatableResponse.header("Location", startsWith("http://localhost"))
.extract().header("Location");
locationUuid = UUID.fromString(location.substring(location.lastIndexOf('/') + 1));
}
if (nextTitle != null) {
log("\n### " + nextTitle + "\n");
}
log("```");
log(httpMethod.name() + " " + uri);
log(requestBody + "=> status : " + status + " " +
(locationUuid != null ? locationUuid : ""));
log("```");
log("");
}
HttpResponse expecting(final HttpStatus httpStatus) {
public HttpResponse expecting(final HttpStatus httpStatus) {
response.statusCode(httpStatus.value());
return this;
}
HttpResponse expecting(final ContentType contentType) {
public HttpResponse expecting(final ContentType contentType) {
response.contentType(contentType);
return this;
}
void keepingAs(final String uuidAliasName) {
final var location = response.header("Location", startsWith("http://localhost"))
.extract().header("Location");
final var newSubjectUuid = UUID.fromString(
location.substring(location.lastIndexOf('/') + 1));
assertThat(newSubjectUuid).isNotNull();
UseCaseTest.aliases.put(uuidAliasName, newSubjectUuid);
public void keepingAs(final String uuidAliasName) {
UseCaseTest.aliases.put(uuidAliasName, new UseCaseTest.Alias(self().getClass(), locationUuid));
}
}
@SneakyThrows
void log() {
Files.write(Paths.get(getClass().getSimpleName() + ".md"), "".getBytes(), CREATE, TRUNCATE_EXISTING);
}
@SneakyThrows
void log(final String output) {
Files.write(Paths.get(getClass().getSimpleName() + ".md"), (output+"\n").getBytes(), APPEND);
}
protected T self() {
//noinspection unchecked
return (T) this;
}
}

View File

@ -5,10 +5,8 @@ import net.hostsharing.hsadminng.hs.office.person.HsOfficePersonRepository;
import net.hostsharing.hsadminng.lambda.Reducer;
import net.hostsharing.hsadminng.rbac.context.ContextBasedTest;
import net.hostsharing.hsadminng.rbac.test.JpaAttempt;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.TestWatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.web.server.LocalServerPort;
@ -22,7 +20,10 @@ public abstract class UseCaseTest extends ContextBasedTest {
final static String RUN_AS_USER = "superuser-alex@hostsharing.net"; // TODO.test: use global:AGENT when implemented
final static Map<String, UUID> aliases = new HashMap<>();
record Alias<T extends UseCase<T>>(Class<T> useCase, UUID uuid) {}
final static Map<String, Alias<?>> aliases = new HashMap<>();
final static Map<String, Object> properties = new HashMap<>();
@LocalServerPort
Integer port;
@ -40,26 +41,19 @@ public abstract class UseCaseTest extends ContextBasedTest {
context.define("superuser-alex@hostsharing.net");
aliases.put(
"person:Hostsharing eG.uuid",
personRepo.findPersonByOptionalNameLike("Hostsharing eG")
.stream()
.map(HsOfficePersonEntity::getUuid)
.reduce(Reducer::toSingleElement).orElseThrow());
new Alias<>(
null,
personRepo.findPersonByOptionalNameLike("Hostsharing eG")
.stream()
.map(HsOfficePersonEntity::getUuid)
.reduce(Reducer::toSingleElement).orElseThrow())
);
}
);
}
}
class OrderedDependedTestsExtension implements TestWatcher, BeforeEachCallback {
private static boolean previousTestsPassed = true;
@Override
public void testFailed(final ExtensionContext context, final Throwable cause) {
previousTestsPassed = false;
}
@Override
public void beforeEach(final ExtensionContext extensionContext) {
assumeThat(previousTestsPassed).isTrue();
@AfterEach
void cleanup() {
properties.clear();
}
}

View File

@ -0,0 +1,65 @@
package net.hostsharing.hsadminng.hs.office.usecases.debitor;
import net.hostsharing.hsadminng.hs.office.usecases.UseCase;
import net.hostsharing.hsadminng.hs.office.usecases.UseCaseTest;
import static io.restassured.http.ContentType.JSON;
import static org.springframework.http.HttpStatus.CREATED;
public class CreateSelfDebitorForPartner extends UseCase<CreateSelfDebitorForPartner> {
public CreateSelfDebitorForPartner(final UseCaseTest testSuite) {
super(testSuite);
requires("person:Test AG.uuid");
}
@Override
protected HttpResponse run() {
keep("bankaccount:Test AG - refund bank account.uuid", () ->
httpPost("/api/hs/office/bankaccounts", usingJsonBody("""
{
"holder": "Test AG - refund bank account",
"iban": "DE88100900001234567892",
"bic": "BEVODEBB"
}
"""))
.expecting(CREATED).expecting(JSON)
);
keep("contact:Test AG - billing department.uuid", () ->
httpPost("/api/hs/office/contacts", usingJsonBody("""
{
"caption": "Test AG - billing department",
"emailAddresses": {
"main": "billing@test-ag.example.org"
}
}
"""))
.expecting(CREATED).expecting(JSON)
);
keep("debitor:Test AG - Hauptdebitor.uuid", () ->
httpPost("/api/hs/office/debitors", usingJsonBody("""
{
"debitorRel": {
"type": "DEBITOR", // FIXME: should be defaulted to DEBITOR
"anchorUuid": ${person:Test AG.uuid},
"holderUuid": ${person:Test AG.uuid},
"contactUuid": ${contact:Test AG - billing department.uuid}
},
"debitorNumberSuffix": "00",
"billable": true,
"vatId": "VAT123456",
"vatCountryCode": "DE",
"vatBusiness": true,
"vatReverseCharge": false,
"refundBankAccountUuid": ${bankaccount:Test AG - refund bank account.uuid},
"defaultPrefix": "tst"
}
"""))
.expecting(CREATED).expecting(JSON)
);
return null;
}
}

View File

@ -1,16 +1,20 @@
package net.hostsharing.hsadminng.hs.office.usecases;
package net.hostsharing.hsadminng.hs.office.usecases.membership;
import io.restassured.http.ContentType;
import net.hostsharing.hsadminng.hs.office.usecases.UseCase;
import net.hostsharing.hsadminng.hs.office.usecases.UseCaseTest;
import org.springframework.http.HttpStatus;
class HsOfficeMembershipUseCase extends UseCase {
public class CreateMembership extends UseCase<CreateMembership> {
public HsOfficeMembershipUseCase(final UseCaseTest testSuite) {
public CreateMembership(final UseCaseTest testSuite) {
super(testSuite);
requires("partner:Test AG.uuid");
}
@Override
HttpResponse run() {
protected HttpResponse run() {
httpPost("/api/hs/office/memberships", usingJsonBody("""
{
"partnerUuid": "${partner:Test AG.uuid}",

View File

@ -0,0 +1,55 @@
package net.hostsharing.hsadminng.hs.office.usecases.partner;
import io.restassured.http.ContentType;
import net.hostsharing.hsadminng.hs.office.usecases.UseCase;
import net.hostsharing.hsadminng.hs.office.usecases.UseCaseTest;
import org.springframework.http.HttpStatus;
public class CreatePartner extends UseCase<CreatePartner> {
public CreatePartner(final UseCaseTest testSuite) {
super(testSuite);
}
@Override
protected HttpResponse run() {
keep("person:Test AG.uuid", () ->
httpPost("/api/hs/office/persons", usingJsonBody("""
{
"personType": ${personType},
"tradeName": ${tradeName}
},
"""))
.expecting(HttpStatus.CREATED).expecting(ContentType.JSON)
);
keep("contact:Test AG - Bord of Directors.uuid", () ->
httpPost("/api/hs/office/contacts", usingJsonBody("""
{
"caption": ${contactCaption},
"emailAddresses": {
"main": ${emailAddress}
}
}
"""))
.expecting(HttpStatus.CREATED).expecting(ContentType.JSON)
);
return httpPost("/api/hs/office/partners", usingJsonBody("""
{
"partnerNumber": ${partnerNumber},
"partnerRel": {
"anchorUuid": ${person:Hostsharing eG.uuid},
"holderUuid": ${person:Test AG.uuid},
"contactUuid": ${contact:Test AG - Bord of Directors.uuid}
},
"details": {
"registrationOffice": "Registergericht Hamburg",
"registrationNumber": "1234567"
}
}
"""))
.expecting(HttpStatus.CREATED).expecting(ContentType.JSON);
}
}

View File

@ -0,0 +1,25 @@
package net.hostsharing.hsadminng.hs.office.usecases.partner;
import net.hostsharing.hsadminng.hs.office.usecases.UseCase;
import net.hostsharing.hsadminng.hs.office.usecases.UseCaseTest;
import org.springframework.http.HttpStatus;
public class DeletePartner extends UseCase<DeletePartner> {
public DeletePartner(final UseCaseTest testSuite) {
super(testSuite);
requires("partner:Delete AG:uuid", () -> new CreatePartner(testSuite)
.given("personType", "LEGAL_PERSON")
.given("tradeName", "Delete AG")
.given("contactCaption", "Delete AG - Bord of Directors")
.given("emailAddress", "bord-of-directors@delete-ag.example.org"));
}
@Override
protected HttpResponse run() {
httpDelete("/api/hs/office/partners/" + uuid("partner:Delete AG:uuid"))
.expecting(HttpStatus.NO_CONTENT);
return null;
}
}