Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
21bdd4fecc | ||
|
|
b0614cdc79 | ||
|
|
7fd7920778 | ||
|
|
797f36c794 | ||
|
|
0d3e5bc875 | ||
|
|
ce59c60b9e | ||
|
|
d647a878a3 | ||
|
|
6065cf9aa5 | ||
|
|
9f80bc3d5d | ||
|
|
4a08ba25a5 | ||
|
|
72bbb48fa3 | ||
|
|
f4da688078 | ||
|
|
2db8c13f8f |
@@ -0,0 +1,80 @@
|
|||||||
|
# Eine kurze Anleitung
|
||||||
|
|
||||||
|
Bei dieser Applikation handelt es sich um das SuMoC-Backend der Masterprojektgruppe 2025/26.
|
||||||
|
|
||||||
|
___
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
Bitte stelle sicher, dass die Abhängigkeiten der pom.xml installiert wurden. Dies geht über:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./mvnw clean install
|
||||||
|
```
|
||||||
|
|
||||||
|
Im Anschluss überprüfe in der `application.properties` weitere Variablen wie die Zugangsdaten zur Datenbank und zu
|
||||||
|
weiteren externen Services wie Firebase.
|
||||||
|
|
||||||
|
Stelle außerdem sicher, dass die Umgebungsvariable ``FCM_DECRYPTION_KEY`` gesetzt ist, damit die Firebase Cloud
|
||||||
|
Messaging (FCM) Funktionalität korrekt funktioniert. Diese Variable sollte den Schlüssel enthalten, der zur
|
||||||
|
Entschlüsselung der FCM-Zugangsdaten verwendet wird.
|
||||||
|
|
||||||
|
___
|
||||||
|
|
||||||
|
## Ausführen
|
||||||
|
|
||||||
|
Zum Ausführen hast du zwei Optionen: entweder direkt über die Kommandozeile oder im Docker-Container.
|
||||||
|
|
||||||
|
### Kommandozeile
|
||||||
|
|
||||||
|
Die Applikation kann über die Kommandozeile einfach über folgenden Befehl gestartet werden:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./mvnw spring-boot:run
|
||||||
|
```
|
||||||
|
|
||||||
|
### Docker
|
||||||
|
|
||||||
|
Stelle sicher, dass eine `.env`-Datei im Projektverzeichnis vorhanden ist.
|
||||||
|
Danach kann die Applikation wie folgt gestartet werden:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./docker-build.sh # Baut die Docker Images
|
||||||
|
./docker-load.sh # Lädt die Images in Docker
|
||||||
|
docker compose up -d # Startet die Container
|
||||||
|
```
|
||||||
|
|
||||||
|
Zum Stoppen:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
___
|
||||||
|
|
||||||
|
## Testing
|
||||||
|
|
||||||
|
Zum Testing wurde JaCoCo installiert, um die Coverage besser anzuzeigen. Der Fokus beim Testing lag dabei auf den
|
||||||
|
Service-Klassen, da diese die zentrale Geschäftslogik der Applikation enthalten. Damit die Coverage überprüft wird, muss
|
||||||
|
folgender Befehl ausgeführt werden:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./mvnw clean verify
|
||||||
|
```
|
||||||
|
|
||||||
|
Im Anschluss sollte die Coverage über folgende Datei abrufbar sein: [JaCoCo](target/site/jacoco/index.html)
|
||||||
|
|
||||||
|
In dieser wurden allerdings folgende Dateien excludiert, da diese keine eigene Logik enthalten sollten:
|
||||||
|
|
||||||
|
```
|
||||||
|
<exclude>SuMoC/backend/**/models/*.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/Models/*.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/enums/*.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*DTO*.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*Impl.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*Entity.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*Repository.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*Controller.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*Application.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/carta/**</exclude>
|
||||||
|
```
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,993 @@
|
|||||||
|
{
|
||||||
|
"type": "excalidraw",
|
||||||
|
"version": 2,
|
||||||
|
"source": "https://marketplace.visualstudio.com/items?itemName=pomdtr.excalidraw-editor",
|
||||||
|
"elements": [
|
||||||
|
{
|
||||||
|
"id": "title",
|
||||||
|
"type": "text",
|
||||||
|
"x": 100,
|
||||||
|
"y": 20,
|
||||||
|
"width": 600,
|
||||||
|
"height": 32,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 1,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 557323847,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "Regular Trip Detection & Notification Flow",
|
||||||
|
"fontSize": 24,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "center",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "Regular Trip Detection & Notification Flow",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "a0"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "cron-box",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 230,
|
||||||
|
"y": 80,
|
||||||
|
"width": 340,
|
||||||
|
"height": 49,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#6741d9",
|
||||||
|
"backgroundColor": "#ede9fe",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 10,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1051760041,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": {
|
||||||
|
"type": 3
|
||||||
|
},
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "a1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "cron-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 235,
|
||||||
|
"y": 87,
|
||||||
|
"width": 330,
|
||||||
|
"height": 37,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#6741d9",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 11,
|
||||||
|
"version": 5,
|
||||||
|
"versionNonce": 1447267689,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881208493,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "Cron Job\nscheduleNotifyRegularRouteAlternatives()",
|
||||||
|
"fontSize": 14,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "center",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "Cron Job\nscheduleNotifyRegularRouteAlternatives()",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "a2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "arr-cron-detect",
|
||||||
|
"type": "arrow",
|
||||||
|
"x": 400,
|
||||||
|
"y": 129,
|
||||||
|
"width": 0,
|
||||||
|
"height": 46,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 20,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1430386825,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"points": [
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
46
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"startBinding": null,
|
||||||
|
"endBinding": null,
|
||||||
|
"lastCommittedPoint": null,
|
||||||
|
"startArrowhead": null,
|
||||||
|
"endArrowhead": "arrow",
|
||||||
|
"index": "a3"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "detect-box",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 130,
|
||||||
|
"y": 175,
|
||||||
|
"width": 540,
|
||||||
|
"height": 49,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#0c8599",
|
||||||
|
"backgroundColor": "#e3fafc",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 30,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 308179079,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": {
|
||||||
|
"type": 3
|
||||||
|
},
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "a4"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "detect-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 135,
|
||||||
|
"y": 185,
|
||||||
|
"width": 530,
|
||||||
|
"height": 37,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#0c8599",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 31,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 493092713,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "RegularTripDetectionService — query CAR trips by day-of-week from DB",
|
||||||
|
"fontSize": 14,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "center",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "RegularTripDetectionService — query CAR trips by day-of-week from DB",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "a5"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "arr-detect-cluster",
|
||||||
|
"type": "arrow",
|
||||||
|
"x": 400,
|
||||||
|
"y": 224,
|
||||||
|
"width": 0,
|
||||||
|
"height": 46,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 40,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1517078439,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"points": [
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
46
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"startBinding": null,
|
||||||
|
"endBinding": null,
|
||||||
|
"lastCommittedPoint": null,
|
||||||
|
"startArrowhead": null,
|
||||||
|
"endArrowhead": "arrow",
|
||||||
|
"index": "a6"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "cluster-box",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 130,
|
||||||
|
"y": 270,
|
||||||
|
"width": 540,
|
||||||
|
"height": 90,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#e8590c",
|
||||||
|
"backgroundColor": "#fff4e6",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 50,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1700932169,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": {
|
||||||
|
"type": 3
|
||||||
|
},
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "a7"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "cluster-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 135,
|
||||||
|
"y": 278,
|
||||||
|
"width": 530,
|
||||||
|
"height": 75,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#e8590c",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 51,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 954415815,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "IterativeClusterer — per user\n① init candidate map from all trips\n② shuffle & aggregate: same dayOfWeek + time window + H3 k-ring area\n③ pick best iteration by supporter count ④ deduplicate overlapping detections",
|
||||||
|
"fontSize": 14,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "center",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "IterativeClusterer — per user\n① init candidate map from all trips\n② shuffle & aggregate: same dayOfWeek + time window + H3 k-ring area\n③ pick best iteration by supporter count ④ deduplicate overlapping detections",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "a8"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "arr-cluster-parallel",
|
||||||
|
"type": "arrow",
|
||||||
|
"x": 400,
|
||||||
|
"y": 360,
|
||||||
|
"width": 0,
|
||||||
|
"height": 46,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 60,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 639105321,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"points": [
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
46
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"startBinding": null,
|
||||||
|
"endBinding": null,
|
||||||
|
"lastCommittedPoint": null,
|
||||||
|
"startArrowhead": null,
|
||||||
|
"endArrowhead": "arrow",
|
||||||
|
"index": "a9"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "parallel-box",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 60,
|
||||||
|
"y": 406,
|
||||||
|
"width": 680,
|
||||||
|
"height": 90,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#2f9e44",
|
||||||
|
"backgroundColor": "#ebfbee",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "dashed",
|
||||||
|
"seed": 70,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1650346471,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": {
|
||||||
|
"type": 3
|
||||||
|
},
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "aA"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "parallel-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 65,
|
||||||
|
"y": 413,
|
||||||
|
"width": 670,
|
||||||
|
"height": 75,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#2f9e44",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 71,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 821095433,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "Per user in parallel (thread pool, parallelism = 10)\nFetch routing prefs → build request (H3 → LatLng, avg arrival time)\n→ AlternativeRoutingService: CARTA API → filter travel time / weather / transit\n→ if alternative found: earliestTimeToSend = departureWindowStart − 15 min",
|
||||||
|
"fontSize": 14,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "center",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "Per user in parallel (thread pool, parallelism = 10)\nFetch routing prefs → build request (H3 → LatLng, avg arrival time)\n→ AlternativeRoutingService: CARTA API → filter travel time / weather / transit\n→ if alternative found: earliestTimeToSend = departureWindowStart − 15 min",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "aB"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "arr-par-left",
|
||||||
|
"type": "arrow",
|
||||||
|
"x": 280,
|
||||||
|
"y": 496,
|
||||||
|
"width": 0,
|
||||||
|
"height": 44,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 80,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1139438855,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"points": [
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
44
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"startBinding": null,
|
||||||
|
"endBinding": null,
|
||||||
|
"lastCommittedPoint": null,
|
||||||
|
"startArrowhead": null,
|
||||||
|
"endArrowhead": "arrow",
|
||||||
|
"index": "aC"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "arr-par-right",
|
||||||
|
"type": "arrow",
|
||||||
|
"x": 520,
|
||||||
|
"y": 496,
|
||||||
|
"width": 0,
|
||||||
|
"height": 44,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 81,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 501777129,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"points": [
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
0
|
||||||
|
],
|
||||||
|
[
|
||||||
|
0,
|
||||||
|
44
|
||||||
|
]
|
||||||
|
],
|
||||||
|
"startBinding": null,
|
||||||
|
"endBinding": null,
|
||||||
|
"lastCommittedPoint": null,
|
||||||
|
"startArrowhead": null,
|
||||||
|
"endArrowhead": "arrow",
|
||||||
|
"index": "aD"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "carrousel-box",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 60,
|
||||||
|
"y": 540,
|
||||||
|
"width": 310,
|
||||||
|
"height": 49,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1971c2",
|
||||||
|
"backgroundColor": "#e7f5ff",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 90,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1963211815,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": {
|
||||||
|
"type": 3
|
||||||
|
},
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "aE"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "carrousel-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 65,
|
||||||
|
"y": 550,
|
||||||
|
"width": 300,
|
||||||
|
"height": 37,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1971c2",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 91,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 2039102921,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "Save CarrouselCandidates (DB)",
|
||||||
|
"fontSize": 14,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "center",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "Save CarrouselCandidates (DB)",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "aF"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "notif-box",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 430,
|
||||||
|
"y": 540,
|
||||||
|
"width": 310,
|
||||||
|
"height": 49,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1971c2",
|
||||||
|
"backgroundColor": "#e7f5ff",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 2,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 92,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1771577159,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": {
|
||||||
|
"type": 3
|
||||||
|
},
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "aG"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "notif-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 435,
|
||||||
|
"y": 550,
|
||||||
|
"width": 300,
|
||||||
|
"height": 37,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1971c2",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 93,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 854695081,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "Schedule Notifications PENDING (DB)",
|
||||||
|
"fontSize": 14,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "center",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "Schedule Notifications PENDING (DB)",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "aH"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "legend-trigger",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 60,
|
||||||
|
"y": 630,
|
||||||
|
"width": 16,
|
||||||
|
"height": 16,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#6741d9",
|
||||||
|
"backgroundColor": "#ede9fe",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 100,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1677893223,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "aI"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "legend-trigger-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 82,
|
||||||
|
"y": 630,
|
||||||
|
"width": 80,
|
||||||
|
"height": 18,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 101,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1237983113,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "Trigger",
|
||||||
|
"fontSize": 13,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "left",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "Trigger",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "aJ"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "legend-data",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 200,
|
||||||
|
"y": 630,
|
||||||
|
"width": 16,
|
||||||
|
"height": 16,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#0c8599",
|
||||||
|
"backgroundColor": "#e3fafc",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 102,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 655374727,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "aK"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "legend-data-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 222,
|
||||||
|
"y": 630,
|
||||||
|
"width": 100,
|
||||||
|
"height": 18,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 103,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1011828329,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "Data fetching",
|
||||||
|
"fontSize": 13,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "left",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "Data fetching",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "aL"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "legend-algo",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 360,
|
||||||
|
"y": 630,
|
||||||
|
"width": 16,
|
||||||
|
"height": 16,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#e8590c",
|
||||||
|
"backgroundColor": "#fff4e6",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 104,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1744662695,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "aM"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "legend-algo-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 382,
|
||||||
|
"y": 630,
|
||||||
|
"width": 100,
|
||||||
|
"height": 18,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 105,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 894210377,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "Algorithm",
|
||||||
|
"fontSize": 13,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "left",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "Algorithm",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "aN"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "legend-parallel",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 510,
|
||||||
|
"y": 630,
|
||||||
|
"width": 16,
|
||||||
|
"height": 16,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#2f9e44",
|
||||||
|
"backgroundColor": "#ebfbee",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "dashed",
|
||||||
|
"seed": 106,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 7783367,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "aO"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "legend-parallel-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 532,
|
||||||
|
"y": 630,
|
||||||
|
"width": 140,
|
||||||
|
"height": 18,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 107,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 2048753705,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "Parallel processing",
|
||||||
|
"fontSize": 13,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "left",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "Parallel processing",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "aP"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "legend-output",
|
||||||
|
"type": "rectangle",
|
||||||
|
"x": 690,
|
||||||
|
"y": 630,
|
||||||
|
"width": 16,
|
||||||
|
"height": 16,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1971c2",
|
||||||
|
"backgroundColor": "#e7f5ff",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 108,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 1620620007,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"index": "aQ"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "legend-output-text",
|
||||||
|
"type": "text",
|
||||||
|
"x": 712,
|
||||||
|
"y": 630,
|
||||||
|
"width": 60,
|
||||||
|
"height": 18,
|
||||||
|
"angle": 0,
|
||||||
|
"strokeColor": "#1e1e1e",
|
||||||
|
"backgroundColor": "transparent",
|
||||||
|
"fillStyle": "solid",
|
||||||
|
"strokeWidth": 1,
|
||||||
|
"roughness": 0,
|
||||||
|
"opacity": 100,
|
||||||
|
"strokeStyle": "solid",
|
||||||
|
"seed": 109,
|
||||||
|
"version": 2,
|
||||||
|
"versionNonce": 414028553,
|
||||||
|
"isDeleted": false,
|
||||||
|
"updated": 1772881204950,
|
||||||
|
"link": null,
|
||||||
|
"locked": false,
|
||||||
|
"groupIds": [],
|
||||||
|
"frameId": null,
|
||||||
|
"roundness": null,
|
||||||
|
"boundElements": [],
|
||||||
|
"text": "Output",
|
||||||
|
"fontSize": 13,
|
||||||
|
"fontFamily": 6,
|
||||||
|
"textAlign": "left",
|
||||||
|
"verticalAlign": "top",
|
||||||
|
"containerId": null,
|
||||||
|
"originalText": "Output",
|
||||||
|
"autoResize": true,
|
||||||
|
"lineHeight": 1.35,
|
||||||
|
"index": "aR"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"appState": {
|
||||||
|
"gridSize": 20,
|
||||||
|
"gridStep": 5,
|
||||||
|
"gridModeEnabled": false,
|
||||||
|
"viewBackgroundColor": "#ffffff"
|
||||||
|
},
|
||||||
|
"files": {}
|
||||||
|
}
|
||||||
@@ -58,11 +58,6 @@
|
|||||||
<groupId>org.springframework.boot</groupId>
|
<groupId>org.springframework.boot</groupId>
|
||||||
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
<artifactId>spring-boot-starter-thymeleaf</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>com.h2database</groupId>
|
|
||||||
<artifactId>h2</artifactId>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.projectlombok</groupId>
|
<groupId>org.projectlombok</groupId>
|
||||||
<artifactId>lombok</artifactId>
|
<artifactId>lombok</artifactId>
|
||||||
@@ -261,6 +256,45 @@
|
|||||||
</execution>
|
</execution>
|
||||||
</executions>
|
</executions>
|
||||||
</plugin>
|
</plugin>
|
||||||
|
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.jacoco</groupId>
|
||||||
|
<artifactId>jacoco-maven-plugin</artifactId>
|
||||||
|
<version>0.8.11</version>
|
||||||
|
<executions>
|
||||||
|
<!-- Agent wird vor Tests aktiviert -->
|
||||||
|
<execution>
|
||||||
|
<id>prepare-agent</id>
|
||||||
|
<goals>
|
||||||
|
<goal>prepare-agent</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
|
||||||
|
<!-- Report nach Tests erzeugen -->
|
||||||
|
<execution>
|
||||||
|
<id>report</id>
|
||||||
|
<phase>verify</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>report</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<excludes>
|
||||||
|
<!-- <exclude>SuMoC/backend/**/mapper/*.class</exclude> -->
|
||||||
|
<exclude>SuMoC/backend/**/models/*.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/Models/*.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/enums/*.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*DTO*.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*Impl.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*Entity.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*Repository.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*Controller.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/**/*Application.class</exclude>
|
||||||
|
<exclude>SuMoC/backend/carta/**</exclude>
|
||||||
|
</excludes>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
</plugins>
|
</plugins>
|
||||||
</build>
|
</build>
|
||||||
|
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import SuMoC.backend.user.service.CurrentUserService;
|
|||||||
import SuMoC.backend.user.service.FriendshipService;
|
import SuMoC.backend.user.service.FriendshipService;
|
||||||
import SuMoC.backend.user.service.PrivacyService;
|
import SuMoC.backend.user.service.PrivacyService;
|
||||||
import SuMoC.backend.user.stats.*;
|
import SuMoC.backend.user.stats.*;
|
||||||
|
import SuMoC.backend.user.stats.models.StatsList;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import org.springframework.data.domain.PageRequest;
|
import org.springframework.data.domain.PageRequest;
|
||||||
import org.springframework.data.domain.Pageable;
|
import org.springframework.data.domain.Pageable;
|
||||||
|
|||||||
@@ -92,10 +92,13 @@ public class AuthenticationService {
|
|||||||
User user = new User(registrationDTO.getPublicName(), registrationDTO.getPrivateName(), registrationDTO.getEmail().toLowerCase(), encodedPassword);
|
User user = new User(registrationDTO.getPublicName(), registrationDTO.getPrivateName(), registrationDTO.getEmail().toLowerCase(), encodedPassword);
|
||||||
|
|
||||||
// Sicherheitshalber nochmal explizit setzen
|
// Sicherheitshalber nochmal explizit setzen
|
||||||
|
/* Shouldnt be necessary
|
||||||
if (user.getRoles() == null || user.getRoles().isEmpty()) {
|
if (user.getRoles() == null || user.getRoles().isEmpty()) {
|
||||||
user.setRoles(new HashSet<>());
|
user.setRoles(new HashSet<>());
|
||||||
user.getRoles().add(RoleName.USER);
|
user.getRoles().add(RoleName.USER);
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
userRepository.save(user);
|
userRepository.save(user);
|
||||||
// We generate the login dto to get the token right after registration
|
// We generate the login dto to get the token right after registration
|
||||||
|
|||||||
@@ -72,7 +72,8 @@ public class TokenService {
|
|||||||
return jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
|
return jwtEncoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();
|
||||||
}
|
}
|
||||||
|
|
||||||
//TODO: change return type
|
// Never used so commented out
|
||||||
|
/*
|
||||||
public void decodeJwt(String jwt){
|
public void decodeJwt(String jwt){
|
||||||
System.out.println("###############DECODED JWT##################");
|
System.out.println("###############DECODED JWT##################");
|
||||||
System.out.println(jwtDecoder.decode(jwt).getClaims());
|
System.out.println(jwtDecoder.decode(jwt).getClaims());
|
||||||
@@ -83,5 +84,7 @@ public class TokenService {
|
|||||||
return Math.toIntExact(jwtDecoder.decode(jwt).getClaim("userId"));
|
return Math.toIntExact(jwtDecoder.decode(jwt).getClaim("userId"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ import java.security.KeyPairGenerator;
|
|||||||
|
|
||||||
public class KeyGeneratorUtility {
|
public class KeyGeneratorUtility {
|
||||||
|
|
||||||
|
private KeyGeneratorUtility() {
|
||||||
|
throw new IllegalStateException("Utility class");
|
||||||
|
}
|
||||||
|
|
||||||
public static KeyPair generateRsaKey(){
|
public static KeyPair generateRsaKey(){
|
||||||
|
|
||||||
KeyPair keyPair;
|
KeyPair keyPair;
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ import SuMoC.backend.user.dtos.MinimalUserDTO;
|
|||||||
import SuMoC.backend.user.dtos.StatScope;
|
import SuMoC.backend.user.dtos.StatScope;
|
||||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||||
import SuMoC.backend.user.service.UserService;
|
import SuMoC.backend.user.service.UserService;
|
||||||
import SuMoC.backend.user.stats.StatsList;
|
import SuMoC.backend.user.stats.models.StatsList;
|
||||||
import SuMoC.backend.user.stats.StatsService;
|
import SuMoC.backend.user.stats.StatsService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.media.Content;
|
import io.swagger.v3.oas.annotations.media.Content;
|
||||||
|
|||||||
@@ -6,14 +6,13 @@ import SuMoC.backend.routing.models.RoutingPreferences;
|
|||||||
import SuMoC.backend.trip.models.Trip;
|
import SuMoC.backend.trip.models.Trip;
|
||||||
import SuMoC.backend.user.enums.RoleName;
|
import SuMoC.backend.user.enums.RoleName;
|
||||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||||
import SuMoC.backend.user.stats.StatsList;
|
import SuMoC.backend.user.stats.models.StatsList;
|
||||||
import com.fasterxml.jackson.annotation.JsonManagedReference;
|
import com.fasterxml.jackson.annotation.JsonManagedReference;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
import java.util.HashSet;
|
import java.util.HashSet;
|
||||||
import java.util.Set;
|
import java.util.Set;
|
||||||
import java.util.UUID;
|
|
||||||
|
|
||||||
@Entity
|
@Entity
|
||||||
@Table(name = "users")
|
@Table(name = "users")
|
||||||
|
|||||||
@@ -145,10 +145,11 @@ public class FriendshipService {
|
|||||||
// Allowing sender to send a new request
|
// Allowing sender to send a new request
|
||||||
friendshipRepository.delete(relFriendToSender);
|
friendshipRepository.delete(relFriendToSender);
|
||||||
friendshipRepository.flush();
|
friendshipRepository.flush();
|
||||||
}
|
} else {
|
||||||
|
|
||||||
// If we reach here, something unexpected happened
|
// If we reach here, something unexpected happened
|
||||||
throw new RuntimeException("Cannot send friend request: Unexpected relationship status. Please inform devs.");
|
throw new RuntimeException("Cannot send friend request: Unexpected relationship status. Please inform devs.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Create new friendship request
|
// Create new friendship request
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ public class UserService {
|
|||||||
));
|
));
|
||||||
// TODO: Check tomorrow if this makes sense
|
// TODO: Check tomorrow if this makes sense
|
||||||
// TODO: Can Users see the minimalDTO if they are blocked?
|
// TODO: Can Users see the minimalDTO if they are blocked?
|
||||||
if (friendshipService.getBlockedUsers(id).stream().anyMatch(blocked -> blocked.getId().equals(requested.getId()))) {
|
if (friendshipService.getBlockedUsers(id).stream().anyMatch(blocked -> blocked.getId().equals(sender.getId()))) {
|
||||||
throw new ResponseStatusException(
|
throw new ResponseStatusException(
|
||||||
HttpStatus.FORBIDDEN,
|
HttpStatus.FORBIDDEN,
|
||||||
"Der Nutzer hat dich blockiert."
|
"Der Nutzer hat dich blockiert."
|
||||||
@@ -87,6 +87,12 @@ public class UserService {
|
|||||||
public void deleteUser(Long id) {
|
public void deleteUser(Long id) {
|
||||||
User sender = currentUser.get();
|
User sender = currentUser.get();
|
||||||
|
|
||||||
|
if (!userRepository.existsById(id)) {
|
||||||
|
throw new ResponseStatusException(
|
||||||
|
HttpStatus.NOT_FOUND,
|
||||||
|
"Nutzer existiert nicht.");
|
||||||
|
}
|
||||||
|
|
||||||
boolean isAdmin = sender.getRoles().contains(RoleName.ADMIN);
|
boolean isAdmin = sender.getRoles().contains(RoleName.ADMIN);
|
||||||
boolean isOwnProfile = sender.getId().equals(id);
|
boolean isOwnProfile = sender.getId().equals(id);
|
||||||
|
|
||||||
@@ -96,12 +102,6 @@ public class UserService {
|
|||||||
"Ein Nutzer kann nur sein eigenes Profil löschen.");
|
"Ein Nutzer kann nur sein eigenes Profil löschen.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!userRepository.existsById(id)) {
|
|
||||||
throw new ResponseStatusException(
|
|
||||||
HttpStatus.NOT_FOUND,
|
|
||||||
"Nutzer existiert nicht.");
|
|
||||||
}
|
|
||||||
|
|
||||||
userRepository.deleteById(id);
|
userRepository.deleteById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,20 +135,23 @@ public class UserService {
|
|||||||
"Das Passwort muss mindestens 8 Zeichen lang sein."
|
"Das Passwort muss mindestens 8 Zeichen lang sein."
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
// TODO: Add Email Notification for password change
|
|
||||||
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
|
||||||
sender.setPassword(passwordEncoder.encode(newPassword));
|
|
||||||
userRepository.save(sender);
|
|
||||||
|
|
||||||
User updatedSender = userRepository.findById(id)
|
// TODO: Add Email Notification for password change
|
||||||
|
User userToChange = userRepository.findById(id)
|
||||||
.orElseThrow(() -> new ResponseStatusException(
|
.orElseThrow(() -> new ResponseStatusException(
|
||||||
HttpStatus.NOT_FOUND,
|
HttpStatus.NOT_FOUND,
|
||||||
"Nutzer existiert nicht"
|
"Nutzer existiert nicht"
|
||||||
));
|
));
|
||||||
|
userToChange.setPassword(passwordEncoder.encode(newPassword));
|
||||||
|
userRepository.save(userToChange);
|
||||||
|
|
||||||
return new LoginResponseDTO(userMapper.toUserDTO(updatedSender),
|
if (!sender.getId().equals(id)) {
|
||||||
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(updatedSender)));
|
return new LoginResponseDTO(null, null);
|
||||||
|
}
|
||||||
|
|
||||||
|
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
|
||||||
|
return new LoginResponseDTO(userMapper.toUserDTO(userToChange),
|
||||||
|
tokenService.generateUserJwt(authentication, userMapper.toUserDTO(userToChange)));
|
||||||
}
|
}
|
||||||
|
|
||||||
public LoginResponseDTO setEmail(Long id, String newEmail) {
|
public LoginResponseDTO setEmail(Long id, String newEmail) {
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package SuMoC.backend.user.stats;
|
package SuMoC.backend.user.stats;
|
||||||
|
|
||||||
|
import SuMoC.backend.user.stats.models.StatsList;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||||
import org.springframework.stereotype.Repository;
|
import org.springframework.stereotype.Repository;
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
package SuMoC.backend.user.stats;
|
package SuMoC.backend.user.stats;
|
||||||
|
|
||||||
import SuMoC.backend.gamification.Timeframe;
|
import SuMoC.backend.gamification.Timeframe;
|
||||||
|
import SuMoC.backend.user.stats.models.Stats;
|
||||||
|
import SuMoC.backend.user.stats.models.StatsList;
|
||||||
import jakarta.persistence.criteria.Join;
|
import jakarta.persistence.criteria.Join;
|
||||||
import jakarta.persistence.criteria.JoinType;
|
import jakarta.persistence.criteria.JoinType;
|
||||||
import org.springframework.data.jpa.domain.Specification;
|
import org.springframework.data.jpa.domain.Specification;
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package SuMoC.backend.user.stats;
|
package SuMoC.backend.user.stats;
|
||||||
|
|
||||||
|
import SuMoC.backend.user.stats.models.Stats;
|
||||||
import org.springframework.data.jpa.repository.JpaRepository;
|
import org.springframework.data.jpa.repository.JpaRepository;
|
||||||
|
|
||||||
public interface StatsRepository extends JpaRepository<Stats, Long> {
|
public interface StatsRepository extends JpaRepository<Stats, Long> {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import SuMoC.backend.user.dtos.StatScope;
|
|||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import SuMoC.backend.user.repository.UserRepository;
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
import SuMoC.backend.user.service.CurrentUserService;
|
import SuMoC.backend.user.service.CurrentUserService;
|
||||||
|
import SuMoC.backend.user.stats.models.StatsList;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
@@ -74,10 +75,11 @@ public class StatsService {
|
|||||||
|
|
||||||
User user = currentUserService.get();
|
User user = currentUserService.get();
|
||||||
|
|
||||||
|
/* Should not be necessary because it gets always init
|
||||||
if (user.getStats() == null) {
|
if (user.getStats() == null) {
|
||||||
user.setStats(new StatsList(user));
|
user.setStats(new StatsList(user));
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
StatScope effectiveScope = (scope == null) ? StatScope.ALL : scope;
|
StatScope effectiveScope = (scope == null) ? StatScope.ALL : scope;
|
||||||
|
|
||||||
|
|||||||
+5
-69
@@ -1,9 +1,13 @@
|
|||||||
package SuMoC.backend.user.stats;
|
package SuMoC.backend.user.stats.models;
|
||||||
|
|
||||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||||
import io.swagger.v3.oas.annotations.media.Schema;
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
import jakarta.persistence.*;
|
import jakarta.persistence.*;
|
||||||
|
import lombok.Getter;
|
||||||
|
import lombok.Setter;
|
||||||
|
|
||||||
|
@Getter
|
||||||
|
@Setter
|
||||||
@Entity
|
@Entity
|
||||||
public class Stats {
|
public class Stats {
|
||||||
|
|
||||||
@@ -57,72 +61,4 @@ public class Stats {
|
|||||||
this.KM_DRIVEN = 0L;
|
this.KM_DRIVEN = 0L;
|
||||||
this.MOBILITY_SCORE = 0L;
|
this.MOBILITY_SCORE = 0L;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Getters and Setters
|
|
||||||
|
|
||||||
|
|
||||||
public StatsList getStatsList() {
|
|
||||||
return statsList;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setStatsList(StatsList statsList) {
|
|
||||||
this.statsList = statsList;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getXP() {
|
|
||||||
return XP;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setXP(Long XP) {
|
|
||||||
this.XP = XP;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getCO2_SAVED() {
|
|
||||||
return CO2_SAVED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setCO2_SAVED(Long CO2_SAVED) {
|
|
||||||
this.CO2_SAVED = CO2_SAVED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getKM_CYCLED() {
|
|
||||||
return KM_CYCLED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setKM_CYCLED(Long KM_CYCLED) {
|
|
||||||
this.KM_CYCLED = KM_CYCLED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getKM_WALKED() {
|
|
||||||
return KM_WALKED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setKM_WALKED(Long KM_WALKED) {
|
|
||||||
this.KM_WALKED = KM_WALKED;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getKM_PUBLIC_TRANSPORT() {
|
|
||||||
return KM_PUBLIC_TRANSPORT;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setKM_PUBLIC_TRANSPORT(Long KM_PUBLIC_TRANSPORT) {
|
|
||||||
this.KM_PUBLIC_TRANSPORT = KM_PUBLIC_TRANSPORT;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getKM_DRIVEN() {
|
|
||||||
return KM_DRIVEN;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setKM_DRIVEN(Long KM_DRIVEN) {
|
|
||||||
this.KM_DRIVEN = KM_DRIVEN;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Long getMobility_SCORE() {
|
|
||||||
return MOBILITY_SCORE;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMobility_SCORE(Long mobility_SCORE) {
|
|
||||||
MOBILITY_SCORE = mobility_SCORE;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+1
-38
@@ -1,4 +1,4 @@
|
|||||||
package SuMoC.backend.user.stats;
|
package SuMoC.backend.user.stats.models;
|
||||||
import java.lang.reflect.Field;
|
import java.lang.reflect.Field;
|
||||||
|
|
||||||
|
|
||||||
@@ -50,43 +50,6 @@ public class StatsList {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Getter & Setter
|
|
||||||
|
|
||||||
|
|
||||||
public User getUser() {
|
|
||||||
return user;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setUser(User user) {
|
|
||||||
this.user = user;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Stats getTotalStats() {
|
|
||||||
return totalStats;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTotalStats(Stats totalStats) {
|
|
||||||
this.totalStats = totalStats;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Stats getMonthlyStats() {
|
|
||||||
return monthlyStats;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setMonthlyStats(Stats monthlyStats) {
|
|
||||||
this.monthlyStats = monthlyStats;
|
|
||||||
}
|
|
||||||
|
|
||||||
public Stats getWeeklyStats() {
|
|
||||||
return weeklyStats;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setWeeklyStats(Stats weeklyStats) {
|
|
||||||
this.weeklyStats = weeklyStats;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// Other Methods
|
// Other Methods
|
||||||
|
|
||||||
public Stats getStats(Timeframe timeframe) {
|
public Stats getStats(Timeframe timeframe) {
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
package SuMoC.backend.carrousel.service;
|
||||||
|
|
||||||
|
import SuMoC.backend.carrousel.config.CarrouselProperties;
|
||||||
|
import SuMoC.backend.carrousel.dto.AdHocAlternativeContext;
|
||||||
|
import SuMoC.backend.carrousel.dto.AlternativeCarrouselDTO;
|
||||||
|
import SuMoC.backend.carrousel.dto.RegularTripAlternativeContext;
|
||||||
|
import SuMoC.backend.carrousel.enums.CarrouselCandidateType;
|
||||||
|
import SuMoC.backend.carrousel.models.CarrouselCandidate;
|
||||||
|
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
|
||||||
|
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||||
|
import SuMoC.backend.regulartrip.dtos.MinimalDetectedRegularTripDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||||
|
import SuMoC.backend.trip.Modality;
|
||||||
|
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||||
|
import SuMoC.backend.trip.models.Trip;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Captor;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.time.DayOfWeek;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.IntStream;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
public class CarrouselServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private CarrouselCandidateRepository carrouselCandidateRepository;
|
||||||
|
|
||||||
|
@Mock(lenient = true)
|
||||||
|
private CarrouselProperties carrouselProperties;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private CarrouselService carrouselService;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<CarrouselCandidate> candidateCaptor;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
when(carrouselProperties.getMaxCarrouselItems()).thenReturn(5);
|
||||||
|
when(carrouselProperties.getRecentSuggestionWindowDays()).thenReturn(7);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- addAdHocTripCandidates ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void addAdHocTripCandidates_EmptyList_NoSaves() {
|
||||||
|
Trip trip = createTrip(10L, 5L);
|
||||||
|
|
||||||
|
carrouselService.addAdHocTripCandidates(trip, List.of());
|
||||||
|
|
||||||
|
verify(carrouselCandidateRepository, never()).save(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void addAdHocTripCandidates_MultipleAlternatives_SavesEachWithCorrectFields() {
|
||||||
|
Trip trip = createTrip(10L, 5L);
|
||||||
|
RouteDTO route1 = RouteDTO.getMockRouteDTO();
|
||||||
|
RouteDTO route2 = RouteDTO.getMockRouteDTO();
|
||||||
|
|
||||||
|
carrouselService.addAdHocTripCandidates(trip, List.of(route1, route2));
|
||||||
|
|
||||||
|
verify(carrouselCandidateRepository, times(2)).save(candidateCaptor.capture());
|
||||||
|
List<CarrouselCandidate> captured = candidateCaptor.getAllValues();
|
||||||
|
|
||||||
|
for (CarrouselCandidate candidate : captured) {
|
||||||
|
assertEquals(5L, candidate.getUserId());
|
||||||
|
assertEquals(10L, candidate.getAdHocTripId());
|
||||||
|
assertEquals(CarrouselCandidateType.ADHOC_ALTERNATIVE, candidate.getCandidateType());
|
||||||
|
assertNotNull(candidate.getSuggestedAt());
|
||||||
|
}
|
||||||
|
assertEquals(route1, captured.get(0).getSuggestedAlternative());
|
||||||
|
assertEquals(route2, captured.get(1).getSuggestedAlternative());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- getRegularTripCandidates ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getRegularTripCandidates_EmptyList_EmptyResult() {
|
||||||
|
DetectedRegularTripDTO detectedTrip = createDetectedRegularTrip();
|
||||||
|
|
||||||
|
List<CarrouselCandidate> result = carrouselService.getRegularTripCandidates(1L, detectedTrip, List.of());
|
||||||
|
|
||||||
|
assertTrue(result.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getRegularTripCandidates_SingleAlternative_CorrectFields() {
|
||||||
|
DetectedRegularTripDTO detectedTrip = createDetectedRegularTrip();
|
||||||
|
RouteDTO route = RouteDTO.getMockRouteDTO();
|
||||||
|
|
||||||
|
List<CarrouselCandidate> result = carrouselService.getRegularTripCandidates(1L, detectedTrip, List.of(route));
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
CarrouselCandidate candidate = result.get(0);
|
||||||
|
assertEquals(1L, candidate.getUserId());
|
||||||
|
assertEquals(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE, candidate.getCandidateType());
|
||||||
|
assertEquals(route, candidate.getSuggestedAlternative());
|
||||||
|
assertNotNull(candidate.getDetectedRegularTrip());
|
||||||
|
assertNotNull(candidate.getSuggestedAt());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- getCarrouselForUser ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getCarrouselForUser_NoCandidates_EmptyDTO() {
|
||||||
|
when(carrouselCandidateRepository.findByUserIdDesc(eq(1L), any(Instant.class)))
|
||||||
|
.thenReturn(List.of());
|
||||||
|
|
||||||
|
AlternativeCarrouselDTO result = carrouselService.getCarrouselForUser(1L);
|
||||||
|
|
||||||
|
assertTrue(result.getAlternatives().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getCarrouselForUser_MixedTypes_MappedCorrectly() {
|
||||||
|
CarrouselCandidate adhocCandidate = createCandidate(CarrouselCandidateType.ADHOC_ALTERNATIVE, 1L);
|
||||||
|
CarrouselCandidate regularCandidate = createCandidate(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE, 1L);
|
||||||
|
|
||||||
|
when(carrouselCandidateRepository.findByUserIdDesc(eq(1L), any(Instant.class)))
|
||||||
|
.thenReturn(List.of(adhocCandidate, regularCandidate));
|
||||||
|
|
||||||
|
AlternativeCarrouselDTO result = carrouselService.getCarrouselForUser(1L);
|
||||||
|
|
||||||
|
assertEquals(2, result.getAlternatives().size());
|
||||||
|
assertInstanceOf(AdHocAlternativeContext.class, result.getAlternatives().get(0));
|
||||||
|
assertInstanceOf(RegularTripAlternativeContext.class, result.getAlternatives().get(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getCarrouselForUser_MoreThanMax_LimitedTo5() {
|
||||||
|
List<CarrouselCandidate> candidates = IntStream.range(0, 7)
|
||||||
|
.mapToObj(i -> createCandidate(CarrouselCandidateType.ADHOC_ALTERNATIVE, 1L))
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
when(carrouselCandidateRepository.findByUserIdDesc(eq(1L), any(Instant.class)))
|
||||||
|
.thenReturn(candidates);
|
||||||
|
|
||||||
|
AlternativeCarrouselDTO result = carrouselService.getCarrouselForUser(1L);
|
||||||
|
|
||||||
|
assertEquals(5, result.getAlternatives().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getCarrouselForUser_AdhocCandidate_MapsToAdHocAlternativeContext() {
|
||||||
|
CarrouselCandidate candidate = createCandidate(CarrouselCandidateType.ADHOC_ALTERNATIVE, 1L);
|
||||||
|
candidate.setAdHocTripId(42L);
|
||||||
|
|
||||||
|
when(carrouselCandidateRepository.findByUserIdDesc(eq(1L), any(Instant.class)))
|
||||||
|
.thenReturn(List.of(candidate));
|
||||||
|
|
||||||
|
AlternativeCarrouselDTO result = carrouselService.getCarrouselForUser(1L);
|
||||||
|
|
||||||
|
assertInstanceOf(AdHocAlternativeContext.class, result.getAlternatives().get(0));
|
||||||
|
AdHocAlternativeContext context = (AdHocAlternativeContext) result.getAlternatives().get(0);
|
||||||
|
assertEquals(42L, context.getTripId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getCarrouselForUser_RegularCandidate_MapsToRegularTripAlternativeContext() {
|
||||||
|
CarrouselCandidate candidate = createCandidate(CarrouselCandidateType.REGULAR_TRIP_ALTERNATIVE, 1L);
|
||||||
|
|
||||||
|
when(carrouselCandidateRepository.findByUserIdDesc(eq(1L), any(Instant.class)))
|
||||||
|
.thenReturn(List.of(candidate));
|
||||||
|
|
||||||
|
AlternativeCarrouselDTO result = carrouselService.getCarrouselForUser(1L);
|
||||||
|
|
||||||
|
assertInstanceOf(RegularTripAlternativeContext.class, result.getAlternatives().get(0));
|
||||||
|
RegularTripAlternativeContext context = (RegularTripAlternativeContext) result.getAlternatives().get(0);
|
||||||
|
assertNotNull(context.getDetectedRegularTrip());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- helpers ---
|
||||||
|
|
||||||
|
private Trip createTrip(Long tripId, Long userId) {
|
||||||
|
User user = new User();
|
||||||
|
user.setId(userId);
|
||||||
|
Trip trip = new Trip();
|
||||||
|
trip.setId(tripId);
|
||||||
|
trip.setUser(user);
|
||||||
|
return trip;
|
||||||
|
}
|
||||||
|
|
||||||
|
private DetectedRegularTripDTO createDetectedRegularTrip() {
|
||||||
|
Instant start = Instant.parse("2026-03-12T08:00:00Z");
|
||||||
|
Instant end = Instant.parse("2026-03-12T08:40:00Z");
|
||||||
|
|
||||||
|
return DetectedRegularTripDTO.builder()
|
||||||
|
.userId(1L)
|
||||||
|
.modality(Modality.CAR)
|
||||||
|
.dayOfWeek(DayOfWeek.THURSDAY)
|
||||||
|
.departureWindowStart(LocalTime.of(8, 0))
|
||||||
|
.departureWindowEnd(LocalTime.of(8, 15))
|
||||||
|
.arrivalWindowStart(LocalTime.of(8, 30))
|
||||||
|
.arrivalWindowEnd(LocalTime.of(8, 45))
|
||||||
|
.startH3Center("8a1fa535568ffff")
|
||||||
|
.endH3Center("8a1fa535020ffff")
|
||||||
|
.supportingTrips(List.of(
|
||||||
|
RegularTripDetectionDTO.builder()
|
||||||
|
.tripId(100L)
|
||||||
|
.userId(1L)
|
||||||
|
.startH3Cell("8a1fa535568ffff")
|
||||||
|
.endH3Cell("8a1fa535020ffff")
|
||||||
|
.startTime(start)
|
||||||
|
.endTime(end)
|
||||||
|
.mainModality(Modality.CAR)
|
||||||
|
.build()
|
||||||
|
))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private CarrouselCandidate createCandidate(CarrouselCandidateType type, Long userId) {
|
||||||
|
CarrouselCandidate.CarrouselCandidateBuilder builder = CarrouselCandidate.builder()
|
||||||
|
.userId(userId)
|
||||||
|
.suggestedAlternative(RouteDTO.getMockRouteDTO())
|
||||||
|
.suggestedAt(Instant.now())
|
||||||
|
.candidateType(type);
|
||||||
|
|
||||||
|
if (type == CarrouselCandidateType.ADHOC_ALTERNATIVE) {
|
||||||
|
builder.adHocTripId(1L);
|
||||||
|
} else {
|
||||||
|
DetectedRegularTripDTO detectedTrip = createDetectedRegularTrip();
|
||||||
|
builder.detectedRegularTrip(MinimalDetectedRegularTripDTO.fromDetectedRegularTripDTO(detectedTrip));
|
||||||
|
}
|
||||||
|
|
||||||
|
return builder.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
package SuMoC.backend.gamification.badges;
|
||||||
|
|
||||||
|
import SuMoC.backend.gamification.badges.mapper.BadgeMapper;
|
||||||
|
import SuMoC.backend.gamification.badges.models.Badge;
|
||||||
|
import SuMoC.backend.gamification.badges.models.BadgeCategory;
|
||||||
|
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
||||||
|
import SuMoC.backend.images.ImageBase64Util;
|
||||||
|
import jakarta.transaction.Transactional;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.annotation.DirtiesContext;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
//@SpringBootTest
|
||||||
|
//@ActiveProfiles("test")
|
||||||
|
//@Transactional
|
||||||
|
//@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)
|
||||||
|
public class BadgeMapperTest {
|
||||||
|
|
||||||
|
private BadgeDTO createDTO() {
|
||||||
|
BadgeDTO dto = new BadgeDTO();
|
||||||
|
dto.setId(1L);
|
||||||
|
dto.setName("TestBadge");
|
||||||
|
dto.setDescription("TestDescription");
|
||||||
|
dto.setCategory(BadgeCategory.MONTHLY);
|
||||||
|
dto.setCriteria(Map.of("XP", 100));
|
||||||
|
dto.setImageBase64(ImageBase64Util.encode(new byte[]{1, 2, 3}));
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testToEntity() {
|
||||||
|
BadgeDTO dto = createDTO();
|
||||||
|
Badge badge = BadgeMapper.toEntity(dto);
|
||||||
|
|
||||||
|
assertEquals(dto.getId(), badge.getId());
|
||||||
|
assertEquals(dto.getName(), badge.getName());
|
||||||
|
assertEquals(dto.getDescription(), badge.getDescription());
|
||||||
|
assertEquals(dto.getCategory(), badge.getCategory());
|
||||||
|
assertEquals(dto.getCriteria(), badge.getCriteria());
|
||||||
|
assertArrayEquals(ImageBase64Util.decode(dto.getImageBase64()), badge.getImage().getImageData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testToDTO() {
|
||||||
|
Badge badge = BadgeMapper.toEntity(createDTO());
|
||||||
|
BadgeDTO dto = BadgeMapper.toDTO(badge);
|
||||||
|
|
||||||
|
assertEquals(badge.getId(), dto.getId());
|
||||||
|
assertEquals(badge.getName(), dto.getName());
|
||||||
|
assertEquals(badge.getDescription(), dto.getDescription());
|
||||||
|
assertEquals(badge.getCategory(), dto.getCategory());
|
||||||
|
assertEquals(badge.getCriteria(), dto.getCriteria());
|
||||||
|
assertEquals(ImageBase64Util.encode(badge.getImage().getImageData()), dto.getImageBase64());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateEntityFromDTO() {
|
||||||
|
Badge badge = BadgeMapper.toEntity(createDTO());
|
||||||
|
|
||||||
|
BadgeDTO updatedDTO = new BadgeDTO();
|
||||||
|
updatedDTO.setName("UpdatedName");
|
||||||
|
updatedDTO.setDescription("UpdatedDescription");
|
||||||
|
updatedDTO.setCategory(BadgeCategory.OPNV);
|
||||||
|
updatedDTO.setCriteria(Map.of("XP", 999));
|
||||||
|
updatedDTO.setImageBase64(ImageBase64Util.encode(new byte[]{9, 8, 7}));
|
||||||
|
|
||||||
|
BadgeMapper.updateEntityFromDTO(badge, updatedDTO);
|
||||||
|
|
||||||
|
assertEquals("UpdatedName", badge.getName());
|
||||||
|
assertEquals("UpdatedDescription", badge.getDescription());
|
||||||
|
assertEquals(BadgeCategory.OPNV, badge.getCategory());
|
||||||
|
assertEquals(Map.of("XP", 999), badge.getCriteria());
|
||||||
|
assertArrayEquals(new byte[]{9, 8, 7}, badge.getImage().getImageData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateEntityFromDTO_nullImage() {
|
||||||
|
// badge.getImage() == null Branch
|
||||||
|
Badge badge = BadgeMapper.toEntity(createDTO());
|
||||||
|
badge.setImage(null);
|
||||||
|
|
||||||
|
BadgeDTO dto = new BadgeDTO();
|
||||||
|
dto.setName("x");
|
||||||
|
dto.setImageBase64(ImageBase64Util.encode(new byte[]{1, 2, 3}));
|
||||||
|
|
||||||
|
BadgeMapper.updateEntityFromDTO(badge, dto);
|
||||||
|
assertNotNull(badge.getImage());
|
||||||
|
assertArrayEquals(new byte[]{1, 2, 3}, badge.getImage().getImageData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateEntityFromDTO_nullImageBase64() {
|
||||||
|
// dto.getImageBase64() == null Branch -> image stays same
|
||||||
|
Badge badge = BadgeMapper.toEntity(createDTO());
|
||||||
|
byte[] originalImage = badge.getImage().getImageData();
|
||||||
|
|
||||||
|
BadgeDTO dto = new BadgeDTO();
|
||||||
|
dto.setName("x");
|
||||||
|
dto.setImageBase64(null);
|
||||||
|
|
||||||
|
BadgeMapper.updateEntityFromDTO(badge, dto);
|
||||||
|
assertArrayEquals(originalImage, badge.getImage().getImageData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateEntityFromDTO_emptyImageBase64() {
|
||||||
|
// dto.getImageBase64() == null Branch -> image stays same
|
||||||
|
Badge badge = BadgeMapper.toEntity(createDTO());
|
||||||
|
byte[] originalImage = badge.getImage().getImageData();
|
||||||
|
|
||||||
|
BadgeDTO dto = new BadgeDTO();
|
||||||
|
dto.setName("x");
|
||||||
|
dto.setImageBase64("");
|
||||||
|
|
||||||
|
BadgeMapper.updateEntityFromDTO(badge, dto);
|
||||||
|
assertArrayEquals(originalImage, badge.getImage().getImageData());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package SuMoC.backend.gamification.badges;
|
||||||
|
|
||||||
|
import SuMoC.backend.gamification.badges.mapper.UserBadgeMapper;
|
||||||
|
import SuMoC.backend.gamification.badges.models.*;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Base64;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class UserBadgeMapperTest {
|
||||||
|
|
||||||
|
private UserBadge createUserBadge(boolean withImage) {
|
||||||
|
Badge badge = new Badge();
|
||||||
|
badge.setId(1L);
|
||||||
|
badge.setName("TestBadge");
|
||||||
|
badge.setDescription("TestDescription");
|
||||||
|
badge.setCategory(BadgeCategory.XP);
|
||||||
|
badge.setCriteria(Map.of("XP", 100));
|
||||||
|
|
||||||
|
if (withImage) {
|
||||||
|
BadgeImageEntity image = new BadgeImageEntity();
|
||||||
|
image.setImageData(new byte[]{1, 2, 3});
|
||||||
|
badge.setImage(image);
|
||||||
|
}
|
||||||
|
|
||||||
|
UserBadge userBadge = new UserBadge();
|
||||||
|
userBadge.setBadge(badge);
|
||||||
|
userBadge.setAwardedAt(LocalDateTime.of(2024, 1, 1, 0, 0));
|
||||||
|
return userBadge;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testToDTO_withImage() {
|
||||||
|
UserBadge userBadge = createUserBadge(true);
|
||||||
|
UserBadgeDTO dto = UserBadgeMapper.toDTO(userBadge);
|
||||||
|
|
||||||
|
assertEquals(1L, dto.getBadgeId());
|
||||||
|
assertEquals("TestBadge", dto.getName());
|
||||||
|
assertEquals("TestDescription", dto.getDescription());
|
||||||
|
assertEquals(BadgeCategory.XP, dto.getCategory());
|
||||||
|
assertEquals(Map.of("XP", 100), dto.getCriteria());
|
||||||
|
assertEquals(LocalDateTime.of(2024, 1, 1, 0, 0), dto.getAwardedAt());
|
||||||
|
assertEquals(Base64.getEncoder().encodeToString(new byte[]{1, 2, 3}), dto.getImageBase64());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testToDTO_withoutImage() {
|
||||||
|
// badge.getImage() == null Branch
|
||||||
|
UserBadge userBadge = createUserBadge(false);
|
||||||
|
UserBadgeDTO dto = UserBadgeMapper.toDTO(userBadge);
|
||||||
|
|
||||||
|
assertNotNull(dto);
|
||||||
|
assertNull(dto.getImageBase64());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testToDTO_list() {
|
||||||
|
List<UserBadge> list = List.of(createUserBadge(true), createUserBadge(false));
|
||||||
|
List<UserBadgeDTO> dtos = UserBadgeMapper.toDTO(list);
|
||||||
|
|
||||||
|
assertEquals(2, dtos.size());
|
||||||
|
assertNotNull(dtos.get(0).getImageBase64());
|
||||||
|
assertNull(dtos.get(1).getImageBase64());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
package SuMoC.backend.gamification.challenges;
|
||||||
|
|
||||||
|
import SuMoC.backend.gamification.challenges.Models.ChallengeDTO;
|
||||||
|
import SuMoC.backend.gamification.challenges.Models.Challenge;
|
||||||
|
import SuMoC.backend.images.ImageBase64Util;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class ChallengeMapperTest {
|
||||||
|
|
||||||
|
private ChallengeDTO createDTO(boolean withImage) {
|
||||||
|
ChallengeDTO dto = new ChallengeDTO();
|
||||||
|
dto.setName("TestChallenge");
|
||||||
|
dto.setDescription("TestDescription");
|
||||||
|
dto.setCriteria(Map.of("XP", 100));
|
||||||
|
dto.setReward(50);
|
||||||
|
if (withImage) {
|
||||||
|
dto.setBase64image(ImageBase64Util.encode(new byte[]{1, 2, 3}));
|
||||||
|
}
|
||||||
|
return dto;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testToEntity_withImage() {
|
||||||
|
ChallengeDTO dto = createDTO(true);
|
||||||
|
Challenge challenge = ChallengeMapper.toEntity(dto);
|
||||||
|
|
||||||
|
assertEquals(dto.getName(), challenge.getName());
|
||||||
|
assertEquals(dto.getDescription(), challenge.getDescription());
|
||||||
|
assertEquals(dto.getCriteria(), challenge.getCriteria());
|
||||||
|
assertEquals(dto.getReward(), challenge.getReward());
|
||||||
|
assertNotNull(challenge.getImage());
|
||||||
|
assertArrayEquals(ImageBase64Util.decode(dto.getBase64image()), challenge.getImage().getImageData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testToEntity_withoutImage() {
|
||||||
|
// dto.getBase64image() == null Branch
|
||||||
|
Challenge challenge = ChallengeMapper.toEntity(createDTO(false));
|
||||||
|
assertNull(challenge.getImage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testToEntity_blankImage() {
|
||||||
|
// dto.getBase64image().isBlank() Branch
|
||||||
|
ChallengeDTO dto = createDTO(false);
|
||||||
|
dto.setBase64image(" ");
|
||||||
|
Challenge challenge = ChallengeMapper.toEntity(dto);
|
||||||
|
assertNull(challenge.getImage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testToDTO_withImage() {
|
||||||
|
Challenge challenge = ChallengeMapper.toEntity(createDTO(true));
|
||||||
|
ChallengeDTO dto = ChallengeMapper.toDTO(challenge);
|
||||||
|
|
||||||
|
assertEquals(challenge.getName(), dto.getName());
|
||||||
|
assertEquals(challenge.getDescription(), dto.getDescription());
|
||||||
|
assertEquals(challenge.getCriteria(), dto.getCriteria());
|
||||||
|
assertEquals(challenge.getReward(), dto.getReward());
|
||||||
|
assertEquals(ImageBase64Util.encode(challenge.getImage().getImageData()), dto.getBase64image());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testToDTO_withoutImage() {
|
||||||
|
// challenge.getImage() == null → orElse(null) Branch
|
||||||
|
Challenge challenge = ChallengeMapper.toEntity(createDTO(false));
|
||||||
|
ChallengeDTO dto = ChallengeMapper.toDTO(challenge);
|
||||||
|
assertNull(dto.getBase64image());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateEntityFromDTO_withImage() {
|
||||||
|
Challenge challenge = ChallengeMapper.toEntity(createDTO(true));
|
||||||
|
|
||||||
|
ChallengeDTO updatedDTO = createDTO(true);
|
||||||
|
updatedDTO.setName("UpdatedName");
|
||||||
|
updatedDTO.setBase64image(ImageBase64Util.encode(new byte[]{9, 8, 7}));
|
||||||
|
|
||||||
|
ChallengeMapper.updateEntityFromDTO(challenge, updatedDTO);
|
||||||
|
|
||||||
|
assertEquals("UpdatedName", challenge.getName());
|
||||||
|
assertArrayEquals(new byte[]{9, 8, 7}, challenge.getImage().getImageData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateEntityFromDTO_nullImage() {
|
||||||
|
// challenge.getImage() == null
|
||||||
|
Challenge challenge = ChallengeMapper.toEntity(createDTO(true));
|
||||||
|
challenge.setImage(null);
|
||||||
|
|
||||||
|
ChallengeDTO dto = createDTO(true);
|
||||||
|
ChallengeMapper.updateEntityFromDTO(challenge, dto);
|
||||||
|
assertNotNull(challenge.getImage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateEntityFromDTO_emptyImageBase64() {
|
||||||
|
// dto.getBase64image().isEmpty()
|
||||||
|
Challenge challenge = ChallengeMapper.toEntity(createDTO(true));
|
||||||
|
byte[] original = challenge.getImage().getImageData();
|
||||||
|
|
||||||
|
ChallengeDTO dto = createDTO(false);
|
||||||
|
dto.setBase64image(""); // ← leerer String
|
||||||
|
|
||||||
|
ChallengeMapper.updateEntityFromDTO(challenge, dto);
|
||||||
|
assertArrayEquals(original, challenge.getImage().getImageData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testUpdateEntityFromDTO_noImageInDTO() {
|
||||||
|
// dto.getBase64image() == null
|
||||||
|
Challenge challenge = ChallengeMapper.toEntity(createDTO(true));
|
||||||
|
byte[] original = challenge.getImage().getImageData();
|
||||||
|
|
||||||
|
ChallengeMapper.updateEntityFromDTO(challenge, createDTO(false));
|
||||||
|
assertArrayEquals(original, challenge.getImage().getImageData());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
package SuMoC.backend.h3;
|
||||||
|
|
||||||
|
import com.uber.h3core.util.LatLng;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class H3ServiceTest {
|
||||||
|
|
||||||
|
private H3Service h3Service;
|
||||||
|
private H3Configuration config;
|
||||||
|
|
||||||
|
// Essen, Germany
|
||||||
|
private static final double ESSEN_LAT = 51.4556;
|
||||||
|
private static final double ESSEN_LON = 7.0116;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
config = new H3Configuration();
|
||||||
|
h3Service = new H3Service(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void latLngToCell_KnownCoordinates_ReturnsValidH3Cell() {
|
||||||
|
String cell = h3Service.latLngToCell(ESSEN_LAT, ESSEN_LON, 10);
|
||||||
|
|
||||||
|
assertNotNull(cell);
|
||||||
|
assertFalse(cell.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void latLngToCellForRoute_UsesConfiguredResolution() {
|
||||||
|
String cellViaRoute = h3Service.latLngToCellForRoute(ESSEN_LAT, ESSEN_LON);
|
||||||
|
String cellExplicit = h3Service.latLngToCell(ESSEN_LAT, ESSEN_LON, 10);
|
||||||
|
|
||||||
|
assertEquals(cellExplicit, cellViaRoute);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void latLngToCellForRoute_DifferentResolution_UsesThatResolution() {
|
||||||
|
config.setRoutePatternResolution(7);
|
||||||
|
h3Service = new H3Service(config);
|
||||||
|
|
||||||
|
String cellViaRoute = h3Service.latLngToCellForRoute(ESSEN_LAT, ESSEN_LON);
|
||||||
|
String cellExplicit = h3Service.latLngToCell(ESSEN_LAT, ESSEN_LON, 7);
|
||||||
|
|
||||||
|
assertEquals(cellExplicit, cellViaRoute);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void cellToLatLng_KnownCell_CoordinatesInExpectedRange() {
|
||||||
|
String cell = h3Service.latLngToCell(ESSEN_LAT, ESSEN_LON, 10);
|
||||||
|
|
||||||
|
LatLng result = h3Service.cellToLatLng(cell);
|
||||||
|
|
||||||
|
assertNotNull(result);
|
||||||
|
assertTrue(result.lat > 51.0 && result.lat < 52.0, "Latitude should be near Essen");
|
||||||
|
assertTrue(result.lng > 6.5 && result.lng < 7.5, "Longitude should be near Essen");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void roundTrip_LatLngToCellThenBack_ApproximatelySameCoordinates() {
|
||||||
|
String cell = h3Service.latLngToCell(ESSEN_LAT, ESSEN_LON, 10);
|
||||||
|
|
||||||
|
LatLng result = h3Service.cellToLatLng(cell);
|
||||||
|
|
||||||
|
assertEquals(ESSEN_LAT, result.lat, 0.01);
|
||||||
|
assertEquals(ESSEN_LON, result.lng, 0.01);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getKRingNeighbors_K1_Returns6Cells() {
|
||||||
|
String cell = h3Service.latLngToCell(ESSEN_LAT, ESSEN_LON, 10);
|
||||||
|
|
||||||
|
List<String> ring = h3Service.getKRingNeighbors(cell, 1);
|
||||||
|
|
||||||
|
assertEquals(6, ring.size());
|
||||||
|
assertFalse(ring.contains(cell), "Ring at k=1 should not contain the origin cell");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getKRingNeighbors_K0_ReturnsOnlyOriginCell() {
|
||||||
|
String cell = h3Service.latLngToCell(ESSEN_LAT, ESSEN_LON, 10);
|
||||||
|
|
||||||
|
List<String> ring = h3Service.getKRingNeighbors(cell, 0);
|
||||||
|
|
||||||
|
assertEquals(1, ring.size());
|
||||||
|
assertEquals(cell, ring.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getRoutePatternNeighbors_UsesConfiguredRings() {
|
||||||
|
String cell = h3Service.latLngToCell(ESSEN_LAT, ESSEN_LON, 10);
|
||||||
|
|
||||||
|
List<String> neighbors = h3Service.getRoutePatternNeighbors(cell);
|
||||||
|
List<String> directRing = h3Service.getKRingNeighbors(cell, 1);
|
||||||
|
|
||||||
|
assertEquals(directRing, neighbors);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package SuMoC.backend.meteo;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class ForecastResponseTest {
|
||||||
|
|
||||||
|
private ForecastResponse createForecast(List<LocalDateTime> times, List<Integer> weatherCodes) {
|
||||||
|
return new ForecastResponse(
|
||||||
|
47.0, 8.0, 0.5, 3600, "Europe/Zurich", "CET", 400.0,
|
||||||
|
new ForecastResponse.HourlyUnits("iso8601", "wmo code"),
|
||||||
|
new ForecastResponse.Hourly(times, weatherCodes)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getWeatherCodeAt_findsExactMatch() {
|
||||||
|
LocalDateTime target = LocalDateTime.of(2026, 3, 12, 14, 0);
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(
|
||||||
|
LocalDateTime.of(2026, 3, 12, 13, 0),
|
||||||
|
target,
|
||||||
|
LocalDateTime.of(2026, 3, 12, 15, 0)
|
||||||
|
),
|
||||||
|
List.of(0, 61, 3)
|
||||||
|
);
|
||||||
|
|
||||||
|
Optional<Integer> code = forecast.getWeatherCodeAt(target);
|
||||||
|
|
||||||
|
assertTrue(code.isPresent());
|
||||||
|
assertEquals(61, code.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getWeatherCodeAt_returnsEmptyWhenNotFound() {
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(LocalDateTime.of(2026, 3, 12, 13, 0)),
|
||||||
|
List.of(0)
|
||||||
|
);
|
||||||
|
|
||||||
|
Optional<Integer> code = forecast.getWeatherCodeAt(LocalDateTime.of(2026, 3, 12, 14, 0));
|
||||||
|
|
||||||
|
assertTrue(code.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getWeatherCodeAt_returnsEmptyWhenHourlyIsNull() {
|
||||||
|
ForecastResponse forecast = new ForecastResponse(
|
||||||
|
47.0, 8.0, 0.5, 3600, "Europe/Zurich", "CET", 400.0,
|
||||||
|
new ForecastResponse.HourlyUnits("iso8601", "wmo code"),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
|
||||||
|
assertTrue(forecast.getWeatherCodeAt(LocalDateTime.now()).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getWeatherConditionsBetween_returnsCorrectConditions() throws Exception {
|
||||||
|
LocalDateTime hour12 = LocalDateTime.of(2026, 3, 12, 12, 0);
|
||||||
|
LocalDateTime hour13 = LocalDateTime.of(2026, 3, 12, 13, 0);
|
||||||
|
LocalDateTime hour14 = LocalDateTime.of(2026, 3, 12, 14, 0);
|
||||||
|
LocalDateTime hour15 = LocalDateTime.of(2026, 3, 12, 15, 0);
|
||||||
|
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour12, hour13, hour14, hour15),
|
||||||
|
List.of(0, 61, 95, 3)
|
||||||
|
);
|
||||||
|
|
||||||
|
Instant start = hour13.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
Instant end = hour15.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
List<WeatherCondition> conditions = forecast.getWeatherConditionsBetween(start, end);
|
||||||
|
|
||||||
|
assertEquals(3, conditions.size());
|
||||||
|
assertEquals(WeatherCondition.RAIN, conditions.get(0));
|
||||||
|
assertEquals(WeatherCondition.THUNDERSTORM, conditions.get(1));
|
||||||
|
assertEquals(WeatherCondition.CLOUDY, conditions.get(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getWeatherConditionsBetween_singleHour() throws Exception {
|
||||||
|
LocalDateTime hour10 = LocalDateTime.of(2026, 3, 12, 10, 0);
|
||||||
|
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour10),
|
||||||
|
List.of(45)
|
||||||
|
);
|
||||||
|
|
||||||
|
Instant instant = hour10.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
List<WeatherCondition> conditions = forecast.getWeatherConditionsBetween(instant, instant);
|
||||||
|
|
||||||
|
assertEquals(1, conditions.size());
|
||||||
|
assertEquals(WeatherCondition.FOG, conditions.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getWeatherConditionsBetween_throwsWhenStartAfterEnd() {
|
||||||
|
LocalDateTime hour10 = LocalDateTime.of(2026, 3, 12, 10, 0);
|
||||||
|
LocalDateTime hour14 = LocalDateTime.of(2026, 3, 12, 14, 0);
|
||||||
|
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour10, hour14),
|
||||||
|
List.of(0, 3)
|
||||||
|
);
|
||||||
|
|
||||||
|
Instant start = hour14.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
Instant end = hour10.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
assertThrows(IllegalArgumentException.class,
|
||||||
|
() -> forecast.getWeatherConditionsBetween(start, end));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void findIndex_throwsWhenTimeNotInList() {
|
||||||
|
LocalDateTime hour10 = LocalDateTime.of(2026, 3, 12, 10, 0);
|
||||||
|
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour10),
|
||||||
|
List.of(0)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Use a time not present in the list to trigger findIndex failure
|
||||||
|
Instant start = LocalDateTime.of(2026, 3, 13, 10, 0)
|
||||||
|
.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
Instant end = LocalDateTime.of(2026, 3, 13, 11, 0)
|
||||||
|
.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
assertThrows(RuntimeException.class,
|
||||||
|
() -> forecast.getWeatherConditionsBetween(start, end));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void findIndex_matchesByDateAndHourIgnoringMinutes() throws Exception {
|
||||||
|
// findIndex matches on date + hour, so minutes don't matter
|
||||||
|
LocalDateTime hour14Exact = LocalDateTime.of(2026, 3, 12, 14, 0);
|
||||||
|
LocalDateTime hour15Exact = LocalDateTime.of(2026, 3, 12, 15, 0);
|
||||||
|
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour14Exact, hour15Exact),
|
||||||
|
List.of(0, 3)
|
||||||
|
);
|
||||||
|
|
||||||
|
// Start/end with non-zero minutes — findIndex should still match on the hour
|
||||||
|
LocalDateTime startWithMinutes = LocalDateTime.of(2026, 3, 12, 14, 30);
|
||||||
|
LocalDateTime endWithMinutes = LocalDateTime.of(2026, 3, 12, 15, 45);
|
||||||
|
|
||||||
|
Instant start = startWithMinutes.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
Instant end = endWithMinutes.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
List<WeatherCondition> conditions = forecast.getWeatherConditionsBetween(start, end);
|
||||||
|
|
||||||
|
assertEquals(2, conditions.size());
|
||||||
|
assertEquals(WeatherCondition.CLEAR, conditions.get(0));
|
||||||
|
assertEquals(WeatherCondition.CLOUDY, conditions.get(1));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
package SuMoC.backend.other;
|
||||||
|
|
||||||
|
import SuMoC.backend.images.ImageBase64Util;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
class ImageBase64UtilTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void encode_nullInput_returnsNull() {
|
||||||
|
assertNull(ImageBase64Util.encode(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void encode_emptyArray_returnsNull() {
|
||||||
|
assertNull(ImageBase64Util.encode(new byte[0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void encode_validData_returnsBase64String() {
|
||||||
|
byte[] data = {1, 2, 3};
|
||||||
|
String result = ImageBase64Util.encode(data);
|
||||||
|
assertNotNull(result);
|
||||||
|
assertFalse(result.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void decode_nullInput_returnsNull() {
|
||||||
|
assertNull(ImageBase64Util.decode(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void decode_emptyString_returnsNull() {
|
||||||
|
assertNull(ImageBase64Util.decode(""));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void decode_validBase64_returnsBytes() {
|
||||||
|
byte[] original = {1, 2, 3};
|
||||||
|
String encoded = ImageBase64Util.encode(original);
|
||||||
|
assertArrayEquals(original, ImageBase64Util.decode(encoded));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void encodeAndDecode_roundtrip_returnsOriginal() {
|
||||||
|
byte[] original = {10, 20, 30, 40, 50};
|
||||||
|
assertArrayEquals(original, ImageBase64Util.decode(ImageBase64Util.encode(original)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
package SuMoC.backend.routing.services;
|
package SuMoC.backend.routing.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.meteo.ForecastResponse;
|
||||||
|
import SuMoC.backend.meteo.ForecastService;
|
||||||
|
import SuMoC.backend.meteo.WeatherCondition;
|
||||||
import SuMoC.backend.routing.config.OnCallRoutingProperties;
|
import SuMoC.backend.routing.config.OnCallRoutingProperties;
|
||||||
import SuMoC.backend.routing.dtos.*;
|
import SuMoC.backend.routing.dtos.*;
|
||||||
import SuMoC.backend.trip.Modality;
|
import SuMoC.backend.trip.Modality;
|
||||||
@@ -11,15 +14,22 @@ import org.mockito.Mock;
|
|||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneId;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyDouble;
|
||||||
import static org.mockito.Mockito.when;
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
@ExtendWith(MockitoExtension.class)
|
||||||
public class AlternativeFilterServiceTest {
|
public class AlternativeFilterServiceTest {
|
||||||
|
|
||||||
|
@Mock(lenient = true)
|
||||||
|
private ForecastService forecastService;
|
||||||
|
|
||||||
@Mock(lenient = true)
|
@Mock(lenient = true)
|
||||||
private OnCallRoutingProperties onCallRoutingProperties;
|
private OnCallRoutingProperties onCallRoutingProperties;
|
||||||
|
|
||||||
@@ -41,6 +51,12 @@ public class AlternativeFilterServiceTest {
|
|||||||
when(onCallRoutingProperties.getAcceptableAdditionalMultiplierPrefersPhysical()).thenReturn(1.5);
|
when(onCallRoutingProperties.getAcceptableAdditionalMultiplierPrefersPhysical()).thenReturn(1.5);
|
||||||
when(onCallRoutingProperties.getMinimumAcceptedAdditionalSecondsRegular()).thenReturn(600);
|
when(onCallRoutingProperties.getMinimumAcceptedAdditionalSecondsRegular()).thenReturn(600);
|
||||||
when(onCallRoutingProperties.getMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity()).thenReturn(900);
|
when(onCallRoutingProperties.getMinimumAcceptedAdditionalSecondsPrefersPhysicalActivity()).thenReturn(900);
|
||||||
|
when(onCallRoutingProperties.getAcceptableCyclingConditions()).thenReturn(List.of(
|
||||||
|
WeatherCondition.CLEAR, WeatherCondition.PARTLY_CLOUDY, WeatherCondition.CLOUDY
|
||||||
|
));
|
||||||
|
when(onCallRoutingProperties.getAcceptableWalkingConditions()).thenReturn(List.of(
|
||||||
|
WeatherCondition.CLEAR, WeatherCondition.PARTLY_CLOUDY, WeatherCondition.CLOUDY, WeatherCondition.FOG
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -160,4 +176,199 @@ public class AlternativeFilterServiceTest {
|
|||||||
route.setSteps(new ArrayList<>(steps));
|
route.setSteps(new ArrayList<>(steps));
|
||||||
return route;
|
return route;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- filterForBadWeather tests ---
|
||||||
|
|
||||||
|
private ForecastResponse createForecast(List<LocalDateTime> times, List<Integer> weatherCodes) {
|
||||||
|
return new ForecastResponse(
|
||||||
|
51.44, 6.98, 0.5, 3600, "Europe/Berlin", "CET", 100.0,
|
||||||
|
new ForecastResponse.HourlyUnits("iso8601", "wmo code"),
|
||||||
|
new ForecastResponse.Hourly(times, weatherCodes)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private RouteDTO createCyclingRoute(Instant start, Instant end) {
|
||||||
|
RouteDTO route = RouteDTO.getMockRouteDTO();
|
||||||
|
route.setStartDateTime(start);
|
||||||
|
route.setEndDateTime(end);
|
||||||
|
route.setSteps(new ArrayList<>(List.of(new StepDTO(Modality.BICYCLE, 3000.0))));
|
||||||
|
return route;
|
||||||
|
}
|
||||||
|
|
||||||
|
private RouteDTO createWalkingRoute(Instant start, Instant end) {
|
||||||
|
RouteDTO route = RouteDTO.getMockRouteDTO();
|
||||||
|
route.setStartDateTime(start);
|
||||||
|
route.setEndDateTime(end);
|
||||||
|
route.setSteps(new ArrayList<>(List.of(new StepDTO(Modality.WALKING, 1000.0))));
|
||||||
|
return route;
|
||||||
|
}
|
||||||
|
|
||||||
|
private RouteDTO createTransitRoute(Instant start, Instant end) {
|
||||||
|
RouteDTO route = RouteDTO.getMockRouteDTO();
|
||||||
|
route.setStartDateTime(start);
|
||||||
|
route.setEndDateTime(end);
|
||||||
|
route.setSteps(new ArrayList<>(List.of(
|
||||||
|
new StepDTO(Modality.WALKING, 300.0),
|
||||||
|
new TransitStepDTO(Modality.BUS, 2000.0, "101", "Line", "Start", "End"),
|
||||||
|
new StepDTO(Modality.WALKING, 200.0)
|
||||||
|
)));
|
||||||
|
return route;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void filterForBadWeather_keepsCyclingInClearWeather() {
|
||||||
|
LocalDateTime hour10 = LocalDateTime.of(2026, 3, 12, 10, 0);
|
||||||
|
LocalDateTime hour11 = LocalDateTime.of(2026, 3, 12, 11, 0);
|
||||||
|
Instant start = hour10.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
Instant end = hour11.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour10, hour11),
|
||||||
|
List.of(0, 1) // CLEAR
|
||||||
|
);
|
||||||
|
when(forecastService.getTodayYesterdayForecast(anyDouble(), anyDouble())).thenReturn(forecast);
|
||||||
|
|
||||||
|
request.setOriginLat(51.44);
|
||||||
|
request.setOriginLon(6.98);
|
||||||
|
|
||||||
|
RouteDTO cyclingRoute = createCyclingRoute(start, end);
|
||||||
|
List<RouteDTO> result = alternativeFilterService.filterForBadWeather(request, List.of(cyclingRoute), onCallRoutingProperties);
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void filterForBadWeather_removesCyclingInRain() {
|
||||||
|
LocalDateTime hour10 = LocalDateTime.of(2026, 3, 12, 10, 0);
|
||||||
|
LocalDateTime hour11 = LocalDateTime.of(2026, 3, 12, 11, 0);
|
||||||
|
Instant start = hour10.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
Instant end = hour11.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour10, hour11),
|
||||||
|
List.of(0, 61) // CLEAR then RAIN
|
||||||
|
);
|
||||||
|
when(forecastService.getTodayYesterdayForecast(anyDouble(), anyDouble())).thenReturn(forecast);
|
||||||
|
|
||||||
|
request.setOriginLat(51.44);
|
||||||
|
request.setOriginLon(6.98);
|
||||||
|
|
||||||
|
RouteDTO cyclingRoute = createCyclingRoute(start, end);
|
||||||
|
List<RouteDTO> result = alternativeFilterService.filterForBadWeather(request, List.of(cyclingRoute), onCallRoutingProperties);
|
||||||
|
|
||||||
|
assertTrue(result.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void filterForBadWeather_keepsWalkingInFog() {
|
||||||
|
LocalDateTime hour10 = LocalDateTime.of(2026, 3, 12, 10, 0);
|
||||||
|
LocalDateTime hour11 = LocalDateTime.of(2026, 3, 12, 11, 0);
|
||||||
|
Instant start = hour10.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
Instant end = hour11.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour10, hour11),
|
||||||
|
List.of(45, 45) // FOG
|
||||||
|
);
|
||||||
|
when(forecastService.getTodayYesterdayForecast(anyDouble(), anyDouble())).thenReturn(forecast);
|
||||||
|
|
||||||
|
request.setOriginLat(51.44);
|
||||||
|
request.setOriginLon(6.98);
|
||||||
|
|
||||||
|
RouteDTO walkingRoute = createWalkingRoute(start, end);
|
||||||
|
List<RouteDTO> result = alternativeFilterService.filterForBadWeather(request, List.of(walkingRoute), onCallRoutingProperties);
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void filterForBadWeather_removesCyclingInFog() {
|
||||||
|
LocalDateTime hour10 = LocalDateTime.of(2026, 3, 12, 10, 0);
|
||||||
|
LocalDateTime hour11 = LocalDateTime.of(2026, 3, 12, 11, 0);
|
||||||
|
Instant start = hour10.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
Instant end = hour11.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
// FOG is acceptable for walking but NOT for cycling
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour10, hour11),
|
||||||
|
List.of(45, 45) // FOG
|
||||||
|
);
|
||||||
|
when(forecastService.getTodayYesterdayForecast(anyDouble(), anyDouble())).thenReturn(forecast);
|
||||||
|
|
||||||
|
request.setOriginLat(51.44);
|
||||||
|
request.setOriginLon(6.98);
|
||||||
|
|
||||||
|
RouteDTO cyclingRoute = createCyclingRoute(start, end);
|
||||||
|
List<RouteDTO> result = alternativeFilterService.filterForBadWeather(request, List.of(cyclingRoute), onCallRoutingProperties);
|
||||||
|
|
||||||
|
assertTrue(result.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void filterForBadWeather_alwaysKeepsTransitRoutes() {
|
||||||
|
LocalDateTime hour10 = LocalDateTime.of(2026, 3, 12, 10, 0);
|
||||||
|
LocalDateTime hour11 = LocalDateTime.of(2026, 3, 12, 11, 0);
|
||||||
|
Instant start = hour10.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
Instant end = hour11.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour10, hour11),
|
||||||
|
List.of(95, 95) // THUNDERSTORM
|
||||||
|
);
|
||||||
|
when(forecastService.getTodayYesterdayForecast(anyDouble(), anyDouble())).thenReturn(forecast);
|
||||||
|
|
||||||
|
request.setOriginLat(51.44);
|
||||||
|
request.setOriginLon(6.98);
|
||||||
|
|
||||||
|
RouteDTO transitRoute = createTransitRoute(start, end);
|
||||||
|
List<RouteDTO> result = alternativeFilterService.filterForBadWeather(request, List.of(transitRoute), onCallRoutingProperties);
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void filterForBadWeather_mixedRoutes_filtersOnlyPhysicalInBadWeather() {
|
||||||
|
LocalDateTime hour10 = LocalDateTime.of(2026, 3, 12, 10, 0);
|
||||||
|
LocalDateTime hour11 = LocalDateTime.of(2026, 3, 12, 11, 0);
|
||||||
|
Instant start = hour10.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
Instant end = hour11.atZone(ZoneId.systemDefault()).toInstant();
|
||||||
|
|
||||||
|
ForecastResponse forecast = createForecast(
|
||||||
|
List.of(hour10, hour11),
|
||||||
|
List.of(61, 61) // RAIN
|
||||||
|
);
|
||||||
|
when(forecastService.getTodayYesterdayForecast(anyDouble(), anyDouble())).thenReturn(forecast);
|
||||||
|
|
||||||
|
request.setOriginLat(51.44);
|
||||||
|
request.setOriginLon(6.98);
|
||||||
|
|
||||||
|
RouteDTO cyclingRoute = createCyclingRoute(start, end);
|
||||||
|
RouteDTO walkingRoute = createWalkingRoute(start, end);
|
||||||
|
RouteDTO transitRoute = createTransitRoute(start, end);
|
||||||
|
|
||||||
|
List<RouteDTO> result = alternativeFilterService.filterForBadWeather(
|
||||||
|
request, List.of(cyclingRoute, walkingRoute, transitRoute), onCallRoutingProperties);
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
assertEquals(transitRoute, result.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void filterForBadWeather_returnsAllWhenForecastFails() {
|
||||||
|
when(forecastService.getTodayYesterdayForecast(anyDouble(), anyDouble()))
|
||||||
|
.thenThrow(new RuntimeException("API unavailable"));
|
||||||
|
|
||||||
|
request.setOriginLat(51.44);
|
||||||
|
request.setOriginLon(6.98);
|
||||||
|
|
||||||
|
Instant start = Instant.parse("2026-03-12T09:00:00Z");
|
||||||
|
Instant end = Instant.parse("2026-03-12T10:00:00Z");
|
||||||
|
RouteDTO cyclingRoute = createCyclingRoute(start, end);
|
||||||
|
RouteDTO walkingRoute = createWalkingRoute(start, end);
|
||||||
|
|
||||||
|
List<RouteDTO> result = alternativeFilterService.filterForBadWeather(
|
||||||
|
request, List.of(cyclingRoute, walkingRoute), onCallRoutingProperties);
|
||||||
|
|
||||||
|
assertEquals(2, result.size());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,236 @@
|
|||||||
|
package SuMoC.backend.routing.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.carta.DirectionsService;
|
||||||
|
import SuMoC.backend.routing.config.AdHocRoutingProperties;
|
||||||
|
import SuMoC.backend.routing.config.OnCallRoutingProperties;
|
||||||
|
import SuMoC.backend.routing.dtos.*;
|
||||||
|
import SuMoC.backend.trip.Modality;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
public class AlternativeRoutingServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private AlternativeFilterService alternativeFilterService;
|
||||||
|
|
||||||
|
@Mock(lenient = true)
|
||||||
|
private OnCallRoutingProperties onCallRoutingProperties;
|
||||||
|
|
||||||
|
@Mock(lenient = true)
|
||||||
|
private AdHocRoutingProperties adHocRoutingProperties;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private DirectionsService directionsService;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private AlternativeRoutingService service;
|
||||||
|
|
||||||
|
private RoutingAlternativeRequestDTO request;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
request = createRequest(true, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- determineAlternativeRoutesOnUserRequest ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void determineOnUserRequest_AllFiltersAppliedWithOnCallProperties() {
|
||||||
|
List<RouteDTO> routes = List.of(RouteDTO.getMockRouteDTO(), RouteDTO.getMockRouteDTO());
|
||||||
|
when(directionsService.getPossibleAlternativeRoutes(request)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForAdditionalTravelTime(request, routes, onCallRoutingProperties)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForInefficientTransitRoutes(routes)).thenReturn(routes);
|
||||||
|
|
||||||
|
List<RouteDTO> result = service.determineAlternativeRoutesOnUserRequest(request);
|
||||||
|
|
||||||
|
assertEquals(2, result.size());
|
||||||
|
verify(directionsService).getPossibleAlternativeRoutes(request);
|
||||||
|
verify(alternativeFilterService).filterForAdditionalTravelTime(request, routes, onCallRoutingProperties);
|
||||||
|
verify(alternativeFilterService).filterForInefficientTransitRoutes(routes);
|
||||||
|
verify(alternativeFilterService, never()).filterForBadWeather(any(), any(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- determineAlternativeRoutesAdHoc ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void determineAdHoc_WeatherEnabled_WeatherFilterApplied() {
|
||||||
|
RoutingAlternativeRequestDTO req = createRequest(true, false);
|
||||||
|
List<RouteDTO> routes = List.of(RouteDTO.getMockRouteDTO());
|
||||||
|
when(directionsService.getPossibleAlternativeRoutes(req)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForAdditionalTravelTime(req, routes, adHocRoutingProperties)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForBadWeather(req, routes, adHocRoutingProperties)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForInefficientTransitRoutes(routes)).thenReturn(routes);
|
||||||
|
|
||||||
|
List<RouteDTO> result = service.determineAlternativeRoutesAdHoc(req);
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
verify(alternativeFilterService).filterForBadWeather(req, routes, adHocRoutingProperties);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void determineAdHoc_WeatherDisabled_WeatherFilterSkipped() {
|
||||||
|
RoutingAlternativeRequestDTO req = createRequest(false, false);
|
||||||
|
List<RouteDTO> routes = List.of(RouteDTO.getMockRouteDTO());
|
||||||
|
when(directionsService.getPossibleAlternativeRoutes(req)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForAdditionalTravelTime(req, routes, adHocRoutingProperties)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForInefficientTransitRoutes(routes)).thenReturn(routes);
|
||||||
|
|
||||||
|
service.determineAlternativeRoutesAdHoc(req);
|
||||||
|
|
||||||
|
verify(alternativeFilterService, never()).filterForBadWeather(any(), any(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void determineAdHoc_EmptyAfterFiltering_EmptyList() {
|
||||||
|
RoutingAlternativeRequestDTO req = createRequest(false, false);
|
||||||
|
List<RouteDTO> routes = List.of(RouteDTO.getMockRouteDTO());
|
||||||
|
when(directionsService.getPossibleAlternativeRoutes(req)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForAdditionalTravelTime(req, routes, adHocRoutingProperties)).thenReturn(List.of());
|
||||||
|
when(alternativeFilterService.filterForInefficientTransitRoutes(List.of())).thenReturn(List.of());
|
||||||
|
|
||||||
|
List<RouteDTO> result = service.determineAlternativeRoutesAdHoc(req);
|
||||||
|
|
||||||
|
assertTrue(result.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- determineBestAlternativeRouteForRegularTrip ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void determineBestForRegularTrip_PreferPhysical_PhysicalExists_ReturnsFastestPhysical() {
|
||||||
|
RoutingAlternativeRequestDTO req = createRequest(true, true);
|
||||||
|
RouteDTO physical1200 = createPhysicalRoute(1200);
|
||||||
|
RouteDTO physical1800 = createPhysicalRoute(1800);
|
||||||
|
RouteDTO nonPhysical900 = createNonPhysicalRoute(900);
|
||||||
|
List<RouteDTO> routes = List.of(physical1200, physical1800, nonPhysical900);
|
||||||
|
|
||||||
|
stubFiltersPassThrough(req, routes);
|
||||||
|
|
||||||
|
RouteDTO result = service.determineBestAlternativeRouteForRegularTrip(req);
|
||||||
|
|
||||||
|
assertEquals(physical1200, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void determineBestForRegularTrip_PreferPhysical_NoPhysical_ReturnsFastestOverall() {
|
||||||
|
RoutingAlternativeRequestDTO req = createRequest(true, true);
|
||||||
|
RouteDTO nonPhysical1000 = createNonPhysicalRoute(1000);
|
||||||
|
RouteDTO nonPhysical2000 = createNonPhysicalRoute(2000);
|
||||||
|
List<RouteDTO> routes = List.of(nonPhysical1000, nonPhysical2000);
|
||||||
|
|
||||||
|
stubFiltersPassThrough(req, routes);
|
||||||
|
|
||||||
|
RouteDTO result = service.determineBestAlternativeRouteForRegularTrip(req);
|
||||||
|
|
||||||
|
assertEquals(nonPhysical1000, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void determineBestForRegularTrip_NoPhysicalPref_ReturnsFastestOverall() {
|
||||||
|
RoutingAlternativeRequestDTO req = createRequest(true, false);
|
||||||
|
RouteDTO physical800 = createPhysicalRoute(800);
|
||||||
|
RouteDTO nonPhysical1200 = createNonPhysicalRoute(1200);
|
||||||
|
List<RouteDTO> routes = List.of(physical800, nonPhysical1200);
|
||||||
|
|
||||||
|
stubFiltersPassThrough(req, routes);
|
||||||
|
|
||||||
|
RouteDTO result = service.determineBestAlternativeRouteForRegularTrip(req);
|
||||||
|
|
||||||
|
assertEquals(physical800, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void determineBestForRegularTrip_NoRoutes_ReturnsNull() {
|
||||||
|
RoutingAlternativeRequestDTO req = createRequest(true, false);
|
||||||
|
when(directionsService.getPossibleAlternativeRoutes(req)).thenReturn(List.of());
|
||||||
|
when(alternativeFilterService.filterForAdditionalTravelTime(req, List.of(), adHocRoutingProperties)).thenReturn(List.of());
|
||||||
|
when(alternativeFilterService.filterForInefficientTransitRoutes(List.of())).thenReturn(List.of());
|
||||||
|
|
||||||
|
RouteDTO result = service.determineBestAlternativeRouteForRegularTrip(req);
|
||||||
|
|
||||||
|
assertNull(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void determineBestForRegularTrip_WeatherEnabled_WeatherFilterApplied() {
|
||||||
|
RoutingAlternativeRequestDTO req = createRequest(true, false);
|
||||||
|
List<RouteDTO> routes = List.of(createNonPhysicalRoute(1000));
|
||||||
|
stubFiltersPassThrough(req, routes);
|
||||||
|
when(alternativeFilterService.filterForBadWeather(req, routes, adHocRoutingProperties)).thenReturn(routes);
|
||||||
|
|
||||||
|
service.determineBestAlternativeRouteForRegularTrip(req);
|
||||||
|
|
||||||
|
verify(alternativeFilterService).filterForBadWeather(req, routes, adHocRoutingProperties);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void determineBestForRegularTrip_WeatherDisabled_WeatherFilterSkipped() {
|
||||||
|
RoutingAlternativeRequestDTO req = createRequest(false, false);
|
||||||
|
List<RouteDTO> routes = List.of(createNonPhysicalRoute(1000));
|
||||||
|
when(directionsService.getPossibleAlternativeRoutes(req)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForAdditionalTravelTime(req, routes, adHocRoutingProperties)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForInefficientTransitRoutes(routes)).thenReturn(routes);
|
||||||
|
|
||||||
|
service.determineBestAlternativeRouteForRegularTrip(req);
|
||||||
|
|
||||||
|
verify(alternativeFilterService, never()).filterForBadWeather(any(), any(), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- helpers ---
|
||||||
|
|
||||||
|
private RoutingAlternativeRequestDTO createRequest(boolean considerWeather, boolean preferPhysical) {
|
||||||
|
RoutingPreferencesDTO preferences = new RoutingPreferencesDTO();
|
||||||
|
preferences.setConsiderWeatherConditions(considerWeather);
|
||||||
|
preferences.setPreferPhysicalActivity(preferPhysical);
|
||||||
|
|
||||||
|
return RoutingAlternativeRequestDTO.builder()
|
||||||
|
.originLat(51.44)
|
||||||
|
.originLon(6.98)
|
||||||
|
.destinationLat(51.46)
|
||||||
|
.destinationLon(7.01)
|
||||||
|
.departureTime(Instant.parse("2026-03-12T08:00:00Z"))
|
||||||
|
.arrivalTime(Instant.parse("2026-03-12T09:00:00Z"))
|
||||||
|
.routingPreferencesDTO(preferences)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
private RouteDTO createPhysicalRoute(long durationSeconds) {
|
||||||
|
RouteDTO route = RouteDTO.getMockRouteDTO();
|
||||||
|
route.setStartDateTime(Instant.parse("2026-03-12T08:00:00Z"));
|
||||||
|
route.setEndDateTime(Instant.parse("2026-03-12T08:00:00Z").plusSeconds(durationSeconds));
|
||||||
|
route.setSteps(new ArrayList<>(List.of(new StepDTO(Modality.BICYCLE, 5000f))));
|
||||||
|
return route;
|
||||||
|
}
|
||||||
|
|
||||||
|
private RouteDTO createNonPhysicalRoute(long durationSeconds) {
|
||||||
|
RouteDTO route = RouteDTO.getMockRouteDTO();
|
||||||
|
route.setStartDateTime(Instant.parse("2026-03-12T08:00:00Z"));
|
||||||
|
route.setEndDateTime(Instant.parse("2026-03-12T08:00:00Z").plusSeconds(durationSeconds));
|
||||||
|
route.setSteps(new ArrayList<>(List.of(
|
||||||
|
new StepDTO(Modality.WALKING, 300f),
|
||||||
|
new TransitStepDTO(Modality.BUS, 3000f, "101", "Line", "Start", "End"),
|
||||||
|
new StepDTO(Modality.WALKING, 200f)
|
||||||
|
)));
|
||||||
|
return route;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void stubFiltersPassThrough(RoutingAlternativeRequestDTO req, List<RouteDTO> routes) {
|
||||||
|
when(directionsService.getPossibleAlternativeRoutes(req)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForAdditionalTravelTime(req, routes, adHocRoutingProperties)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForBadWeather(req, routes, adHocRoutingProperties)).thenReturn(routes);
|
||||||
|
when(alternativeFilterService.filterForInefficientTransitRoutes(routes)).thenReturn(routes);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
package SuMoC.backend.security;
|
||||||
|
|
||||||
|
import SuMoC.backend.notification.services.EmailService;
|
||||||
|
import SuMoC.backend.security.dtos.*;
|
||||||
|
import SuMoC.backend.security.enums.RegistrationStatus;
|
||||||
|
import SuMoC.backend.security.repository.PasswordResetTokenRepository;
|
||||||
|
import SuMoC.backend.security.services.AuthenticationService;
|
||||||
|
import SuMoC.backend.security.services.TokenService;
|
||||||
|
import SuMoC.backend.user.mapper.UserMapper;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.mail.MailSendException;
|
||||||
|
import org.springframework.security.authentication.AuthenticationManager;
|
||||||
|
import org.springframework.security.authentication.BadCredentialsException;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
|
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.anyString;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
public class AuthenticationServiceUnitTest {
|
||||||
|
|
||||||
|
@Mock private UserRepository userRepository;
|
||||||
|
@Mock private PasswordEncoder passwordEncoder;
|
||||||
|
@Mock private AuthenticationManager authenticationManager;
|
||||||
|
@Mock private TokenService tokenService;
|
||||||
|
@Mock private UserMapper userMapper;
|
||||||
|
@Mock private PasswordResetTokenRepository passwordResetTokenRepository;
|
||||||
|
@Mock private EmailService emailService;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private AuthenticationService authenticationService;
|
||||||
|
|
||||||
|
// registerUser -> catch (IllegalArgumentException)
|
||||||
|
@Test
|
||||||
|
public void testRegisterUser_IllegalArgumentException_ReturnsUnknownError() {
|
||||||
|
UserRegistrationDTO dto = new UserRegistrationDTO(
|
||||||
|
"publicName", "privateName", "valid@test.de", "validPassword123"
|
||||||
|
);
|
||||||
|
|
||||||
|
when(userRepository.existsByEmail(anyString())).thenReturn(false);
|
||||||
|
when(userRepository.existsByPublicName(anyString())).thenReturn(false);
|
||||||
|
when(passwordEncoder.encode(anyString()))
|
||||||
|
.thenThrow(new IllegalArgumentException("Simulated encoding error"));
|
||||||
|
|
||||||
|
RegistrationResponseDTO response = authenticationService.registerUser(dto);
|
||||||
|
|
||||||
|
assertEquals(RegistrationStatus.UNKNOWN_ERROR, response.getStatus());
|
||||||
|
assertNull(response.getUserDTO());
|
||||||
|
assertNull(response.getJwt());
|
||||||
|
}
|
||||||
|
|
||||||
|
// login -> catch (AuthenticationException) -> leeres LoginResponseDTO
|
||||||
|
@Test
|
||||||
|
public void testLogin_AuthenticationException_ReturnsEmptyResponse() {
|
||||||
|
UserAuthenticationPairDTO dto = new UserAuthenticationPairDTO("test@test.de", "wrongPassword");
|
||||||
|
|
||||||
|
when(authenticationManager.authenticate(any()))
|
||||||
|
.thenThrow(new BadCredentialsException("Bad credentials"));
|
||||||
|
|
||||||
|
LoginResponseDTO response = authenticationService.login(dto);
|
||||||
|
|
||||||
|
assertNotNull(response);
|
||||||
|
assertNull(response.getUserDTO());
|
||||||
|
assertEquals("", response.getJwt());
|
||||||
|
}
|
||||||
|
|
||||||
|
// login -> catch (RuntimeException) -> leeres LoginResponseDTO
|
||||||
|
// z.B. wenn userRepository.findByEmail() nach erfolgreichem Auth fehlschlägt
|
||||||
|
@Test
|
||||||
|
public void testLogin_RuntimeException_ReturnsEmptyResponse() {
|
||||||
|
UserAuthenticationPairDTO dto = new UserAuthenticationPairDTO("test@test.de", "validPassword123");
|
||||||
|
|
||||||
|
when(authenticationManager.authenticate(any())).thenReturn(null);
|
||||||
|
when(userRepository.findByEmail(anyString()))
|
||||||
|
.thenThrow(new RuntimeException("DB connection lost"));
|
||||||
|
|
||||||
|
LoginResponseDTO response = authenticationService.login(dto);
|
||||||
|
|
||||||
|
assertNotNull(response);
|
||||||
|
assertNull(response.getUserDTO());
|
||||||
|
assertEquals("", response.getJwt());
|
||||||
|
}
|
||||||
|
|
||||||
|
// generateNewPasswordResetTokenForUser -> throws MailException
|
||||||
|
@Test
|
||||||
|
public void testGenerateOtp_MailException_Propagates() {
|
||||||
|
String email = "test@test.de";
|
||||||
|
|
||||||
|
when(userRepository.existsByEmail(email)).thenReturn(true);
|
||||||
|
when(passwordResetTokenRepository.findByEmail(email)).thenReturn(Optional.empty());
|
||||||
|
when(passwordEncoder.encode(anyString())).thenReturn("encodedOtp");
|
||||||
|
doThrow(new MailSendException("Mail server down"))
|
||||||
|
.when(emailService).sendPasswordResetEmail(anyString(), anyString());
|
||||||
|
|
||||||
|
// MailException soll propagieren (kein catch im Service)
|
||||||
|
assertThrows(MailSendException.class, () ->
|
||||||
|
authenticationService.generateNewPasswordResetTokenForUser(email)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// generateNewPasswordResetTokenForUser -> UsernameNotFoundException
|
||||||
|
@Test
|
||||||
|
public void testGenerateOtp_UserNotFound_ThrowsUsernameNotFoundException() {
|
||||||
|
when(userRepository.existsByEmail(anyString())).thenReturn(false);
|
||||||
|
|
||||||
|
assertThrows(UsernameNotFoundException.class, () ->
|
||||||
|
authenticationService.generateNewPasswordResetTokenForUser("ghost@test.de")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import SuMoC.backend.notification.services.EmailService;
|
|||||||
import SuMoC.backend.security.dtos.*;
|
import SuMoC.backend.security.dtos.*;
|
||||||
import SuMoC.backend.security.enums.RegistrationStatus;
|
import SuMoC.backend.security.enums.RegistrationStatus;
|
||||||
import SuMoC.backend.security.exceptions.InvalidTokenException;
|
import SuMoC.backend.security.exceptions.InvalidTokenException;
|
||||||
|
import SuMoC.backend.security.models.PasswordResetToken;
|
||||||
import SuMoC.backend.security.repository.PasswordResetTokenRepository;
|
import SuMoC.backend.security.repository.PasswordResetTokenRepository;
|
||||||
import SuMoC.backend.security.services.AuthenticationService;
|
import SuMoC.backend.security.services.AuthenticationService;
|
||||||
|
|
||||||
@@ -23,14 +24,17 @@ import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
|
|||||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.springframework.mail.javamail.JavaMailSender;
|
import org.springframework.mail.javamail.JavaMailSender;
|
||||||
|
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
import org.springframework.test.context.bean.override.mockito.MockitoBean;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
|
|
||||||
import static SuMoC.backend.Factories.UserTestFactory.*;
|
import static SuMoC.backend.Factories.UserTestFactory.*;
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
import static org.mockito.Mockito.times;
|
import static org.mockito.Mockito.times;
|
||||||
import static org.mockito.Mockito.verify;
|
import static org.mockito.Mockito.verify;
|
||||||
@@ -157,6 +161,22 @@ public class AuthentificationServiceTest {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testRegistration_InvalidPassword() {
|
||||||
|
User user = validUser();
|
||||||
|
UserRegistrationDTO dto = getUserRegistrationDTO(user);
|
||||||
|
UserRegistrationDTO shortPwDto = new UserRegistrationDTO(
|
||||||
|
dto.getPublicName(), dto.getPrivateName(), dto.getEmail(), "abc"
|
||||||
|
);
|
||||||
|
|
||||||
|
RegistrationResponseDTO response = authenticationService.registerUser(shortPwDto);
|
||||||
|
|
||||||
|
assertEquals(RegistrationStatus.PASSWORD_INVALID, response.getStatus());
|
||||||
|
assertNull(response.getUserDTO());
|
||||||
|
assertNull(response.getJwt());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testRegistrationSuccessful() {
|
public void testRegistrationSuccessful() {
|
||||||
User user = validUser();
|
User user = validUser();
|
||||||
@@ -320,4 +340,67 @@ public class AuthentificationServiceTest {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testGenerateOtp_DeletesExistingToken() {
|
||||||
|
User user = validUser();
|
||||||
|
authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||||
|
String email = user.getEmail();
|
||||||
|
|
||||||
|
authenticationService.generateNewPasswordResetTokenForUser(email);
|
||||||
|
authenticationService.generateNewPasswordResetTokenForUser(email);
|
||||||
|
|
||||||
|
long tokenCount = passwordResetTokenRepository.findAll()
|
||||||
|
.stream()
|
||||||
|
.filter(t -> t.getEmail().equals(email))
|
||||||
|
.count();
|
||||||
|
assertEquals(1, tokenCount);
|
||||||
|
verify(emailService, times(2)).sendPasswordResetEmail(eq(email), any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testResetPassword_ExpiredToken() {
|
||||||
|
User user = validUser();
|
||||||
|
authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||||
|
String email = user.getEmail();
|
||||||
|
|
||||||
|
authenticationService.generateNewPasswordResetTokenForUser(email);
|
||||||
|
ArgumentCaptor<String> otpCaptor = ArgumentCaptor.forClass(String.class);
|
||||||
|
verify(emailService).sendPasswordResetEmail(eq(email), otpCaptor.capture());
|
||||||
|
|
||||||
|
// Query necessary to set back time manually
|
||||||
|
entityManager.createNativeQuery(
|
||||||
|
"UPDATE one_time_password_tokens SET expiry_date = :expired WHERE email = :email"
|
||||||
|
)
|
||||||
|
.setParameter("expired", LocalDateTime.now().minusMinutes(1))
|
||||||
|
.setParameter("email", email)
|
||||||
|
.executeUpdate();
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
assertThrows(InvalidTokenException.class, () ->
|
||||||
|
authenticationService.resetPassword(new PasswordResetDTO(otpCaptor.getValue(), email, "NewValidPassword"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testResetPassword_UserDeleted() {
|
||||||
|
User user = validUser();
|
||||||
|
authenticationService.registerUser(getUserRegistrationDTO(user));
|
||||||
|
String email = user.getEmail();
|
||||||
|
|
||||||
|
authenticationService.generateNewPasswordResetTokenForUser(email);
|
||||||
|
ArgumentCaptor<String> otpCaptor = ArgumentCaptor.forClass(String.class);
|
||||||
|
verify(emailService).sendPasswordResetEmail(eq(email), otpCaptor.capture());
|
||||||
|
|
||||||
|
userRepository.deleteAll();
|
||||||
|
entityManager.flush();
|
||||||
|
entityManager.clear();
|
||||||
|
|
||||||
|
assertThrows(UsernameNotFoundException.class, () ->
|
||||||
|
authenticationService.resetPassword(new PasswordResetDTO(otpCaptor.getValue(), email, "NewValidPassword2026"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
package SuMoC.backend.security;
|
||||||
|
|
||||||
|
import SuMoC.backend.security.utils.KeyGeneratorUtility;
|
||||||
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
|
import jakarta.transaction.Transactional;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
|
import java.security.KeyPair;
|
||||||
|
import java.security.interfaces.RSAPrivateKey;
|
||||||
|
import java.security.interfaces.RSAPublicKey;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
@Transactional
|
||||||
|
public class KeyGeneratorUtilityTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private UserRepository userRepository;
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void tearDown() {
|
||||||
|
userRepository.deleteAll();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void generateRsaKey_returnValidKeyPair() {
|
||||||
|
KeyPair keyPair = KeyGeneratorUtility.generateRsaKey();
|
||||||
|
|
||||||
|
assertNotNull(keyPair);
|
||||||
|
assertNotNull(keyPair.getPublic());
|
||||||
|
assertNotNull(keyPair.getPrivate());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void generateRsaKey_return2048BitKeys() {
|
||||||
|
KeyPair keyPair = KeyGeneratorUtility.generateRsaKey();
|
||||||
|
|
||||||
|
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
|
||||||
|
assertEquals(2048, publicKey.getModulus().bitLength());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void generateRsaKey_returnRsaKeyType() {
|
||||||
|
KeyPair keyPair = KeyGeneratorUtility.generateRsaKey();
|
||||||
|
|
||||||
|
assertInstanceOf(RSAPublicKey.class, keyPair.getPublic());
|
||||||
|
assertInstanceOf(RSAPrivateKey.class, keyPair.getPrivate());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void generateRsaKey_returnDifferentKeysOnEachCall() {
|
||||||
|
KeyPair keyPair1 = KeyGeneratorUtility.generateRsaKey();
|
||||||
|
KeyPair keyPair2 = KeyGeneratorUtility.generateRsaKey();
|
||||||
|
|
||||||
|
assertNotEquals(keyPair1.getPublic(), keyPair2.getPublic());
|
||||||
|
assertNotEquals(keyPair1.getPrivate(), keyPair2.getPrivate());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
package SuMoC.backend.security;
|
||||||
|
|
||||||
|
import SuMoC.backend.security.utils.RSAKeyProperties;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.security.interfaces.RSAPrivateKey;
|
||||||
|
import java.security.interfaces.RSAPublicKey;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
public class RSAKeyPropertiesTest {
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
Path tempDir;
|
||||||
|
|
||||||
|
private String pubKeyPath() { return tempDir.resolve("public.pem").toString(); }
|
||||||
|
private String privKeyPath() { return tempDir.resolve("private.pem").toString(); }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructor_generatesAndPersistsKeys_whenFilesDoNotExist() {
|
||||||
|
RSAKeyProperties props = new RSAKeyProperties(pubKeyPath(), privKeyPath());
|
||||||
|
|
||||||
|
assertNotNull(props.getPublicKey());
|
||||||
|
assertNotNull(props.getPrivateKey());
|
||||||
|
assertInstanceOf(RSAPublicKey.class, props.getPublicKey());
|
||||||
|
assertInstanceOf(RSAPrivateKey.class, props.getPrivateKey());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructor_loadsExistingKeys_whenFilesExist() throws IOException {
|
||||||
|
RSAKeyProperties first = new RSAKeyProperties(pubKeyPath(), privKeyPath());
|
||||||
|
|
||||||
|
RSAKeyProperties second = new RSAKeyProperties(pubKeyPath(), privKeyPath());
|
||||||
|
|
||||||
|
assertEquals(
|
||||||
|
first.getPublicKey().getModulus(),
|
||||||
|
second.getPublicKey().getModulus()
|
||||||
|
);
|
||||||
|
assertEquals(
|
||||||
|
first.getPrivateKey().getModulus(),
|
||||||
|
second.getPrivateKey().getModulus()
|
||||||
|
);
|
||||||
|
|
||||||
|
Path onlyPub = tempDir.resolve("onlypub");
|
||||||
|
String pub2 = onlyPub.resolve("public.pem").toString();
|
||||||
|
String priv2 = onlyPub.resolve("private.pem").toString();
|
||||||
|
|
||||||
|
RSAKeyProperties onlyPubProps = new RSAKeyProperties(pub2, priv2);
|
||||||
|
Files.delete(Paths.get(priv2));
|
||||||
|
|
||||||
|
RSAKeyProperties mixed = new RSAKeyProperties(pub2, priv2);
|
||||||
|
assertNotNull(mixed.getPublicKey());
|
||||||
|
assertNotNull(mixed.getPrivateKey());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructor_generatesDifferentKeys_forDifferentDirs() {
|
||||||
|
Path otherDir = tempDir.resolve("other");
|
||||||
|
String otherPub = otherDir.resolve("public.pem").toString();
|
||||||
|
String otherPriv = otherDir.resolve("private.pem").toString();
|
||||||
|
|
||||||
|
RSAKeyProperties first = new RSAKeyProperties(pubKeyPath(), privKeyPath());
|
||||||
|
RSAKeyProperties second = new RSAKeyProperties(otherPub, otherPriv);
|
||||||
|
|
||||||
|
assertNotEquals(
|
||||||
|
first.getPublicKey().getModulus(),
|
||||||
|
second.getPublicKey().getModulus()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructor_throwsIllegalStateException_onInvalidPath() {
|
||||||
|
assertThrows(IllegalStateException.class,
|
||||||
|
() -> new RSAKeyProperties("/invalid\0path/pub.pem", "/invalid\0path/priv.pem")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void constructor_throwsIllegalStateException_whenDirectoryNotWritable() throws Exception {
|
||||||
|
Path readOnlyDir = tempDir.resolve("readonly");
|
||||||
|
Files.createDirectories(readOnlyDir);
|
||||||
|
readOnlyDir.toFile().setWritable(false);
|
||||||
|
|
||||||
|
String pub = readOnlyDir.resolve("public.pem").toString();
|
||||||
|
String priv = readOnlyDir.resolve("private.pem").toString();
|
||||||
|
|
||||||
|
try {
|
||||||
|
assertThrows(IllegalStateException.class,
|
||||||
|
() -> new RSAKeyProperties(pub, priv)
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
readOnlyDir.toFile().setWritable(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
package SuMoC.backend.suggestion.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.carrousel.service.CarrouselService;
|
||||||
|
import SuMoC.backend.notification.enums.NotificationType;
|
||||||
|
import SuMoC.backend.notification.services.NotificationSchedulerService;
|
||||||
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.StepDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.TransitStepDTO;
|
||||||
|
import SuMoC.backend.routing.services.AlternativeRoutingService;
|
||||||
|
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||||
|
import SuMoC.backend.suggestion.config.AdHocSuggestionProperties;
|
||||||
|
import SuMoC.backend.trip.Modality;
|
||||||
|
import SuMoC.backend.trip.models.Trip;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Captor;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
public class AdHocSuggestionServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private AlternativeRoutingService alternativeRoutingService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private RoutingPreferencesService routingPreferencesService;
|
||||||
|
|
||||||
|
@Mock(lenient = true)
|
||||||
|
private AdHocSuggestionProperties adHocSuggestionProperties;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private NotificationSchedulerService notificationSchedulerService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private CarrouselService carrouselService;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private AdHocSuggestionService service;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<List<RouteDTO>> routeListCaptor;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
when(adHocSuggestionProperties.getRecentTripThresholdSeconds()).thenReturn(6 * 60 * 60); // 6 hours
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- early exits ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_OldTrip_ReturnsImmediately() {
|
||||||
|
Trip trip = createTrip(Modality.CAR, Instant.now().minusSeconds(7 * 60 * 60));
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verifyNoInteractions(alternativeRoutingService, notificationSchedulerService, carrouselService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_BicycleTrip_ReturnsImmediately() {
|
||||||
|
Trip trip = createTrip(Modality.BICYCLE, Instant.now().minusSeconds(60));
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verifyNoInteractions(alternativeRoutingService);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_WalkingTrip_ReturnsImmediately() {
|
||||||
|
Trip trip = createTrip(Modality.WALKING, Instant.now().minusSeconds(60));
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verifyNoInteractions(alternativeRoutingService);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- no alternatives ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_CarTrip_NoAlternatives_NoNotification() {
|
||||||
|
Trip trip = createRecentCarTrip();
|
||||||
|
stubPreferences(false);
|
||||||
|
when(alternativeRoutingService.determineAlternativeRoutesAdHoc(any())).thenReturn(List.of());
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verifyNoInteractions(notificationSchedulerService, carrouselService);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- pickBestAlternatives ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_CarTrip_NoPhysicalPref_PicksFastestOnly() {
|
||||||
|
Trip trip = createRecentCarTrip();
|
||||||
|
RoutingPreferencesDTO prefs = stubPreferences(false);
|
||||||
|
RouteDTO fast = createNonPhysicalRoute(1800);
|
||||||
|
RouteDTO slow = createNonPhysicalRoute(2400);
|
||||||
|
when(alternativeRoutingService.determineAlternativeRoutesAdHoc(any())).thenReturn(List.of(fast, slow));
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenReturn(prefs);
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verify(carrouselService).addAdHocTripCandidates(eq(trip), routeListCaptor.capture());
|
||||||
|
List<RouteDTO> bestAlternatives = routeListCaptor.getValue();
|
||||||
|
assertEquals(1, bestAlternatives.size());
|
||||||
|
assertEquals(fast, bestAlternatives.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_CarTrip_PhysicalPref_HasPhysicalRoutes_PicksTwo() {
|
||||||
|
Trip trip = createRecentCarTrip();
|
||||||
|
RoutingPreferencesDTO prefs = stubPreferences(true);
|
||||||
|
RouteDTO physical = createPhysicalRoute(2000);
|
||||||
|
RouteDTO nonPhysical = createNonPhysicalRoute(1500);
|
||||||
|
when(alternativeRoutingService.determineAlternativeRoutesAdHoc(any())).thenReturn(List.of(physical, nonPhysical));
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenReturn(prefs);
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verify(carrouselService).addAdHocTripCandidates(eq(trip), routeListCaptor.capture());
|
||||||
|
List<RouteDTO> bestAlternatives = routeListCaptor.getValue();
|
||||||
|
assertEquals(2, bestAlternatives.size());
|
||||||
|
assertTrue(bestAlternatives.contains(physical));
|
||||||
|
assertTrue(bestAlternatives.contains(nonPhysical));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_CarTrip_PhysicalPref_FastestPhysicalIsFastest_PicksOne() {
|
||||||
|
Trip trip = createRecentCarTrip();
|
||||||
|
RoutingPreferencesDTO prefs = stubPreferences(true);
|
||||||
|
RouteDTO physical = createPhysicalRoute(1200);
|
||||||
|
RouteDTO nonPhysical = createNonPhysicalRoute(1800);
|
||||||
|
when(alternativeRoutingService.determineAlternativeRoutesAdHoc(any())).thenReturn(List.of(physical, nonPhysical));
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenReturn(prefs);
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verify(carrouselService).addAdHocTripCandidates(eq(trip), routeListCaptor.capture());
|
||||||
|
List<RouteDTO> bestAlternatives = routeListCaptor.getValue();
|
||||||
|
assertEquals(1, bestAlternatives.size());
|
||||||
|
assertEquals(physical, bestAlternatives.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_CarTrip_PhysicalPref_NoPhysicalRoutes_PicksFastestOnly() {
|
||||||
|
Trip trip = createRecentCarTrip();
|
||||||
|
RoutingPreferencesDTO prefs = stubPreferences(true);
|
||||||
|
RouteDTO fast = createNonPhysicalRoute(1500);
|
||||||
|
RouteDTO slow = createNonPhysicalRoute(2000);
|
||||||
|
when(alternativeRoutingService.determineAlternativeRoutesAdHoc(any())).thenReturn(List.of(fast, slow));
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenReturn(prefs);
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verify(carrouselService).addAdHocTripCandidates(eq(trip), routeListCaptor.capture());
|
||||||
|
List<RouteDTO> bestAlternatives = routeListCaptor.getValue();
|
||||||
|
assertEquals(1, bestAlternatives.size());
|
||||||
|
assertEquals(fast, bestAlternatives.get(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- modality triggers ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_MotorcycleTrip_TriggersSuggestion() {
|
||||||
|
Trip trip = createTrip(Modality.MOTORCYCLE, Instant.now().minusSeconds(60));
|
||||||
|
stubPreferences(false);
|
||||||
|
when(alternativeRoutingService.determineAlternativeRoutesAdHoc(any())).thenReturn(List.of());
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verify(alternativeRoutingService).determineAlternativeRoutesAdHoc(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_TaxiTrip_TriggersSuggestion() {
|
||||||
|
Trip trip = createTrip(Modality.TAXI, Instant.now().minusSeconds(60));
|
||||||
|
stubPreferences(false);
|
||||||
|
when(alternativeRoutingService.determineAlternativeRoutesAdHoc(any())).thenReturn(List.of());
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verify(alternativeRoutingService).determineAlternativeRoutesAdHoc(any());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- verify notification scheduling ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkNewTrip_CarTrip_VerifiesNotificationCalledWithCorrectArgs() {
|
||||||
|
Trip trip = createRecentCarTrip();
|
||||||
|
RoutingPreferencesDTO prefs = stubPreferences(false);
|
||||||
|
RouteDTO route = createNonPhysicalRoute(1800);
|
||||||
|
when(alternativeRoutingService.determineAlternativeRoutesAdHoc(any())).thenReturn(List.of(route));
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenReturn(prefs);
|
||||||
|
|
||||||
|
service.checkNewTripForNotifiedAlternativeSuggestion(trip);
|
||||||
|
|
||||||
|
verify(notificationSchedulerService).schedule(
|
||||||
|
eq(1L),
|
||||||
|
routeListCaptor.capture(),
|
||||||
|
eq(NotificationType.ADHOC_ALTERNATIVE),
|
||||||
|
any(LocalTime.class)
|
||||||
|
);
|
||||||
|
assertEquals(1, routeListCaptor.getValue().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- helpers ---
|
||||||
|
|
||||||
|
private Trip createTrip(Modality modality, Instant endTime) {
|
||||||
|
User user = new User();
|
||||||
|
user.setId(1L);
|
||||||
|
Trip trip = new Trip();
|
||||||
|
trip.setId(1L);
|
||||||
|
trip.setUser(user);
|
||||||
|
trip.setMainModality(modality);
|
||||||
|
trip.setStartTime(endTime.minusSeconds(1800));
|
||||||
|
trip.setEndTime(endTime);
|
||||||
|
trip.setStartLatitude(51.44);
|
||||||
|
trip.setStartLongitude(6.98);
|
||||||
|
trip.setEndLatitude(51.46);
|
||||||
|
trip.setEndLongitude(7.01);
|
||||||
|
return trip;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Trip createRecentCarTrip() {
|
||||||
|
return createTrip(Modality.CAR, Instant.now().minusSeconds(60));
|
||||||
|
}
|
||||||
|
|
||||||
|
private RoutingPreferencesDTO stubPreferences(boolean preferPhysical) {
|
||||||
|
RoutingPreferencesDTO prefs = new RoutingPreferencesDTO();
|
||||||
|
prefs.setPreferPhysicalActivity(preferPhysical);
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenReturn(prefs);
|
||||||
|
return prefs;
|
||||||
|
}
|
||||||
|
|
||||||
|
private RouteDTO createPhysicalRoute(long durationSeconds) {
|
||||||
|
RouteDTO route = RouteDTO.getMockRouteDTO();
|
||||||
|
route.setStartDateTime(Instant.parse("2026-03-12T08:00:00Z"));
|
||||||
|
route.setEndDateTime(Instant.parse("2026-03-12T08:00:00Z").plusSeconds(durationSeconds));
|
||||||
|
route.setSteps(new ArrayList<>(List.of(new StepDTO(Modality.BICYCLE, 5000f))));
|
||||||
|
return route;
|
||||||
|
}
|
||||||
|
|
||||||
|
private RouteDTO createNonPhysicalRoute(long durationSeconds) {
|
||||||
|
RouteDTO route = RouteDTO.getMockRouteDTO();
|
||||||
|
route.setStartDateTime(Instant.parse("2026-03-12T08:00:00Z"));
|
||||||
|
route.setEndDateTime(Instant.parse("2026-03-12T08:00:00Z").plusSeconds(durationSeconds));
|
||||||
|
route.setSteps(new ArrayList<>(List.of(
|
||||||
|
new StepDTO(Modality.WALKING, 300f),
|
||||||
|
new TransitStepDTO(Modality.BUS, 3000f, "101", "Line", "Start", "End"),
|
||||||
|
new StepDTO(Modality.WALKING, 200f)
|
||||||
|
)));
|
||||||
|
return route;
|
||||||
|
}
|
||||||
|
}
|
||||||
+267
@@ -0,0 +1,267 @@
|
|||||||
|
package SuMoC.backend.suggestion.services;
|
||||||
|
|
||||||
|
import SuMoC.backend.carrousel.models.CarrouselCandidate;
|
||||||
|
import SuMoC.backend.carrousel.repository.CarrouselCandidateRepository;
|
||||||
|
import SuMoC.backend.carrousel.service.CarrouselService;
|
||||||
|
import SuMoC.backend.h3.H3Service;
|
||||||
|
import SuMoC.backend.notification.enums.NotificationType;
|
||||||
|
import SuMoC.backend.notification.interfaces.NotifieableWithTime;
|
||||||
|
import SuMoC.backend.notification.services.NotificationSchedulerService;
|
||||||
|
import SuMoC.backend.regulartrip.dtos.DetectedRegularTripDTO;
|
||||||
|
import SuMoC.backend.regulartrip.services.RegularTripDetectionService;
|
||||||
|
import SuMoC.backend.routing.dtos.RouteDTO;
|
||||||
|
import SuMoC.backend.routing.dtos.RoutingPreferencesDTO;
|
||||||
|
import SuMoC.backend.routing.services.AlternativeRoutingService;
|
||||||
|
import SuMoC.backend.routing.services.RoutingPreferencesService;
|
||||||
|
import SuMoC.backend.suggestion.config.RegularTripSuggestionProperties;
|
||||||
|
import SuMoC.backend.trip.Modality;
|
||||||
|
import SuMoC.backend.trip.dtos.RegularTripDetectionDTO;
|
||||||
|
import com.uber.h3core.util.LatLng;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.ArgumentCaptor;
|
||||||
|
import org.mockito.Captor;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
|
||||||
|
import java.time.DayOfWeek;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.util.Collection;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
public class RegularTripSuggestionServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private AlternativeRoutingService alternativeRoutingService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private RoutingPreferencesService routingPreferencesService;
|
||||||
|
|
||||||
|
@Mock(lenient = true)
|
||||||
|
private RegularTripSuggestionProperties properties;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private NotificationSchedulerService notificationSchedulerService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private RegularTripDetectionService regularTripDetectionService;
|
||||||
|
|
||||||
|
@Mock(lenient = true)
|
||||||
|
private H3Service h3Service;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private CarrouselService carrouselService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private CarrouselCandidateRepository carrouselCandidateRepository;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<Collection<CarrouselCandidate>> candidateCaptor;
|
||||||
|
|
||||||
|
@Captor
|
||||||
|
private ArgumentCaptor<List<NotifieableWithTime>> notificationCaptor;
|
||||||
|
|
||||||
|
private RegularTripSuggestionService service;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
// Synchronous executor for deterministic testing
|
||||||
|
service = new RegularTripSuggestionService(
|
||||||
|
alternativeRoutingService,
|
||||||
|
routingPreferencesService,
|
||||||
|
properties,
|
||||||
|
notificationSchedulerService,
|
||||||
|
regularTripDetectionService,
|
||||||
|
h3Service,
|
||||||
|
carrouselService,
|
||||||
|
carrouselCandidateRepository,
|
||||||
|
Runnable::run // synchronous executor
|
||||||
|
);
|
||||||
|
|
||||||
|
when(properties.getNotifyBeforeMinutes()).thenReturn(15);
|
||||||
|
when(h3Service.cellToLatLng(anyString())).thenReturn(new LatLng(51.44, 6.98));
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- checkAlternativesAndNotify ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkAlternativesAndNotify_EmptyMap_NoSavesNoNotifications() {
|
||||||
|
HashMap<Long, List<DetectedRegularTripDTO>> emptyMap = new HashMap<>();
|
||||||
|
|
||||||
|
service.checkAlternativesAndNotify(emptyMap);
|
||||||
|
|
||||||
|
verify(carrouselCandidateRepository).saveAll(candidateCaptor.capture());
|
||||||
|
verify(notificationSchedulerService).scheduleAll(notificationCaptor.capture(), eq(NotificationType.REGULAR_TRIP_ALTERNATIVE));
|
||||||
|
assertTrue(candidateCaptor.getValue().isEmpty());
|
||||||
|
assertTrue(notificationCaptor.getValue().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkAlternativesAndNotify_SingleUserSingleTrip_AlternativeFound_SavesAndSchedules() {
|
||||||
|
HashMap<Long, List<DetectedRegularTripDTO>> map = new HashMap<>();
|
||||||
|
DetectedRegularTripDTO trip = createDetectedTrip();
|
||||||
|
map.put(1L, List.of(trip));
|
||||||
|
|
||||||
|
RoutingPreferencesDTO prefs = new RoutingPreferencesDTO();
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenReturn(prefs);
|
||||||
|
|
||||||
|
RouteDTO bestRoute = RouteDTO.getMockRouteDTO();
|
||||||
|
when(alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(any())).thenReturn(bestRoute);
|
||||||
|
|
||||||
|
CarrouselCandidate candidate = CarrouselCandidate.builder().userId(1L).build();
|
||||||
|
when(carrouselService.getRegularTripCandidates(eq(1L), eq(trip), any())).thenReturn(List.of(candidate));
|
||||||
|
|
||||||
|
service.checkAlternativesAndNotify(map);
|
||||||
|
|
||||||
|
verify(carrouselCandidateRepository).saveAll(candidateCaptor.capture());
|
||||||
|
verify(notificationSchedulerService).scheduleAll(notificationCaptor.capture(), eq(NotificationType.REGULAR_TRIP_ALTERNATIVE));
|
||||||
|
assertEquals(1, candidateCaptor.getValue().size());
|
||||||
|
assertEquals(1, notificationCaptor.getValue().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkAlternativesAndNotify_SingleUserSingleTrip_NoAlternative_EmptyResults() {
|
||||||
|
HashMap<Long, List<DetectedRegularTripDTO>> map = new HashMap<>();
|
||||||
|
map.put(1L, List.of(createDetectedTrip()));
|
||||||
|
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenReturn(new RoutingPreferencesDTO());
|
||||||
|
when(alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(any())).thenReturn(null);
|
||||||
|
|
||||||
|
service.checkAlternativesAndNotify(map);
|
||||||
|
|
||||||
|
verify(carrouselCandidateRepository).saveAll(candidateCaptor.capture());
|
||||||
|
verify(notificationSchedulerService).scheduleAll(notificationCaptor.capture(), eq(NotificationType.REGULAR_TRIP_ALTERNATIVE));
|
||||||
|
assertTrue(candidateCaptor.getValue().isEmpty());
|
||||||
|
assertTrue(notificationCaptor.getValue().isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkAlternativesAndNotify_MultipleUsers_MixedResults_CorrectAggregation() {
|
||||||
|
HashMap<Long, List<DetectedRegularTripDTO>> map = new HashMap<>();
|
||||||
|
map.put(1L, List.of(createDetectedTrip()));
|
||||||
|
map.put(2L, List.of(createDetectedTrip()));
|
||||||
|
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(anyLong())).thenReturn(new RoutingPreferencesDTO());
|
||||||
|
|
||||||
|
// User 1 gets an alternative, user 2 does not
|
||||||
|
RouteDTO bestRoute = RouteDTO.getMockRouteDTO();
|
||||||
|
when(alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(any()))
|
||||||
|
.thenReturn(bestRoute)
|
||||||
|
.thenReturn(null);
|
||||||
|
|
||||||
|
CarrouselCandidate candidate = CarrouselCandidate.builder().userId(1L).build();
|
||||||
|
when(carrouselService.getRegularTripCandidates(anyLong(), any(), any())).thenReturn(List.of(candidate));
|
||||||
|
|
||||||
|
service.checkAlternativesAndNotify(map);
|
||||||
|
|
||||||
|
verify(carrouselCandidateRepository).saveAll(candidateCaptor.capture());
|
||||||
|
verify(notificationSchedulerService).scheduleAll(notificationCaptor.capture(), eq(NotificationType.REGULAR_TRIP_ALTERNATIVE));
|
||||||
|
assertEquals(1, candidateCaptor.getValue().size());
|
||||||
|
assertEquals(1, notificationCaptor.getValue().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkAlternativesAndNotify_ExceptionInOneUser_OtherUsersStillProcessed() {
|
||||||
|
HashMap<Long, List<DetectedRegularTripDTO>> map = new HashMap<>();
|
||||||
|
map.put(1L, List.of(createDetectedTrip()));
|
||||||
|
map.put(2L, List.of(createDetectedTrip()));
|
||||||
|
|
||||||
|
// User 1 throws, user 2 succeeds
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenThrow(new RuntimeException("DB error"));
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(2L)).thenReturn(new RoutingPreferencesDTO());
|
||||||
|
|
||||||
|
RouteDTO bestRoute = RouteDTO.getMockRouteDTO();
|
||||||
|
when(alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(any())).thenReturn(bestRoute);
|
||||||
|
|
||||||
|
CarrouselCandidate candidate = CarrouselCandidate.builder().userId(2L).build();
|
||||||
|
when(carrouselService.getRegularTripCandidates(eq(2L), any(), any())).thenReturn(List.of(candidate));
|
||||||
|
|
||||||
|
service.checkAlternativesAndNotify(map);
|
||||||
|
|
||||||
|
// Should still save user 2's results despite user 1's exception
|
||||||
|
verify(carrouselCandidateRepository).saveAll(candidateCaptor.capture());
|
||||||
|
verify(notificationSchedulerService).scheduleAll(notificationCaptor.capture(), eq(NotificationType.REGULAR_TRIP_ALTERNATIVE));
|
||||||
|
assertEquals(1, candidateCaptor.getValue().size());
|
||||||
|
assertEquals(1, notificationCaptor.getValue().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkAlternativesAndNotify_NotificationTime_CorrectCalculation() {
|
||||||
|
HashMap<Long, List<DetectedRegularTripDTO>> map = new HashMap<>();
|
||||||
|
DetectedRegularTripDTO trip = createDetectedTrip(); // departureWindowStart = 08:00
|
||||||
|
map.put(1L, List.of(trip));
|
||||||
|
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenReturn(new RoutingPreferencesDTO());
|
||||||
|
RouteDTO bestRoute = RouteDTO.getMockRouteDTO();
|
||||||
|
when(alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(any())).thenReturn(bestRoute);
|
||||||
|
when(carrouselService.getRegularTripCandidates(eq(1L), eq(trip), any())).thenReturn(List.of());
|
||||||
|
|
||||||
|
service.checkAlternativesAndNotify(map);
|
||||||
|
|
||||||
|
verify(notificationSchedulerService).scheduleAll(notificationCaptor.capture(), eq(NotificationType.REGULAR_TRIP_ALTERNATIVE));
|
||||||
|
NotifieableWithTime notification = notificationCaptor.getValue().get(0);
|
||||||
|
// departureWindowStart(08:00) - notifyBeforeMinutes(15) = 07:45
|
||||||
|
assertEquals(LocalTime.of(7, 45), notification.getEarliestTimeOfDayToSend());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void checkAlternativesAndNotify_SingleUserMultipleTrips_EachProcessed() {
|
||||||
|
HashMap<Long, List<DetectedRegularTripDTO>> map = new HashMap<>();
|
||||||
|
map.put(1L, List.of(createDetectedTrip(), createDetectedTrip()));
|
||||||
|
|
||||||
|
when(routingPreferencesService.getUserRoutingPreferences(1L)).thenReturn(new RoutingPreferencesDTO());
|
||||||
|
RouteDTO bestRoute = RouteDTO.getMockRouteDTO();
|
||||||
|
when(alternativeRoutingService.determineBestAlternativeRouteForRegularTrip(any())).thenReturn(bestRoute);
|
||||||
|
|
||||||
|
CarrouselCandidate candidate = CarrouselCandidate.builder().userId(1L).build();
|
||||||
|
when(carrouselService.getRegularTripCandidates(eq(1L), any(), any())).thenReturn(List.of(candidate));
|
||||||
|
|
||||||
|
service.checkAlternativesAndNotify(map);
|
||||||
|
|
||||||
|
verify(alternativeRoutingService, times(2)).determineBestAlternativeRouteForRegularTrip(any());
|
||||||
|
verify(carrouselCandidateRepository).saveAll(candidateCaptor.capture());
|
||||||
|
verify(notificationSchedulerService).scheduleAll(notificationCaptor.capture(), eq(NotificationType.REGULAR_TRIP_ALTERNATIVE));
|
||||||
|
assertEquals(2, candidateCaptor.getValue().size());
|
||||||
|
assertEquals(2, notificationCaptor.getValue().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- helpers ---
|
||||||
|
|
||||||
|
private DetectedRegularTripDTO createDetectedTrip() {
|
||||||
|
Instant start = Instant.parse("2026-03-12T08:00:00Z");
|
||||||
|
Instant end = Instant.parse("2026-03-12T08:40:00Z");
|
||||||
|
|
||||||
|
return DetectedRegularTripDTO.builder()
|
||||||
|
.userId(1L)
|
||||||
|
.modality(Modality.CAR)
|
||||||
|
.dayOfWeek(DayOfWeek.THURSDAY)
|
||||||
|
.departureWindowStart(LocalTime.of(8, 0))
|
||||||
|
.departureWindowEnd(LocalTime.of(8, 15))
|
||||||
|
.arrivalWindowStart(LocalTime.of(8, 30))
|
||||||
|
.arrivalWindowEnd(LocalTime.of(8, 45))
|
||||||
|
.startH3Center("8a1fa535568ffff")
|
||||||
|
.endH3Center("8a1fa535020ffff")
|
||||||
|
.supportingTrips(List.of(
|
||||||
|
RegularTripDetectionDTO.builder()
|
||||||
|
.tripId(100L)
|
||||||
|
.userId(1L)
|
||||||
|
.startH3Cell("8a1fa535568ffff")
|
||||||
|
.endH3Cell("8a1fa535020ffff")
|
||||||
|
.startTime(start)
|
||||||
|
.endTime(end)
|
||||||
|
.mainModality(Modality.CAR)
|
||||||
|
.build()
|
||||||
|
))
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,196 @@
|
|||||||
|
package SuMoC.backend.trip;
|
||||||
|
|
||||||
|
import SuMoC.backend.Factories.TripTestFactory;
|
||||||
|
import SuMoC.backend.trip.dtos.NewTripDTO;
|
||||||
|
import SuMoC.backend.trip.dtos.TripDTO;
|
||||||
|
import SuMoC.backend.trip.models.Trip;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.util.HashSet;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class TripServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private TripRepository tripRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private TripMapper tripMapper;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private TripService tripService;
|
||||||
|
|
||||||
|
private User owner;
|
||||||
|
private User otherUser;
|
||||||
|
private Trip trip;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
owner = new User("Public", "Private", "owner@test.com", "pass");
|
||||||
|
owner.setId(1L);
|
||||||
|
|
||||||
|
otherUser = new User("Other", "OtherPrivate", "other@test.com", "pass");
|
||||||
|
otherUser.setId(2L);
|
||||||
|
|
||||||
|
trip = TripTestFactory.getValidTrip(
|
||||||
|
Instant.parse("2026-03-12T10:00:00Z"),
|
||||||
|
Instant.parse("2026-03-12T11:00:00Z"),
|
||||||
|
owner
|
||||||
|
);
|
||||||
|
trip.setId(1L);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- invalidateTrip ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void invalidateTrip_setsInvalidatedTrue() {
|
||||||
|
when(tripRepository.findById(1L)).thenReturn(Optional.of(trip));
|
||||||
|
|
||||||
|
tripService.invalidateTrip(owner, 1L);
|
||||||
|
|
||||||
|
assertTrue(trip.isInvalidated());
|
||||||
|
verify(tripRepository).save(trip);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void invalidateTrip_throwsNotFoundForUnknownId() {
|
||||||
|
when(tripRepository.findById(99L)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
|
||||||
|
() -> tripService.invalidateTrip(owner, 99L));
|
||||||
|
|
||||||
|
assertEquals(404, ex.getStatusCode().value());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void invalidateTrip_throwsForbiddenForWrongUser() {
|
||||||
|
when(tripRepository.findById(1L)).thenReturn(Optional.of(trip));
|
||||||
|
|
||||||
|
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
|
||||||
|
() -> tripService.invalidateTrip(otherUser, 1L));
|
||||||
|
|
||||||
|
assertEquals(403, ex.getStatusCode().value());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- validateTrip ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateTrip_setsInvalidatedFalse() {
|
||||||
|
trip.setInvalidated(true);
|
||||||
|
when(tripRepository.findById(1L)).thenReturn(Optional.of(trip));
|
||||||
|
|
||||||
|
tripService.validateTrip(owner, 1L);
|
||||||
|
|
||||||
|
assertFalse(trip.isInvalidated());
|
||||||
|
verify(tripRepository).save(trip);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateTrip_throwsNotFoundForUnknownId() {
|
||||||
|
when(tripRepository.findById(99L)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
|
||||||
|
() -> tripService.validateTrip(owner, 99L));
|
||||||
|
|
||||||
|
assertEquals(404, ex.getStatusCode().value());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void validateTrip_throwsForbiddenForWrongUser() {
|
||||||
|
when(tripRepository.findById(1L)).thenReturn(Optional.of(trip));
|
||||||
|
|
||||||
|
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
|
||||||
|
() -> tripService.validateTrip(otherUser, 1L));
|
||||||
|
|
||||||
|
assertEquals(403, ex.getStatusCode().value());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- addTrip ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void addTrip_setsUserAndSaves() {
|
||||||
|
NewTripDTO newTripDTO = mock(NewTripDTO.class);
|
||||||
|
Trip mappedTrip = TripTestFactory.getValidTrip(
|
||||||
|
Instant.parse("2026-03-12T10:00:00Z"),
|
||||||
|
Instant.parse("2026-03-12T11:00:00Z"),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
mappedTrip.setTripSegments(new HashSet<>());
|
||||||
|
|
||||||
|
when(tripMapper.toTrip(newTripDTO)).thenReturn(mappedTrip);
|
||||||
|
when(tripRepository.save(mappedTrip)).thenReturn(mappedTrip);
|
||||||
|
|
||||||
|
Trip result = tripService.addTrip(owner, newTripDTO);
|
||||||
|
|
||||||
|
assertEquals(owner, result.getUser());
|
||||||
|
verify(tripRepository).save(mappedTrip);
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- deleteTrip ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deleteTrip_deletesOwnTrip() {
|
||||||
|
when(tripRepository.findById(1L)).thenReturn(Optional.of(trip));
|
||||||
|
|
||||||
|
tripService.deleteTrip(owner, 1L);
|
||||||
|
|
||||||
|
verify(tripRepository).delete(trip);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deleteTrip_throwsNotFoundForUnknownId() {
|
||||||
|
when(tripRepository.findById(99L)).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
|
||||||
|
() -> tripService.deleteTrip(owner, 99L));
|
||||||
|
|
||||||
|
assertEquals(404, ex.getStatusCode().value());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deleteTrip_throwsForbiddenForWrongUser() {
|
||||||
|
when(tripRepository.findById(1L)).thenReturn(Optional.of(trip));
|
||||||
|
|
||||||
|
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
|
||||||
|
() -> tripService.deleteTrip(otherUser, 1L));
|
||||||
|
|
||||||
|
assertEquals(403, ex.getStatusCode().value());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- getAllTripsOfUser ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAllTripsOfUser_returnsMappedTrips() {
|
||||||
|
List<Trip> trips = List.of(trip);
|
||||||
|
TripDTO tripDTO = mock(TripDTO.class);
|
||||||
|
|
||||||
|
when(tripRepository.findAllByUser(owner)).thenReturn(Optional.of(trips));
|
||||||
|
when(tripMapper.toTripDTOs(trips)).thenReturn(List.of(tripDTO));
|
||||||
|
|
||||||
|
List<TripDTO> result = tripService.getAllTripsOfUser(owner);
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- deleteAllTripsOfUser ---
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void deleteAllTripsOfUser_delegatesToRepository() {
|
||||||
|
tripService.deleteAllTripsOfUser(owner);
|
||||||
|
|
||||||
|
verify(tripRepository).deleteAllByUser(owner);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package SuMoC.backend.user;
|
||||||
|
|
||||||
|
import SuMoC.backend.gamification.Timeframe;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
|
import SuMoC.backend.user.stats.models.Stats;
|
||||||
|
import SuMoC.backend.user.stats.models.StatsList;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.security.test.context.support.WithMockUser;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
|
||||||
|
import static SuMoC.backend.Factories.UserTestFactory.uniqueUser;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
@Transactional
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
public class StatsListTest {
|
||||||
|
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private UserRepository userRepository;
|
||||||
|
|
||||||
|
private StatsList statsList;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setup() {
|
||||||
|
userRepository.deleteAll();
|
||||||
|
User user = userRepository.save(uniqueUser(1));
|
||||||
|
statsList = user.getStats();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetStats() {
|
||||||
|
assertNotNull(statsList.getStats(Timeframe.TOTAL));
|
||||||
|
assertNotNull(statsList.getStats(Timeframe.MONTHLY));
|
||||||
|
assertNotNull(statsList.getStats(Timeframe.WEEKLY));
|
||||||
|
|
||||||
|
assertThrows(NullPointerException.class,
|
||||||
|
() -> statsList.getStats(null));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testAddToStat_andGetStatValue() {
|
||||||
|
statsList.addToStat(Timeframe.TOTAL, "XP", 100);
|
||||||
|
assertEquals(100, statsList.getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
assertEquals(0, statsList.getStatValue(Timeframe.WEEKLY, "XP"));
|
||||||
|
|
||||||
|
assertEquals(0, statsList.getStatValue(Timeframe.TOTAL, "NON_EXISTING"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testAddToAllStats() {
|
||||||
|
statsList.addToAllStats("XP", 50);
|
||||||
|
assertEquals(50, statsList.getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
assertEquals(50, statsList.getStatValue(Timeframe.MONTHLY, "XP"));
|
||||||
|
assertEquals(50, statsList.getStatValue(Timeframe.WEEKLY, "XP"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testResetStats() {
|
||||||
|
statsList.addToAllStats("XP", 200);
|
||||||
|
statsList.addToAllStats("KM_CYCLED", 100);
|
||||||
|
|
||||||
|
statsList.resetStats(Timeframe.WEEKLY);
|
||||||
|
|
||||||
|
assertEquals(0, statsList.getStatValue(Timeframe.WEEKLY, "XP"));
|
||||||
|
assertEquals(0, statsList.getStatValue(Timeframe.WEEKLY, "KM_CYCLED"));
|
||||||
|
assertEquals(200, statsList.getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
assertEquals(200, statsList.getStatValue(Timeframe.MONTHLY, "XP"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testStatsConstructor_setsAllFieldsToZero() {
|
||||||
|
Stats stats = statsList.getTotalStats();
|
||||||
|
assertEquals(0L, stats.getXP());
|
||||||
|
assertEquals(0L, stats.getCO2_SAVED());
|
||||||
|
assertEquals(0L, stats.getKM_CYCLED());
|
||||||
|
assertEquals(0L, stats.getKM_WALKED());
|
||||||
|
assertEquals(0L, stats.getKM_PUBLIC_TRANSPORT());
|
||||||
|
assertEquals(0L, stats.getKM_DRIVEN());
|
||||||
|
assertEquals(0L, stats.getMOBILITY_SCORE());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
@@ -6,6 +6,7 @@ import SuMoC.backend.gamification.badges.models.Badge;
|
|||||||
import SuMoC.backend.gamification.badges.models.BadgeCategory;
|
import SuMoC.backend.gamification.badges.models.BadgeCategory;
|
||||||
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
import SuMoC.backend.gamification.badges.models.BadgeDTO;
|
||||||
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
import SuMoC.backend.gamification.badges.models.UserBadgeDTO;
|
||||||
|
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import SuMoC.backend.user.repository.UserRepository;
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
import SuMoC.backend.user.stats.StatsService;
|
import SuMoC.backend.user.stats.StatsService;
|
||||||
@@ -178,6 +179,18 @@ public class BadgeServiceTest {
|
|||||||
|
|
||||||
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
||||||
|
|
||||||
|
|
||||||
|
// CONFLICT - add badge with same name
|
||||||
|
BadgeDTO duplicate = new BadgeDTO();
|
||||||
|
duplicate.setName("badgeName1");
|
||||||
|
duplicate.setDescription("x");
|
||||||
|
duplicate.setCategory(BadgeCategory.XP);
|
||||||
|
|
||||||
|
ResponseStatusException conflictEx = assertThrows(ResponseStatusException.class,
|
||||||
|
() -> badgeService.createBadge(duplicate));
|
||||||
|
assertEquals(HttpStatus.CONFLICT, conflictEx.getStatusCode());
|
||||||
|
|
||||||
|
|
||||||
// DELETE
|
// DELETE
|
||||||
// existing
|
// existing
|
||||||
for(BadgeDTO delBadge : badgeService.getAllBadges()) {
|
for(BadgeDTO delBadge : badgeService.getAllBadges()) {
|
||||||
@@ -225,5 +238,12 @@ public class BadgeServiceTest {
|
|||||||
badgeList = badgeService.getUserBadges(another.getId());
|
badgeList = badgeService.getUserBadges(another.getId());
|
||||||
assertNotNull(badgeList);
|
assertNotNull(badgeList);
|
||||||
assertEquals(0, badgeList.size());
|
assertEquals(0, badgeList.size());
|
||||||
|
|
||||||
|
|
||||||
|
// PUBLIC visibility → Badges sichtbar
|
||||||
|
another.setVisibilityPrivacy(VisibilityPrivacy.PUBLIC);
|
||||||
|
userRepository.save(another);
|
||||||
|
badgeList = badgeService.getUserBadges(another.getId());
|
||||||
|
assertNotNull(badgeList);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
package SuMoC.backend.user.service;
|
package SuMoC.backend.user.service;
|
||||||
|
import SuMoC.backend.gamification.Timeframe;
|
||||||
import SuMoC.backend.gamification.challenges.ChallengeRepository;
|
import SuMoC.backend.gamification.challenges.ChallengeRepository;
|
||||||
import SuMoC.backend.gamification.challenges.ChallengeService;
|
import SuMoC.backend.gamification.challenges.ChallengeService;
|
||||||
import SuMoC.backend.gamification.challenges.Models.Challenge;
|
import SuMoC.backend.gamification.challenges.Models.Challenge;
|
||||||
@@ -248,4 +249,56 @@ public class ChallengeServiceTest {
|
|||||||
assertEquals(3, availableChallenges.size());
|
assertEquals(3, availableChallenges.size());
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
public void testCheckAndAwardChallenges() {
|
||||||
|
// activate first schallenges
|
||||||
|
challengeService.weeklyChallengeScheduler();
|
||||||
|
|
||||||
|
// rerun scheduler and activate new challenges
|
||||||
|
challengeService.weeklyChallengeScheduler();
|
||||||
|
|
||||||
|
List<ChallengeDTO> active = challengeService.getAvailableChallenges();
|
||||||
|
assertEquals(3, active.size());
|
||||||
|
|
||||||
|
// fulfill all active XP challenges
|
||||||
|
for (ChallengeDTO activeChallenge : active) {
|
||||||
|
if (activeChallenge.getCriteria() != null && activeChallenge.getCriteria().get("XP") != null) {
|
||||||
|
Integer target = activeChallenge.getCriteria().get("XP");
|
||||||
|
// currentStat auf 0 setzen, dann genau auf target springen
|
||||||
|
challengeService.checkAndAwardChallenges("XP", (long) target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
User updated = userRepository.findById(sender.getId()).orElseThrow();
|
||||||
|
assertTrue(updated.getStats().getStatValue(Timeframe.TOTAL, "XP") > 0);
|
||||||
|
|
||||||
|
// wrong field with no reward - target == null
|
||||||
|
challengeService.checkAndAwardChallenges("KM_DRIVEN", 999L);
|
||||||
|
|
||||||
|
// value to low - newStat < target
|
||||||
|
challengeService.checkAndAwardChallenges("XP", 0L);
|
||||||
|
|
||||||
|
// currentStat >= target
|
||||||
|
challengeService.checkAndAwardChallenges("XP", 9999L);
|
||||||
|
challengeService.checkAndAwardChallenges("XP", 1L);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
public void testWeeklyScheduler_empty() {
|
||||||
|
challengeRepository.deleteAll();
|
||||||
|
assertDoesNotThrow(() -> challengeService.weeklyChallengeScheduler());
|
||||||
|
assertEquals(0, challengeService.getAvailableChallenges().size());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
public void testDeactivateActivate_notFound() {
|
||||||
|
assertThrows(ResponseStatusException.class,
|
||||||
|
() -> challengeService.deactivateChallenge(999L));
|
||||||
|
assertThrows(ResponseStatusException.class,
|
||||||
|
() -> challengeService.activateChallenge(999L));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,131 @@
|
|||||||
|
package SuMoC.backend.user.service;
|
||||||
|
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
|
import org.junit.jupiter.api.AfterEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.extension.ExtendWith;
|
||||||
|
import org.mockito.InjectMocks;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.junit.jupiter.MockitoExtension;
|
||||||
|
import org.springframework.security.authentication.AnonymousAuthenticationToken;
|
||||||
|
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||||
|
import org.springframework.security.core.Authentication;
|
||||||
|
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Optional;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
import static org.mockito.Mockito.*;
|
||||||
|
import static org.springframework.http.HttpStatus.NOT_FOUND;
|
||||||
|
import static org.springframework.http.HttpStatus.UNAUTHORIZED;
|
||||||
|
|
||||||
|
@ExtendWith(MockitoExtension.class)
|
||||||
|
class CurrentUserServiceTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private UserRepository userRepository;
|
||||||
|
|
||||||
|
@InjectMocks
|
||||||
|
private CurrentUserService currentUserService;
|
||||||
|
|
||||||
|
@AfterEach
|
||||||
|
void clearSecurityContext() {
|
||||||
|
SecurityContextHolder.clearContext();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper Classes for initialization
|
||||||
|
private void setAuthentication(String email) {
|
||||||
|
var auth = new UsernamePasswordAuthenticationToken(email, null, List.of());
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void setAnonymousAuthentication() {
|
||||||
|
var auth = new AnonymousAuthenticationToken(
|
||||||
|
"key", "anonymousUser", List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS")));
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tests get()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void get_returnsUser_whenAuthenticatedAndUserExists() {
|
||||||
|
var user = new User();
|
||||||
|
setAuthentication("user@example.com");
|
||||||
|
when(userRepository.findByEmail("user@example.com")).thenReturn(Optional.of(user));
|
||||||
|
|
||||||
|
User result = currentUserService.get();
|
||||||
|
|
||||||
|
assertThat(result).isEqualTo(user);
|
||||||
|
verify(userRepository).findByEmail("user@example.com");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void get_throwsUnauthorized_whenNoAuthentication() {
|
||||||
|
SecurityContextHolder.clearContext();
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> currentUserService.get())
|
||||||
|
.isInstanceOf(ResponseStatusException.class)
|
||||||
|
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||||
|
.isEqualTo(UNAUTHORIZED));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void get_throwsUnauthorized_whenAuthenticationIsNotAuthenticated() {
|
||||||
|
Authentication auth = mock(Authentication.class);
|
||||||
|
when(auth.isAuthenticated()).thenReturn(false);
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> currentUserService.get())
|
||||||
|
.isInstanceOf(ResponseStatusException.class)
|
||||||
|
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||||
|
.isEqualTo(UNAUTHORIZED));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void get_throwsNotFound_whenUserDoesNotExistInRepository() {
|
||||||
|
setAuthentication("ghost@example.com");
|
||||||
|
when(userRepository.findByEmail("ghost@example.com")).thenReturn(Optional.empty());
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> currentUserService.get())
|
||||||
|
.isInstanceOf(ResponseStatusException.class)
|
||||||
|
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||||
|
.isEqualTo(NOT_FOUND));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Tests isLoggedInUser()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isLoggedInUser_returnsTrue_whenAuthenticated() {
|
||||||
|
setAuthentication("user@example.com");
|
||||||
|
|
||||||
|
assertThat(currentUserService.isLoggedInUser()).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isLoggedInUser_returnsFalse_whenNoAuthentication() {
|
||||||
|
SecurityContextHolder.clearContext();
|
||||||
|
|
||||||
|
assertThat(currentUserService.isLoggedInUser()).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isLoggedInUser_returnsFalse_whenAnonymous() {
|
||||||
|
setAnonymousAuthentication();
|
||||||
|
|
||||||
|
assertThat(currentUserService.isLoggedInUser()).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void isLoggedInUser_returnsFalse_whenAuthenticationIsNotAuthenticated() {
|
||||||
|
Authentication auth = mock(Authentication.class);
|
||||||
|
when(auth.isAuthenticated()).thenReturn(false);
|
||||||
|
SecurityContextHolder.getContext().setAuthentication(auth);
|
||||||
|
|
||||||
|
assertThat(currentUserService.isLoggedInUser()).isFalse();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,213 +1,545 @@
|
|||||||
package SuMoC.backend.user.service;
|
package SuMoC.backend.user.service;
|
||||||
|
|
||||||
import SuMoC.backend.notification.services.NotificationSchedulerService;
|
import SuMoC.backend.user.dtos.FriendshipDTO;
|
||||||
|
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||||
import SuMoC.backend.user.enums.FriendShipStatus;
|
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||||
import SuMoC.backend.user.models.Friendship;
|
import SuMoC.backend.user.models.Friendship;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
import SuMoC.backend.user.repository.FriendshipRepository;
|
import SuMoC.backend.user.repository.FriendshipRepository;
|
||||||
import SuMoC.backend.user.repository.UserRepository;
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
|
import jakarta.transaction.Transactional;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.junit.jupiter.api.extension.ExtendWith;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.mockito.ArgumentCaptor;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
import org.mockito.Captor;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
import org.mockito.InjectMocks;
|
|
||||||
import org.mockito.Mock;
|
|
||||||
import org.mockito.junit.jupiter.MockitoExtension;
|
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
import static SuMoC.backend.Factories.UserTestFactory.uniqueUser;
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
import static org.mockito.ArgumentMatchers.any;
|
|
||||||
import static org.mockito.ArgumentMatchers.eq;
|
|
||||||
import static org.mockito.Mockito.*;
|
|
||||||
|
|
||||||
@ExtendWith(MockitoExtension.class)
|
@SpringBootTest
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
@Transactional
|
||||||
public class FriendshipServiceTest {
|
public class FriendshipServiceTest {
|
||||||
|
|
||||||
@Mock
|
@Autowired
|
||||||
private FriendshipRepository friendshipRepository;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private UserRepository userRepository;
|
|
||||||
|
|
||||||
@Mock
|
|
||||||
private NotificationSchedulerService notificationSchedulerService;
|
|
||||||
|
|
||||||
@InjectMocks
|
|
||||||
private FriendshipService friendshipService;
|
private FriendshipService friendshipService;
|
||||||
|
|
||||||
@Captor
|
@Autowired
|
||||||
private ArgumentCaptor<Friendship> friendshipCaptor;
|
private FriendshipRepository friendshipRepository;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private UserRepository userRepository;
|
||||||
|
|
||||||
private User sender;
|
private User sender;
|
||||||
private User friend;
|
private User friend;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
sender = new User("Public1", "Private1", "email1@example.com", "pass1");
|
sender = userRepository.save(uniqueUser(1));
|
||||||
sender.setId(1L);
|
friend = userRepository.save(uniqueUser(2));
|
||||||
friend = new User("Public2", "Private2", "email2@example.com", "pass2");
|
|
||||||
friend.setId(2L);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// requestFriendship
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void requestFriendship_Success() {
|
void requestFriendship_Success() {
|
||||||
// Arrange
|
|
||||||
when(userRepository.findById(friend.getId())).thenReturn(Optional.of(friend));
|
|
||||||
when(friendshipRepository.findByUserAndFriend(any(User.class), any(User.class))).thenReturn(null);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
friendshipService.requestFriendship(sender, friend.getId());
|
friendshipService.requestFriendship(sender, friend.getId());
|
||||||
|
|
||||||
// Assert
|
Friendship senderToFriend = friendshipRepository.findByUserAndFriend(sender, friend);
|
||||||
verify(friendshipRepository, times(2)).save(friendshipCaptor.capture());
|
Friendship friendToSender = friendshipRepository.findByUserAndFriend(friend, sender);
|
||||||
List<Friendship> capturedFriendships = friendshipCaptor.getAllValues();
|
|
||||||
assertEquals(2, capturedFriendships.size());
|
|
||||||
|
|
||||||
// Verify one friendship: sender -> friend, REQUESTED
|
assertNotNull(senderToFriend);
|
||||||
assertTrue(capturedFriendships.stream()
|
assertNotNull(friendToSender);
|
||||||
.anyMatch(f -> f.getUser().equals(sender) && f.getFriend().equals(friend) && f.getStatus().equals(FriendShipStatus.REQUESTED)));
|
assertEquals(FriendShipStatus.REQUESTED, senderToFriend.getStatus());
|
||||||
|
assertEquals(FriendShipStatus.PENDING, friendToSender.getStatus());
|
||||||
// Verify one friendship: friend -> sender, PENDING
|
|
||||||
assertTrue(capturedFriendships.stream()
|
|
||||||
.anyMatch(f -> f.getUser().equals(friend) && f.getFriend().equals(sender) && f.getStatus().equals(FriendShipStatus.PENDING)));
|
|
||||||
|
|
||||||
// Verify notificationSchedulerService.schedule called with correct params
|
|
||||||
verify(notificationSchedulerService, times(1)).schedule(
|
|
||||||
eq(friend.getId()),
|
|
||||||
argThat(arg -> {
|
|
||||||
// Check FriendshipDTO fields
|
|
||||||
if (!(arg instanceof SuMoC.backend.user.dtos.FriendshipDTO dto)) return false;
|
|
||||||
return dto.getUserId().equals(friend.getId()) &&
|
|
||||||
dto.getFriend().getId().equals(sender.getId()) &&
|
|
||||||
dto.getFriend().getDisplayName().equals(sender.getPrivateName()) &&
|
|
||||||
dto.getStatus() == FriendShipStatus.PENDING;
|
|
||||||
}),
|
|
||||||
eq(SuMoC.backend.notification.enums.NotificationType.FRIENDSHIP_REQUEST_RECEIVED),
|
|
||||||
isNull()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void requestFriendship_Blocked() {
|
void requestFriendship_InvalidStates_Throw() {
|
||||||
// Arrange
|
// friend not found
|
||||||
Friendship blockedFriendship = new Friendship(sender, friend, FriendShipStatus.BLOCKED);
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, 99999L));
|
||||||
when(friendshipRepository.findByUserAndFriend(sender, friend)).thenReturn(blockedFriendship);
|
|
||||||
when(friendshipRepository.findByUserAndFriend(friend, sender)).thenReturn(null);
|
|
||||||
when(userRepository.findById(friend.getId())).thenReturn(Optional.of(friend));
|
|
||||||
|
|
||||||
|
// sender is blocked
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.BLOCKED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
// Act & Assert
|
// already rejected
|
||||||
boolean exceptionThrown = false;
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REJECTED));
|
||||||
try {
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
friendshipService.requestFriendship(sender, friend.getId());
|
friendshipRepository.deleteAllInBatch();
|
||||||
} catch (Exception e) {
|
friendshipRepository.flush();
|
||||||
exceptionThrown = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
assertTrue(exceptionThrown);
|
// already pending: both sides (REQUESTED + PENDING)
|
||||||
verify(friendshipRepository, never()).save(any(Friendship.class));
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REQUESTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.PENDING));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// already pending: only sender side exists, reverse missing -> unexpected throw
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REQUESTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// already pending reverse: both sides (PENDING + REQUESTED)
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REQUESTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// already pending reverse: only sender side exists, reverse missing -> unexpected throw
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// already friends: both sides ACCEPTED
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// already friends: only sender side exists, reverse missing -> unexpected throw
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// corrupt state: REJECTED + unexpected second row
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REJECTED));
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// PENDING check: relation to Friend != REQUESTED, rel to Sender == PENDING
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.PENDING));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// ACCEPTED check: relation to Friend != ACCEPTED, rel to Sender == ACCEPTED
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REQUESTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.requestFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void requestFriendship_AlreadyRejectedFriendship() {
|
void requestFriendship_AfterRejection_Success() {
|
||||||
// Arrange
|
// friend previously rejected senders request only the REJECTED row remains
|
||||||
Friendship rejectedFriendship = new Friendship(sender, friend, FriendShipStatus.REJECTED);
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REJECTED));
|
||||||
when(friendshipRepository.findByUserAndFriend(sender, friend)).thenReturn(rejectedFriendship);
|
|
||||||
when(friendshipRepository.findByUserAndFriend(friend, sender)).thenReturn(null);
|
|
||||||
when(userRepository.findById(friend.getId())).thenReturn(Optional.of(friend));
|
|
||||||
|
|
||||||
// Act & Assert
|
friendshipService.requestFriendship(sender, friend.getId());
|
||||||
boolean exceptionThrown = false;
|
|
||||||
try {
|
|
||||||
friendshipService.requestFriendship(sender, friend.getId());
|
|
||||||
} catch (Exception e) {
|
|
||||||
exceptionThrown = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
assertTrue(exceptionThrown);
|
Friendship senderToFriend = friendshipRepository.findByUserAndFriend(sender, friend);
|
||||||
verify(friendshipRepository, never()).save(any(Friendship.class));
|
Friendship friendToSender = friendshipRepository.findByUserAndFriend(friend, sender);
|
||||||
|
assertNotNull(senderToFriend);
|
||||||
|
assertNotNull(friendToSender);
|
||||||
|
assertEquals(FriendShipStatus.REQUESTED, senderToFriend.getStatus());
|
||||||
|
assertEquals(FriendShipStatus.PENDING, friendToSender.getStatus());
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO
|
|
||||||
void requestFriendship_AlreadyPendingRequest() {
|
|
||||||
|
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// acceptFriendship
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void acceptFriendship_Success() {
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REQUESTED));
|
||||||
|
|
||||||
|
friendshipService.acceptFriendship(sender, friend.getId());
|
||||||
|
|
||||||
|
assertEquals(FriendShipStatus.ACCEPTED, friendshipRepository.findByUserAndFriend(sender, friend).getStatus());
|
||||||
|
assertEquals(FriendShipStatus.ACCEPTED, friendshipRepository.findByUserAndFriend(friend, sender).getStatus());
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO
|
@Test
|
||||||
void requestFriendship_AlreadyPnedingRequestReverse() {
|
void acceptFriendship_InvalidStates_Throw() {
|
||||||
|
// friend not found
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, 99999L));
|
||||||
|
|
||||||
|
// no relationship at all
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
|
||||||
|
|
||||||
|
// only one side exists
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
|
||||||
|
friendshipRepository.flush();
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// wrong status (already accepted)
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
|
||||||
|
|
||||||
|
// wrong status: sender is REQUESTED instead of PENDING (swapped)
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REQUESTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.PENDING));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
|
||||||
|
// wrong status: both ACCEPTED
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
|
||||||
|
|
||||||
|
// relation to Friend != PENDING, relation to Sender == REQUESTED
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REQUESTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// relation to Friend == PENDING, relation to sender != REQUESTED
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.acceptFriendship(sender, friend.getId()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO
|
|
||||||
void requestFriendship_AlreadyFriends() {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO
|
// -------------------------------------------------------------------------
|
||||||
void requestFriendship_SenderPreviouslyRejected() {
|
// rejectFriendship
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
}
|
@Test
|
||||||
|
|
||||||
// TODO
|
|
||||||
void rejectFriendship_Success() {
|
void rejectFriendship_Success() {
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REQUESTED));
|
||||||
|
|
||||||
|
friendshipService.rejectFriendship(sender, friend.getId());
|
||||||
|
|
||||||
|
assertNull(friendshipRepository.findByUserAndFriend(sender, friend));
|
||||||
|
assertEquals(FriendShipStatus.REJECTED, friendshipRepository.findByUserAndFriend(friend, sender).getStatus());
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO
|
@Test
|
||||||
|
void rejectFriendship_InvalidStates_Throw() {
|
||||||
|
// friend not found
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.rejectFriendship(sender, 99999L));
|
||||||
|
|
||||||
|
// no relationship
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.rejectFriendship(sender, friend.getId()));
|
||||||
|
|
||||||
|
// wrong status
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.rejectFriendship(sender, friend.getId()));
|
||||||
|
|
||||||
|
// only one side exists (sender has PENDING, friend missing)
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.rejectFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
|
||||||
|
// only one side exists (friend has REQUESTED, sender missing)
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REQUESTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.rejectFriendship(sender, friend.getId()));
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
|
||||||
|
// wrong status: sender is REQUESTED instead of PENDING
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REQUESTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.PENDING));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.rejectFriendship(sender, friend.getId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// unfriend
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
void unfriend_Success() {
|
void unfriend_Success() {
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
|
||||||
|
|
||||||
}
|
friendshipService.unfriend(sender, friend.getId());
|
||||||
|
|
||||||
// TODO
|
assertNull(friendshipRepository.findByUserAndFriend(sender, friend));
|
||||||
@Test
|
assertNull(friendshipRepository.findByUserAndFriend(friend, sender));
|
||||||
void blockNotFriendUser_Success() {
|
|
||||||
// Arrange
|
|
||||||
when(userRepository.findById(friend.getId())).thenReturn(Optional.of(friend));
|
|
||||||
when(friendshipRepository.findByUserAndFriend(any(User.class), any(User.class))).thenReturn(null);
|
|
||||||
|
|
||||||
// Act
|
|
||||||
friendshipService.blockUser(sender, friend.getId());
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
verify(friendshipRepository, times(1)).save(friendshipCaptor.capture());
|
|
||||||
List<Friendship> capturedFriendships = friendshipCaptor.getAllValues();
|
|
||||||
assertEquals(1, capturedFriendships.size());
|
|
||||||
|
|
||||||
// Verify one friendship exists where the blocked users id is the user id and the blocking users id is the friend id, BLOCKED
|
|
||||||
assertTrue(capturedFriendships.stream()
|
|
||||||
.anyMatch(f -> f.getFriend().equals(sender) && f.getUser().equals(friend) && f.getStatus().equals(FriendShipStatus.BLOCKED)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void blockFriendUser_Success() {
|
void unfriend_InvalidStates_Throw() {
|
||||||
// Arrange
|
// friend not found
|
||||||
when(userRepository.findById(friend.getId())).thenReturn(Optional.of(friend));
|
assertThrows(RuntimeException.class, () -> friendshipService.unfriend(sender, 99999L));
|
||||||
Friendship acceptedFriendship = new Friendship(sender, friend, FriendShipStatus.ACCEPTED);
|
|
||||||
Friendship acceptedFriendshipReverse = new Friendship(friend, sender, FriendShipStatus.ACCEPTED);
|
|
||||||
when(friendshipRepository.findByUserAndFriend(sender, friend)).thenReturn(acceptedFriendship);
|
|
||||||
when(friendshipRepository.findByUserAndFriend(friend, sender)).thenReturn(acceptedFriendshipReverse);
|
|
||||||
|
|
||||||
// Act
|
// no relationship
|
||||||
friendshipService.blockUser(sender, friend.getId());
|
assertThrows(RuntimeException.class, () -> friendshipService.unfriend(sender, friend.getId()));
|
||||||
|
|
||||||
// Assert
|
// wrong status
|
||||||
// first, old friendships are deleted
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.PENDING));
|
||||||
verify(friendshipRepository, times(2)).delete(any(Friendship.class));
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.REQUESTED));
|
||||||
// then, new blocked friendship is created
|
assertThrows(RuntimeException.class, () -> friendshipService.unfriend(sender, friend.getId()));
|
||||||
verify(friendshipRepository, times(1)).save(friendshipCaptor.capture());
|
|
||||||
List<Friendship> capturedFriendships = friendshipCaptor.getAllValues();
|
// only one side exists (only sender has ACCEPTED)
|
||||||
assertEquals(1, capturedFriendships.size());
|
friendshipRepository.deleteAllInBatch();
|
||||||
// Verify one friendship exists where the blocked users id is the user id and the blocking users id is the friend id, BLOCKED
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
assertTrue(capturedFriendships.stream()
|
assertThrows(RuntimeException.class, () -> friendshipService.unfriend(sender, friend.getId()));
|
||||||
.anyMatch(f -> f.getFriend().equals(sender) && f.getUser().equals(friend) && f.getStatus().equals(FriendShipStatus.BLOCKED)));
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
|
||||||
|
// only one side exists (only friend has ACCEPTED)
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.unfriend(sender, friend.getId()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO
|
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// blockUser
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void blockUser_CreatesBlocked() {
|
||||||
|
// no prior relationship
|
||||||
|
friendshipService.blockUser(sender, friend.getId());
|
||||||
|
|
||||||
|
assertNull(friendshipRepository.findByUserAndFriend(sender, friend));
|
||||||
|
assertEquals(FriendShipStatus.BLOCKED, friendshipRepository.findByUserAndFriend(friend, sender).getStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void blockUser_DeletesPriorRelationship() {
|
||||||
|
// friends -> block
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipService.blockUser(sender, friend.getId());
|
||||||
|
assertNull(friendshipRepository.findByUserAndFriend(sender, friend));
|
||||||
|
assertEquals(FriendShipStatus.BLOCKED, friendshipRepository.findByUserAndFriend(friend, sender).getStatus());
|
||||||
|
|
||||||
|
friendshipRepository.deleteAllInBatch();
|
||||||
|
friendshipRepository.flush();
|
||||||
|
|
||||||
|
// pending request -> block
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.REQUESTED));
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.PENDING));
|
||||||
|
friendshipService.blockUser(sender, friend.getId());
|
||||||
|
assertNull(friendshipRepository.findByUserAndFriend(sender, friend));
|
||||||
|
assertEquals(FriendShipStatus.BLOCKED, friendshipRepository.findByUserAndFriend(friend, sender).getStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void blockUser_FriendNotFound_Throws() {
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.blockUser(sender, 99999L));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// unblockUser
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
void unblockUser_Success() {
|
void unblockUser_Success() {
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.BLOCKED));
|
||||||
|
|
||||||
|
friendshipService.unblockUser(sender, friend.getId());
|
||||||
|
|
||||||
|
assertNull(friendshipRepository.findByUserAndFriend(friend, sender));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void unblockUser_InvalidStates_Throw() {
|
||||||
|
// friend not found
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.unblockUser(sender, 99999L));
|
||||||
|
|
||||||
|
// no relationship
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.unblockUser(sender, friend.getId()));
|
||||||
|
|
||||||
|
// wrong status
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.ACCEPTED));
|
||||||
|
assertThrows(RuntimeException.class, () -> friendshipService.unblockUser(sender, friend.getId()));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// getFriendships / getAcceptedFriendships
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getFriendships_ReturnsAllEntries_WithCorrectNames() {
|
||||||
|
User third = userRepository.save(uniqueUser(3));
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(sender, third, FriendShipStatus.REQUESTED));
|
||||||
|
|
||||||
|
List<FriendshipDTO> all = friendshipService.getFriendships(sender.getId());
|
||||||
|
assertEquals(2, all.size());
|
||||||
|
|
||||||
|
// accepted -> private name
|
||||||
|
all.stream()
|
||||||
|
.filter(f -> f.getFriend().getId().equals(friend.getId()))
|
||||||
|
.findFirst()
|
||||||
|
.ifPresentOrElse(
|
||||||
|
f -> assertEquals(friend.getPrivateName(), f.getFriend().getDisplayName()),
|
||||||
|
() -> fail("Accepted friendship not found")
|
||||||
|
);
|
||||||
|
|
||||||
|
// requested -> public name
|
||||||
|
all.stream()
|
||||||
|
.filter(f -> f.getFriend().getId().equals(third.getId()))
|
||||||
|
.findFirst()
|
||||||
|
.ifPresentOrElse(
|
||||||
|
f -> assertEquals(third.getPublicName(), f.getFriend().getDisplayName()),
|
||||||
|
() -> fail("Requested friendship not found")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getFriendships_Empty() {
|
||||||
|
assertTrue(friendshipService.getFriendships(sender.getId()).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAcceptedFriendships_OnlyReturnsAccepted_WithPrivateName() {
|
||||||
|
User third = userRepository.save(uniqueUser(3));
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(sender, third, FriendShipStatus.REQUESTED));
|
||||||
|
|
||||||
|
List<FriendshipDTO> result = friendshipService.getAcceptedFriendships(sender.getId());
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
assertEquals(FriendShipStatus.ACCEPTED, result.get(0).getStatus());
|
||||||
|
assertEquals(friend.getPrivateName(), result.get(0).getFriend().getDisplayName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAcceptedFriendships_Empty() {
|
||||||
|
assertTrue(friendshipService.getAcceptedFriendships(sender.getId()).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// getBlockedUsers
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getBlockedUsers_ReturnsBlockedUsers() {
|
||||||
|
friendshipRepository.save(new Friendship(friend, sender, FriendShipStatus.BLOCKED));
|
||||||
|
|
||||||
|
List<MinimalUserDTO> result = friendshipService.getBlockedUsers(sender.getId());
|
||||||
|
|
||||||
|
assertEquals(1, result.size());
|
||||||
|
assertEquals(friend.getId(), result.get(0).getId());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getBlockedUsers_Empty() {
|
||||||
|
assertTrue(friendshipService.getBlockedUsers(sender.getId()).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// getAcceptedFriends
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAcceptedFriends_ReturnsOnlyAccepted() {
|
||||||
|
User third = userRepository.save(uniqueUser(3));
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
friendshipRepository.save(new Friendship(sender, third, FriendShipStatus.ACCEPTED));
|
||||||
|
|
||||||
|
List<User> accepted = friendshipService.getAcceptedFriends(sender);
|
||||||
|
|
||||||
|
assertEquals(2, accepted.size());
|
||||||
|
assertTrue(accepted.stream().anyMatch(u -> u.getId().equals(friend.getId())));
|
||||||
|
assertTrue(accepted.stream().anyMatch(u -> u.getId().equals(third.getId())));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getAcceptedFriends_Empty() {
|
||||||
|
assertTrue(friendshipService.getAcceptedFriends(sender).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// getPrivateNameIfFriendshipAccepted
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getPrivateNameIfFriendshipAccepted_PrivateOrPublicName() {
|
||||||
|
User third = userRepository.save(uniqueUser(3));
|
||||||
|
friendshipRepository.save(new Friendship(sender, friend, FriendShipStatus.ACCEPTED));
|
||||||
|
// sender and third are NOT friends
|
||||||
|
|
||||||
|
List<FriendshipService.NameWithFriendship> result =
|
||||||
|
friendshipService.getPrivateNameIfFriendshipAccepted(sender, List.of(friend.getId(), third.getId()));
|
||||||
|
|
||||||
|
assertEquals(2, result.size());
|
||||||
|
|
||||||
|
FriendshipService.NameWithFriendship friendResult = result.stream()
|
||||||
|
.filter(r -> r.id().equals(friend.getId())).findFirst().orElseThrow();
|
||||||
|
assertEquals(friend.getPrivateName(), friendResult.name());
|
||||||
|
assertTrue(friendResult.friendship());
|
||||||
|
|
||||||
|
FriendshipService.NameWithFriendship thirdResult = result.stream()
|
||||||
|
.filter(r -> r.id().equals(third.getId())).findFirst().orElseThrow();
|
||||||
|
assertEquals(third.getPublicName(), thirdResult.name());
|
||||||
|
assertFalse(thirdResult.friendship());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getPrivateNameIfFriendshipAccepted_EmptyList() {
|
||||||
|
assertTrue(friendshipService.getPrivateNameIfFriendshipAccepted(sender, List.of()).isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getPrivateNameIfFriendshipAccepted_UserNotFound_Throws() {
|
||||||
|
assertThrows(RuntimeException.class,
|
||||||
|
() -> friendshipService.getPrivateNameIfFriendshipAccepted(sender, List.of(99999L)));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
// getByFriendcode
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void requestFriendshipByFriendcode_Success() {
|
||||||
|
friendshipService.requestFriendshipByFriendcode(sender, friend.getFriendCode());
|
||||||
|
|
||||||
|
assertEquals(FriendShipStatus.REQUESTED, friendshipRepository.findByUserAndFriend(sender, friend).getStatus());
|
||||||
|
assertEquals(FriendShipStatus.PENDING, friendshipRepository.findByUserAndFriend(friend, sender).getStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void requestFriendshipByFriendcode_NotFound_Throws() {
|
||||||
|
assertThrows(RuntimeException.class,
|
||||||
|
() -> friendshipService.requestFriendshipByFriendcode(sender, "INVALID_CODE"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void requestFriendshipByFriendcode_Self_Throws() {
|
||||||
|
assertThrows(RuntimeException.class,
|
||||||
|
() -> friendshipService.requestFriendshipByFriendcode(sender, sender.getFriendCode()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,7 +5,10 @@ import SuMoC.backend.gamification.Timeframe;
|
|||||||
import SuMoC.backend.gamification.scoretable.LeaderboardService;
|
import SuMoC.backend.gamification.scoretable.LeaderboardService;
|
||||||
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
|
import SuMoC.backend.gamification.scoretable.models.Leaderboard;
|
||||||
import SuMoC.backend.gamification.scoretable.models.LeaderboardEntry;
|
import SuMoC.backend.gamification.scoretable.models.LeaderboardEntry;
|
||||||
|
import SuMoC.backend.images.ImageBase64Util;
|
||||||
|
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
|
import SuMoC.backend.user.repository.FriendshipRepository;
|
||||||
import SuMoC.backend.user.repository.UserRepository;
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
import SuMoC.backend.user.stats.StatsService;
|
import SuMoC.backend.user.stats.StatsService;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
@@ -43,14 +46,21 @@ public class LeaderboardServiceTest {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private PrivacyService privacyService;
|
private PrivacyService privacyService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private FriendshipRepository friendshipRepository;
|
||||||
|
|
||||||
private FriendshipTestFactory friendshipFactory;
|
private FriendshipTestFactory friendshipFactory;
|
||||||
|
|
||||||
private User sender;
|
private User sender;
|
||||||
private List<User> friends;
|
private List<User> friends;
|
||||||
private List<User> others;
|
private List<User> others;
|
||||||
|
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
|
friendshipRepository.deleteAll();
|
||||||
|
userRepository.deleteAll();
|
||||||
|
|
||||||
friendshipFactory = new FriendshipTestFactory(friendshipService);
|
friendshipFactory = new FriendshipTestFactory(friendshipService);
|
||||||
|
|
||||||
sender = userRepository.save(uniqueUser(1));
|
sender = userRepository.save(uniqueUser(1));
|
||||||
@@ -189,5 +199,87 @@ public class LeaderboardServiceTest {
|
|||||||
assertEquals(privacyService.checkVisibility(sender, user) ? user.getPrivateName() : user.getPublicName(), entry.getUsername());
|
assertEquals(privacyService.checkVisibility(sender, user) ? user.getPrivateName() : user.getPublicName(), entry.getUsername());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
public void testGetFriendLeaderboard_senderNotInFriendList() {
|
||||||
|
// sender is never in friendlist -> noneMatch always true -> sender always appended
|
||||||
|
Leaderboard lb = leaderboardService.getFriendLeaderboard(Timeframe.TOTAL, "XP", 3);
|
||||||
|
|
||||||
|
LeaderboardEntry senderEntry = lb.getEntries().stream()
|
||||||
|
.filter(e -> e.getUserId().equals(sender.getId()))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
|
||||||
|
// sender entry uses privateName, isFriend=false, own profilePicture
|
||||||
|
assertEquals(sender.getPrivateName(), senderEntry.getUsername());
|
||||||
|
assertFalse(senderEntry.getIsFriend());
|
||||||
|
assertEquals(
|
||||||
|
ImageBase64Util.encode(sender.getProfileImage().getImageData()),
|
||||||
|
senderEntry.getBase64ProfilePicture()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
public void testGetLeaderboard_senderNotInTopN() {
|
||||||
|
// reset sender XP to 0 so sender is last -> falls into noneMatch-block
|
||||||
|
sender.getStats().addToAllStats("XP", -1000);
|
||||||
|
|
||||||
|
Leaderboard lb = leaderboardService.getLeaderboard(Timeframe.TOTAL, "XP", 3);
|
||||||
|
|
||||||
|
// should be top 3 + sender appended
|
||||||
|
assertEquals(4, lb.getEntries().size());
|
||||||
|
|
||||||
|
LeaderboardEntry senderEntry = lb.getEntries().stream()
|
||||||
|
.filter(e -> e.getUserId().equals(sender.getId()))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
|
||||||
|
assertEquals(sender.getPrivateName(), senderEntry.getUsername());
|
||||||
|
assertFalse(senderEntry.getIsFriend());
|
||||||
|
assertEquals(
|
||||||
|
ImageBase64Util.encode(sender.getProfileImage().getImageData()),
|
||||||
|
senderEntry.getBase64ProfilePicture()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
public void testGetRank() {
|
||||||
|
// sender has 1000 XP -> rank 1 (nobody higher)
|
||||||
|
long rank = leaderboardService.getRank(Timeframe.TOTAL, "XP", 1000);
|
||||||
|
assertEquals(1, rank);
|
||||||
|
|
||||||
|
// rank of 0 XP, everyone is higher -> last place
|
||||||
|
long lastRank = leaderboardService.getRank(Timeframe.TOTAL, "XP", 0);
|
||||||
|
assertEquals(11, lastRank); // 10 users all have > 0 XP, so rank = 10 + 1
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
public void testGetFriendLeaderboard_profilePictureEncoding() {
|
||||||
|
// ps = true: friend is PUBLIC -> encode() called, privateName
|
||||||
|
User friend = friends.getFirst();
|
||||||
|
friend.setVisibilityPrivacy(VisibilityPrivacy.PUBLIC);
|
||||||
|
byte[] img = new byte[]{1, 2, 3};
|
||||||
|
friend.getProfileImage().setImageData(img);
|
||||||
|
|
||||||
|
Leaderboard lb = leaderboardService.getFriendLeaderboard(Timeframe.TOTAL, "XP");
|
||||||
|
|
||||||
|
LeaderboardEntry publicEntry = lb.getEntries().stream()
|
||||||
|
.filter(e -> e.getUserId().equals(friend.getId()))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
|
||||||
|
assertEquals(friend.getPrivateName(), publicEntry.getUsername());
|
||||||
|
assertEquals(ImageBase64Util.encode(img), publicEntry.getBase64ProfilePicture());
|
||||||
|
|
||||||
|
// ps = false: friend not public -> null, publicName
|
||||||
|
User nonPublicFriend = friends.get(1);
|
||||||
|
LeaderboardEntry nonPublicEntry = lb.getEntries().stream()
|
||||||
|
.filter(e -> e.getUserId().equals(nonPublicFriend.getId()))
|
||||||
|
.findFirst().orElseThrow();
|
||||||
|
|
||||||
|
assertEquals(nonPublicFriend.getPublicName(), nonPublicEntry.getUsername());
|
||||||
|
assertNull(nonPublicEntry.getBase64ProfilePicture());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
package SuMoC.backend.user.service;
|
||||||
|
|
||||||
|
import SuMoC.backend.gamification.Timeframe;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
|
import SuMoC.backend.user.stats.StatsListRepository;
|
||||||
|
import SuMoC.backend.user.stats.StatsListSpecifications;
|
||||||
|
import SuMoC.backend.user.stats.models.StatsList;
|
||||||
|
import jakarta.transaction.Transactional;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import static SuMoC.backend.Factories.UserTestFactory.uniqueUser;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
@Transactional
|
||||||
|
public class StatsListSpecificationsTest {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private UserRepository userRepository;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private StatsListRepository statsListRepository;
|
||||||
|
|
||||||
|
private User user1;
|
||||||
|
private User user2;
|
||||||
|
private User user3;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setup() {
|
||||||
|
user1 = userRepository.save(uniqueUser(1));
|
||||||
|
user2 = userRepository.save(uniqueUser(2));
|
||||||
|
user3 = userRepository.save(uniqueUser(3));
|
||||||
|
|
||||||
|
user1.getStats().addToStat(Timeframe.TOTAL, "XP", 100);
|
||||||
|
user2.getStats().addToStat(Timeframe.TOTAL, "XP", 50);
|
||||||
|
user3.getStats().addToStat(Timeframe.TOTAL, "XP", 200);
|
||||||
|
|
||||||
|
user1.getStats().addToStat(Timeframe.WEEKLY, "XP", 30);
|
||||||
|
user2.getStats().addToStat(Timeframe.WEEKLY, "XP", 80);
|
||||||
|
user3.getStats().addToStat(Timeframe.WEEKLY, "XP", 10);
|
||||||
|
|
||||||
|
user1.getStats().addToStat(Timeframe.MONTHLY, "CO2_SAVED", 500);
|
||||||
|
user2.getStats().addToStat(Timeframe.MONTHLY, "CO2_SAVED", 100);
|
||||||
|
user3.getStats().addToStat(Timeframe.MONTHLY, "CO2_SAVED", 300);
|
||||||
|
|
||||||
|
userRepository.saveAll(List.of(user1, user2, user3));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void orderByStat_total_xp_descendingOrder() {
|
||||||
|
List<StatsList> result = statsListRepository.findAll(
|
||||||
|
StatsListSpecifications.orderByStat(Timeframe.TOTAL, "XP"));
|
||||||
|
|
||||||
|
List<StatsList> filtered = result.stream()
|
||||||
|
.filter(s -> s.getStatValue(Timeframe.TOTAL, "XP") > 0)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
assertTrue(filtered.size() >= 3);
|
||||||
|
assertEquals(200, filtered.get(0).getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
assertEquals(100, filtered.get(1).getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
assertEquals(50, filtered.get(2).getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void orderByStat_weekly_xp_descendingOrder() {
|
||||||
|
List<StatsList> result = statsListRepository.findAll(
|
||||||
|
StatsListSpecifications.orderByStat(Timeframe.WEEKLY, "XP"));
|
||||||
|
|
||||||
|
List<StatsList> filtered = result.stream()
|
||||||
|
.filter(s -> s.getStatValue(Timeframe.WEEKLY, "XP") > 0)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
assertTrue(filtered.size() >= 3);
|
||||||
|
assertEquals(80, filtered.get(0).getStatValue(Timeframe.WEEKLY, "XP"));
|
||||||
|
assertEquals(30, filtered.get(1).getStatValue(Timeframe.WEEKLY, "XP"));
|
||||||
|
assertEquals(10, filtered.get(2).getStatValue(Timeframe.WEEKLY, "XP"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void orderByStat_monthly_co2_descendingOrder() {
|
||||||
|
List<StatsList> result = statsListRepository.findAll(
|
||||||
|
StatsListSpecifications.orderByStat(Timeframe.MONTHLY, "CO2_SAVED"));
|
||||||
|
|
||||||
|
List<StatsList> filtered = result.stream()
|
||||||
|
.filter(s -> s.getStatValue(Timeframe.MONTHLY, "CO2_SAVED") > 0)
|
||||||
|
.toList();
|
||||||
|
|
||||||
|
assertTrue(filtered.size() >= 3);
|
||||||
|
assertEquals(500, filtered.get(0).getStatValue(Timeframe.MONTHLY, "CO2_SAVED"));
|
||||||
|
assertEquals(300, filtered.get(1).getStatValue(Timeframe.MONTHLY, "CO2_SAVED"));
|
||||||
|
assertEquals(100, filtered.get(2).getStatValue(Timeframe.MONTHLY, "CO2_SAVED"));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void higherThan_total_xp_findsCorrectUsers() {
|
||||||
|
List<StatsList> result = statsListRepository.findAll(
|
||||||
|
StatsListSpecifications.higherThan(Timeframe.TOTAL, "XP", 75));
|
||||||
|
|
||||||
|
assertTrue(result.size() >= 2);
|
||||||
|
assertTrue(result.stream()
|
||||||
|
.allMatch(s -> s.getStatValue(Timeframe.TOTAL, "XP") > 75));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void higherThan_weekly_xp_exactBoundary() {
|
||||||
|
List<StatsList> result = statsListRepository.findAll(
|
||||||
|
StatsListSpecifications.higherThan(Timeframe.WEEKLY, "XP", 30));
|
||||||
|
|
||||||
|
assertTrue(result.stream()
|
||||||
|
.allMatch(s -> s.getStatValue(Timeframe.WEEKLY, "XP") > 30));
|
||||||
|
assertTrue(result.stream()
|
||||||
|
.anyMatch(s -> s.getStatValue(Timeframe.WEEKLY, "XP") == 80));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void higherThan_monthly_co2_noResults() {
|
||||||
|
List<StatsList> result = statsListRepository.findAll(
|
||||||
|
StatsListSpecifications.higherThan(Timeframe.MONTHLY, "CO2_SAVED", 600));
|
||||||
|
|
||||||
|
assertTrue(result.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void higherThan_total_xp_allOwnResults() {
|
||||||
|
List<StatsList> result = statsListRepository.findAll(
|
||||||
|
StatsListSpecifications.higherThan(Timeframe.TOTAL, "XP", 0));
|
||||||
|
|
||||||
|
assertTrue(result.size() >= 3);
|
||||||
|
assertTrue(result.stream()
|
||||||
|
.allMatch(s -> s.getStatValue(Timeframe.TOTAL, "XP") > 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void combined_higherThan_and_orderByStat() {
|
||||||
|
List<StatsList> result = statsListRepository.findAll(
|
||||||
|
StatsListSpecifications.higherThan(Timeframe.TOTAL, "XP", 75)
|
||||||
|
.and(StatsListSpecifications.orderByStat(Timeframe.TOTAL, "XP")));
|
||||||
|
|
||||||
|
assertTrue(result.size() >= 2);
|
||||||
|
assertTrue(result.stream()
|
||||||
|
.allMatch(s -> s.getStatValue(Timeframe.TOTAL, "XP") > 75));
|
||||||
|
assertEquals(200, result.get(0).getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
assertEquals(100, result.get(1).getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
package SuMoC.backend.user.service;
|
||||||
|
|
||||||
|
import SuMoC.backend.gamification.Timeframe;
|
||||||
|
import SuMoC.backend.user.dtos.StatScope;
|
||||||
|
import SuMoC.backend.user.models.User;
|
||||||
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
|
import SuMoC.backend.user.stats.models.StatsList;
|
||||||
|
import SuMoC.backend.user.stats.StatsService;
|
||||||
|
import jakarta.transaction.Transactional;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.security.test.context.support.WithMockUser;
|
||||||
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
|
import static SuMoC.backend.Factories.UserTestFactory.uniqueUser;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
@SpringBootTest
|
||||||
|
@ActiveProfiles("test")
|
||||||
|
@Transactional
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
public class StatsServiceTest {
|
||||||
|
|
||||||
|
@Autowired private StatsService statsService;
|
||||||
|
@Autowired private UserRepository userRepository;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setup() {
|
||||||
|
userRepository.save(uniqueUser(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
private StatsList currentUserStats() {
|
||||||
|
return userRepository.findByEmail("test1@test.de").orElseThrow().getStats();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testAddStatsToCurrentUser() {
|
||||||
|
// exception
|
||||||
|
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
|
||||||
|
() -> statsService.addStatsToCurrentUser("NON_EXISTING", 100, StatScope.TOTAL, false, false));
|
||||||
|
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||||
|
|
||||||
|
// scope = null
|
||||||
|
statsService.addStatsToCurrentUser("XP", 10, null, false, false);
|
||||||
|
assertEquals(10, currentUserStats().getStatValue(Timeframe.WEEKLY, "XP"));
|
||||||
|
assertEquals(10, currentUserStats().getStatValue(Timeframe.MONTHLY, "XP"));
|
||||||
|
assertEquals(10, currentUserStats().getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
|
||||||
|
// scope = ALL
|
||||||
|
statsService.addStatsToCurrentUser("XP", 10, StatScope.ALL, false, false);
|
||||||
|
assertEquals(20, currentUserStats().getStatValue(Timeframe.WEEKLY, "XP"));
|
||||||
|
assertEquals(20, currentUserStats().getStatValue(Timeframe.MONTHLY, "XP"));
|
||||||
|
assertEquals(20, currentUserStats().getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
|
||||||
|
// scope = TOTAL
|
||||||
|
statsService.addStatsToCurrentUser("KM_CYCLED", 30, StatScope.TOTAL, false, false);
|
||||||
|
assertEquals(30, currentUserStats().getStatValue(Timeframe.TOTAL, "KM_CYCLED"));
|
||||||
|
assertEquals(0, currentUserStats().getStatValue(Timeframe.WEEKLY, "KM_CYCLED"));
|
||||||
|
|
||||||
|
// scope = MONTHLY
|
||||||
|
statsService.addStatsToCurrentUser("CO2_SAVED", 20, StatScope.MONTHLY, false, false);
|
||||||
|
assertEquals(20, currentUserStats().getStatValue(Timeframe.MONTHLY, "CO2_SAVED"));
|
||||||
|
assertEquals(0, currentUserStats().getStatValue(Timeframe.WEEKLY, "CO2_SAVED"));
|
||||||
|
|
||||||
|
// scope = WEEKLY
|
||||||
|
statsService.addStatsToCurrentUser("KM_WALKED", 10, StatScope.WEEKLY, false, false);
|
||||||
|
assertEquals(10, currentUserStats().getStatValue(Timeframe.WEEKLY, "KM_WALKED"));
|
||||||
|
assertEquals(0, currentUserStats().getStatValue(Timeframe.MONTHLY, "KM_WALKED"));
|
||||||
|
|
||||||
|
// awardBadges / awardChallenges Flags
|
||||||
|
assertDoesNotThrow(() -> statsService.addStatsToCurrentUser("XP", 1, StatScope.ALL, true, false));
|
||||||
|
assertDoesNotThrow(() -> statsService.addStatsToCurrentUser("XP", 1, StatScope.ALL, false, true));
|
||||||
|
assertDoesNotThrow(() -> statsService.addStatsToCurrentUser("XP", 1, StatScope.ALL, true, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testGetStats() {
|
||||||
|
statsService.addStatsToCurrentUser("XP", 77, StatScope.TOTAL, false, false);
|
||||||
|
StatsList stats = statsService.getStats();
|
||||||
|
assertNotNull(stats);
|
||||||
|
assertEquals(77, stats.getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testResetWeeklyStats() {
|
||||||
|
User user2 = userRepository.save(uniqueUser(2));
|
||||||
|
statsService.addStatsToCurrentUser("XP", 100, StatScope.ALL, false, false);
|
||||||
|
user2.getStats().addToAllStats("XP", 100);
|
||||||
|
userRepository.save(user2);
|
||||||
|
|
||||||
|
statsService.resetWeeklyStats();
|
||||||
|
|
||||||
|
// WEEKLY = 0, keep MONTHLY & TOTAL
|
||||||
|
assertEquals(0, currentUserStats().getStatValue(Timeframe.WEEKLY, "XP"));
|
||||||
|
assertEquals(100, currentUserStats().getStatValue(Timeframe.MONTHLY, "XP"));
|
||||||
|
assertEquals(100, currentUserStats().getStatValue(Timeframe.TOTAL, "XP"));
|
||||||
|
|
||||||
|
userRepository.findAll().forEach(u ->
|
||||||
|
assertEquals(0, u.getStats().getStatValue(Timeframe.WEEKLY, "XP")));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void testResetMonthlyStats() {
|
||||||
|
statsService.addStatsToCurrentUser("CO2_SAVED", 200, StatScope.ALL, false, false);
|
||||||
|
|
||||||
|
statsService.resetMonthlyStats();
|
||||||
|
|
||||||
|
// MONTHLY = 0, keep WEEKLY & TOTAL
|
||||||
|
assertEquals(0, currentUserStats().getStatValue(Timeframe.MONTHLY, "CO2_SAVED"));
|
||||||
|
assertEquals(200, currentUserStats().getStatValue(Timeframe.WEEKLY, "CO2_SAVED"));
|
||||||
|
assertEquals(200, currentUserStats().getStatValue(Timeframe.TOTAL, "CO2_SAVED"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,23 +3,24 @@ package SuMoC.backend.user.service;
|
|||||||
import SuMoC.backend.images.ImageBase64Util;
|
import SuMoC.backend.images.ImageBase64Util;
|
||||||
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
import SuMoC.backend.user.dtos.MaximalUserDTO;
|
||||||
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
import SuMoC.backend.user.dtos.MinimalUserDTO;
|
||||||
|
import SuMoC.backend.user.enums.FriendShipStatus;
|
||||||
|
import SuMoC.backend.user.enums.RoleName;
|
||||||
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
import SuMoC.backend.user.enums.VisibilityPrivacy;
|
||||||
|
import SuMoC.backend.user.models.Friendship;
|
||||||
import SuMoC.backend.user.models.User;
|
import SuMoC.backend.user.models.User;
|
||||||
|
import SuMoC.backend.user.repository.FriendshipRepository;
|
||||||
import SuMoC.backend.user.repository.UserRepository;
|
import SuMoC.backend.user.repository.UserRepository;
|
||||||
import jakarta.transaction.Transactional;
|
import jakarta.transaction.Transactional;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.jdbc.EmbeddedDatabaseConnection;
|
|
||||||
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
|
|
||||||
import org.springframework.boot.test.context.SpringBootTest;
|
import org.springframework.boot.test.context.SpringBootTest;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
import org.springframework.security.test.context.support.WithMockUser;
|
import org.springframework.security.test.context.support.WithMockUser;
|
||||||
import org.springframework.test.context.ActiveProfiles;
|
import org.springframework.test.context.ActiveProfiles;
|
||||||
import org.springframework.web.multipart.MultipartFile;
|
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
|
||||||
import java.awt.*;
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
||||||
import static SuMoC.backend.Factories.UserTestFactory.uniqueUser;
|
import static SuMoC.backend.Factories.UserTestFactory.uniqueUser;
|
||||||
@@ -36,16 +37,20 @@ public class UserServiceTest {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private UserRepository userRepository;
|
private UserRepository userRepository;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private FriendshipRepository friendshipRepository;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private PasswordEncoder passwordEncoder;
|
private PasswordEncoder passwordEncoder;
|
||||||
|
|
||||||
private User sender;
|
private User sender;
|
||||||
private User differentUser;
|
private User differentUser;
|
||||||
|
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() {
|
void setUp() {
|
||||||
|
friendshipRepository.deleteAll();
|
||||||
userRepository.deleteAll();
|
userRepository.deleteAll();
|
||||||
|
|
||||||
sender = userRepository.save(uniqueUser(1));
|
sender = userRepository.save(uniqueUser(1));
|
||||||
differentUser = userRepository.save(uniqueUser(2));
|
differentUser = userRepository.save(uniqueUser(2));
|
||||||
}
|
}
|
||||||
@@ -54,101 +59,209 @@ public class UserServiceTest {
|
|||||||
@Test
|
@Test
|
||||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
void testGetUser() {
|
void testGetUser() {
|
||||||
|
// visibility NONE -> public name shown
|
||||||
// Set different user to Private
|
|
||||||
MinimalUserDTO noneSetting = userService.getUser(differentUser.getId());
|
MinimalUserDTO noneSetting = userService.getUser(differentUser.getId());
|
||||||
assertNotNull(noneSetting);
|
assertNotNull(noneSetting);
|
||||||
assertEquals(differentUser.getPublicName(), noneSetting.getDisplayName());
|
assertEquals(differentUser.getPublicName(), noneSetting.getDisplayName());
|
||||||
|
|
||||||
// Set different user to Friends Only
|
// visibility FRIENDS_ONLY -> public name shown
|
||||||
differentUser.setVisibilityPrivacy(VisibilityPrivacy.FRIENDS_ONLY);
|
differentUser.setVisibilityPrivacy(VisibilityPrivacy.FRIENDS_ONLY);
|
||||||
userRepository.save(differentUser);
|
userRepository.save(differentUser);
|
||||||
MinimalUserDTO friendsOnlySetting = userService.getUser(differentUser.getId());
|
MinimalUserDTO friendsOnly = userService.getUser(differentUser.getId());
|
||||||
assertNotNull(friendsOnlySetting);
|
assertNotNull(friendsOnly);
|
||||||
assertEquals(differentUser.getPublicName(), friendsOnlySetting.getDisplayName());
|
assertEquals(differentUser.getPublicName(), friendsOnly.getDisplayName());
|
||||||
|
|
||||||
// Set different user to Public
|
// visibility PUBLIC -> private name shown
|
||||||
differentUser.setVisibilityPrivacy(VisibilityPrivacy.PUBLIC);
|
differentUser.setVisibilityPrivacy(VisibilityPrivacy.PUBLIC);
|
||||||
userRepository.save(differentUser);
|
userRepository.save(differentUser);
|
||||||
MinimalUserDTO publicSetting = userService.getUser(differentUser.getId());
|
MinimalUserDTO publicSetting = userService.getUser(differentUser.getId());
|
||||||
assertNotNull(publicSetting);
|
assertNotNull(publicSetting);
|
||||||
assertEquals(differentUser.getPrivateName(), publicSetting.getDisplayName());
|
assertEquals(differentUser.getPrivateName(), publicSetting.getDisplayName());
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
public void testDeleteUser() {
|
void testGetUser_notFound() {
|
||||||
// Try deleting another user
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.getUser(99999L)
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testGetUser_blocked() {
|
||||||
|
Friendship blocked = new Friendship(sender, differentUser, FriendShipStatus.BLOCKED);
|
||||||
|
friendshipRepository.save(blocked);
|
||||||
|
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.getUser(differentUser.getId())
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.FORBIDDEN, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testDeleteUser() {
|
||||||
|
// delete other user -> forbidden
|
||||||
assertThrows(RuntimeException.class, () -> userService.deleteUser(differentUser.getId()));
|
assertThrows(RuntimeException.class, () -> userService.deleteUser(differentUser.getId()));
|
||||||
assertEquals(2, userRepository.count());
|
assertEquals(2, userRepository.count());
|
||||||
|
|
||||||
|
// delete own profile
|
||||||
// Deleting own Profile
|
|
||||||
userService.deleteUser(sender.getId());
|
userService.deleteUser(sender.getId());
|
||||||
assertEquals(1, userRepository.count());
|
assertEquals(1, userRepository.count());
|
||||||
|
|
||||||
assertTrue(userRepository.findById(sender.getId()).isEmpty());
|
assertTrue(userRepository.findById(sender.getId()).isEmpty());
|
||||||
assertTrue(userRepository.findById(differentUser.getId()).isPresent());
|
assertTrue(userRepository.findById(differentUser.getId()).isPresent());
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"ADMIN"})
|
||||||
|
void testDeleteUser_asAdmin() {
|
||||||
|
sender.getRoles().add(RoleName.ADMIN);
|
||||||
|
userRepository.save(sender);
|
||||||
|
|
||||||
|
// admin deletes other user -> allowed
|
||||||
|
userService.deleteUser(differentUser.getId());
|
||||||
|
assertTrue(userRepository.findById(differentUser.getId()).isEmpty());
|
||||||
|
|
||||||
|
sender.getRoles().remove(RoleName.ADMIN);
|
||||||
|
userRepository.save(sender);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
public void testSetPassword() {
|
void testDeleteUser_notFound() {
|
||||||
|
// non-existent id, no admin role -> hits NOT_FOUND
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.deleteUser(99999L)
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"ADMIN"})
|
||||||
|
void testDeleteUser_asAdmin_notFound() {
|
||||||
|
sender.getRoles().add(RoleName.ADMIN);
|
||||||
|
userRepository.save(sender);
|
||||||
|
|
||||||
|
// admin bypasses permission check but user still doesn't exist -> NOT_FOUND
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.deleteUser(99999L)
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
||||||
|
|
||||||
|
sender.getRoles().remove(RoleName.ADMIN);
|
||||||
|
userRepository.save(sender);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testDeleteMobilityData() {
|
||||||
|
assertDoesNotThrow(() -> userService.deleteMobilityData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testSetPassword() {
|
||||||
String newPassword = "newPassword";
|
String newPassword = "newPassword";
|
||||||
|
|
||||||
// Check if user can change different user's password
|
// change other users password -> forbidden
|
||||||
assertThrows(RuntimeException.class, () -> userService.setPassword(differentUser.getId(), newPassword));
|
assertThrows(RuntimeException.class, () -> userService.setPassword(differentUser.getId(), newPassword));
|
||||||
assertEquals(differentUser.getPassword(), userRepository.findById(differentUser.getId()).get().getPassword());
|
assertEquals(differentUser.getPassword(), userRepository.findById(differentUser.getId()).get().getPassword());
|
||||||
|
|
||||||
// Check if user can change his own password
|
// password too short -> rejected
|
||||||
|
|
||||||
// Too short password
|
|
||||||
assertThrows(RuntimeException.class, () -> userService.setPassword(sender.getId(), "test"));
|
assertThrows(RuntimeException.class, () -> userService.setPassword(sender.getId(), "test"));
|
||||||
// TODO: check why this assertion fails (most likely because of password encoding internals)
|
|
||||||
// assertTrue(passwordEncoder.matches("password1", userRepository.findById(sender.getId()).get().getPassword()));
|
|
||||||
|
|
||||||
// Valid password
|
// valid password -> updated
|
||||||
userService.setPassword(sender.getId(), newPassword);
|
userService.setPassword(sender.getId(), newPassword);
|
||||||
assertTrue(passwordEncoder.matches(newPassword, userRepository.findById(sender.getId()).get().getPassword()));
|
assertTrue(passwordEncoder.matches(newPassword, userRepository.findById(sender.getId()).get().getPassword()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testSetPassword_invalid() {
|
||||||
|
// Blank password
|
||||||
|
ResponseStatusException blank = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.setPassword(sender.getId(), " ")
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.BAD_REQUEST, blank.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
public void testSetEmail() {
|
void testSetPassword_eightChars() {
|
||||||
String newEmail = "wd@wd.wd";
|
String eightCharPassword = "exactly8";
|
||||||
String invalidEmail = "test";
|
assertDoesNotThrow(() -> userService.setPassword(sender.getId(), eightCharPassword));
|
||||||
|
assertTrue(passwordEncoder.matches(eightCharPassword,
|
||||||
|
userRepository.findById(sender.getId()).get().getPassword()));
|
||||||
|
}
|
||||||
|
|
||||||
// Check if user can change different user's email
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"ADMIN"})
|
||||||
|
void testSetPassword_asAdmin() {
|
||||||
|
sender.getRoles().add(RoleName.ADMIN);
|
||||||
|
userRepository.save(sender);
|
||||||
|
|
||||||
|
String newPassword = "adminSet8";
|
||||||
|
assertDoesNotThrow(() -> userService.setPassword(differentUser.getId(), newPassword));
|
||||||
|
assertTrue(passwordEncoder.matches(newPassword,
|
||||||
|
userRepository.findById(differentUser.getId()).get().getPassword()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"ADMIN"})
|
||||||
|
void testSetPassword_asAdmin_notFound() {
|
||||||
|
sender.getRoles().add(RoleName.ADMIN);
|
||||||
|
userRepository.save(sender);
|
||||||
|
|
||||||
|
// admin bypasses permission check but user doesn't exist -> NOT_FOUND
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.setPassword(99999L, "validPass8")
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testSetEmail() {
|
||||||
|
String newEmail = "wd@wd.wd";
|
||||||
|
|
||||||
|
// change other users email -> forbidden
|
||||||
assertThrows(RuntimeException.class, () -> userService.setEmail(differentUser.getId(), newEmail));
|
assertThrows(RuntimeException.class, () -> userService.setEmail(differentUser.getId(), newEmail));
|
||||||
assertEquals(differentUser.getEmail(), userRepository.findById(differentUser.getId()).get().getEmail());
|
assertEquals(differentUser.getEmail(), userRepository.findById(differentUser.getId()).get().getEmail());
|
||||||
|
|
||||||
|
// email already taken -> rejected
|
||||||
// Check if user can change his own email
|
|
||||||
|
|
||||||
// Other user's email
|
|
||||||
assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), differentUser.getEmail()));
|
assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), differentUser.getEmail()));
|
||||||
assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
|
assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
|
||||||
|
|
||||||
// Invalid email format
|
// invalid email format -> rejected
|
||||||
assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), invalidEmail));
|
assertThrows(RuntimeException.class, () -> userService.setEmail(sender.getId(), "test"));
|
||||||
assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
|
assertEquals(sender.getEmail(), userRepository.findById(sender.getId()).get().getEmail());
|
||||||
|
|
||||||
// Valid email
|
// valid email -> updated
|
||||||
userService.setEmail(sender.getId(), newEmail);
|
userService.setEmail(sender.getId(), newEmail);
|
||||||
assertEquals(newEmail, userRepository.findById(sender.getId()).get().getEmail());
|
assertEquals(newEmail, userRepository.findById(sender.getId()).get().getEmail());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testSetEmail_normalized() {
|
||||||
|
String upperEmail = "NEW@EMAIL.DE";
|
||||||
|
userService.setEmail(sender.getId(), upperEmail);
|
||||||
|
assertEquals(upperEmail.toLowerCase(),
|
||||||
|
userRepository.findById(sender.getId()).get().getEmail());
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
public void testSetVisibilityPrivacy() {
|
void testSetVisibilityPrivacy() {
|
||||||
userService.setVisibilityPrivacy(VisibilityPrivacy.NONE);
|
userService.setVisibilityPrivacy(VisibilityPrivacy.NONE);
|
||||||
assertEquals(VisibilityPrivacy.NONE, userRepository.findById(sender.getId()).get().getVisibilityPrivacy());
|
assertEquals(VisibilityPrivacy.NONE, userRepository.findById(sender.getId()).get().getVisibilityPrivacy());
|
||||||
|
|
||||||
@@ -161,18 +274,57 @@ public class UserServiceTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
public void testSetPrivateName() {
|
void testSetPrivateName() {
|
||||||
String newPrivateName = "newPrivateName";
|
String newName = "newPrivateName";
|
||||||
assertThrows(RuntimeException.class, () -> userService.setPrivateName(differentUser.getId(), newPrivateName));
|
|
||||||
|
// change other users name -> forbidden
|
||||||
|
assertThrows(RuntimeException.class, () -> userService.setPrivateName(differentUser.getId(), newName));
|
||||||
assertEquals(differentUser.getPrivateName(), userRepository.findById(differentUser.getId()).get().getPrivateName());
|
assertEquals(differentUser.getPrivateName(), userRepository.findById(differentUser.getId()).get().getPrivateName());
|
||||||
|
|
||||||
userService.setPrivateName(sender.getId(), newPrivateName);
|
// change own name -> updated
|
||||||
assertEquals(newPrivateName, userRepository.findById(sender.getId()).get().getPrivateName());
|
userService.setPrivateName(sender.getId(), newName);
|
||||||
|
assertEquals(newName, userRepository.findById(sender.getId()).get().getPrivateName());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
public void testGetSelf() {
|
void testSetPrivateName_forbidden() {
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.setPrivateName(99999L, "name")
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.FORBIDDEN, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"ADMIN"})
|
||||||
|
void testSetPrivateName_asAdmin() {
|
||||||
|
sender.getRoles().add(RoleName.ADMIN);
|
||||||
|
userRepository.save(sender);
|
||||||
|
|
||||||
|
// admin changes other users name -> allowed
|
||||||
|
String newName = "adminSetName";
|
||||||
|
assertDoesNotThrow(() -> userService.setPrivateName(differentUser.getId(), newName));
|
||||||
|
assertEquals(newName, userRepository.findById(differentUser.getId()).get().getPrivateName());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"ADMIN"})
|
||||||
|
void testSetPrivateName_asAdmin_notFound() {
|
||||||
|
sender.getRoles().add(RoleName.ADMIN);
|
||||||
|
userRepository.save(sender);
|
||||||
|
|
||||||
|
// admin bypasses permission check but user doesn't exist -> NOT_FOUND
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.setPrivateName(99999L, "name")
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testGetSelf() {
|
||||||
MaximalUserDTO selfDTO = userService.getSelf();
|
MaximalUserDTO selfDTO = userService.getSelf();
|
||||||
assertNotNull(selfDTO);
|
assertNotNull(selfDTO);
|
||||||
assertEquals(sender.getId(), selfDTO.getId());
|
assertEquals(sender.getId(), selfDTO.getId());
|
||||||
@@ -184,41 +336,174 @@ public class UserServiceTest {
|
|||||||
assertEquals(0, selfDTO.getFriendships().size());
|
assertEquals(0, selfDTO.getFriendships().size());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// setProfilePicture / getProfilePicture
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
public void testGetSetProfilePicture() throws IOException {
|
void testProfilePicture() throws IOException {
|
||||||
|
// no picture set yet -> not found
|
||||||
|
assertThrows(ResponseStatusException.class, () -> userService.getProfilePicture(sender.getId()));
|
||||||
|
|
||||||
// Own profile -> should throw before picture is set
|
// set own picture
|
||||||
assertThrows(ResponseStatusException.class , () -> userService.getProfilePicture(sender.getId()));
|
byte[] image = new byte[]{1, 2, 3, 4, 5};
|
||||||
|
|
||||||
byte[] image = new byte[]{1,2,3,4,5};
|
|
||||||
String base64Image = ImageBase64Util.encode(image);
|
String base64Image = ImageBase64Util.encode(image);
|
||||||
userService.setProfilePicture(sender.getId(), base64Image);
|
userService.setProfilePicture(sender.getId(), base64Image);
|
||||||
|
|
||||||
// Get profile picture
|
// get own picture -> matches
|
||||||
String profilePicture = userService.getProfilePicture(sender.getId()).getBase64ProfilePicture();
|
String profilePicture = userService.getProfilePicture(sender.getId()).getBase64ProfilePicture();
|
||||||
assertNotNull(profilePicture);
|
assertNotNull(profilePicture);
|
||||||
assertEquals(base64Image.getBytes().length, profilePicture.length());
|
assertEquals(base64Image.getBytes().length, profilePicture.length());
|
||||||
assertEquals(base64Image, profilePicture);
|
assertEquals(base64Image, profilePicture);
|
||||||
|
|
||||||
assertEquals(ImageBase64Util.decode(base64Image).length, image.length);
|
|
||||||
assertArrayEquals(image, ImageBase64Util.decode(base64Image));
|
assertArrayEquals(image, ImageBase64Util.decode(base64Image));
|
||||||
|
|
||||||
// Different user's profile picture -> should throw
|
// set/get other users picture (non-public) -> forbidden
|
||||||
assertThrows(ResponseStatusException.class , () -> userService.setProfilePicture(differentUser.getId(), base64Image));
|
assertThrows(ResponseStatusException.class, () -> userService.setProfilePicture(differentUser.getId(), base64Image));
|
||||||
assertThrows(ResponseStatusException.class , () -> userService.getProfilePicture(differentUser.getId()));
|
assertThrows(ResponseStatusException.class, () -> userService.getProfilePicture(differentUser.getId()));
|
||||||
|
|
||||||
// Different user's profile picture with public visibility -> should work
|
// get public users picture -> accessible
|
||||||
User anotherUser = userRepository.save(uniqueUser(3));
|
User anotherUser = userRepository.save(uniqueUser(3));
|
||||||
anotherUser.setVisibilityPrivacy(VisibilityPrivacy.PUBLIC);
|
anotherUser.setVisibilityPrivacy(VisibilityPrivacy.PUBLIC);
|
||||||
userRepository.save(anotherUser);
|
userRepository.save(anotherUser);
|
||||||
byte[] secondImage = new byte[]{10,20,30,40,50};
|
byte[] secondImage = new byte[]{10, 20, 30, 40, 50};
|
||||||
anotherUser.getProfileImage().setImageData(secondImage);
|
anotherUser.getProfileImage().setImageData(secondImage);
|
||||||
byte[] profilePicture2 = ImageBase64Util.decode(userService.getProfilePicture(anotherUser.getId()).getBase64ProfilePicture());
|
byte[] profilePicture2 = ImageBase64Util.decode(userService.getProfilePicture(anotherUser.getId()).getBase64ProfilePicture());
|
||||||
assertNotNull(profilePicture2);
|
assertNotNull(profilePicture2);
|
||||||
assertEquals(secondImage.length, profilePicture2.length);
|
|
||||||
assertArrayEquals(secondImage, profilePicture2);
|
assertArrayEquals(secondImage, profilePicture2);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testSetProfilePicture_invalidBase64() {
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.setProfilePicture(sender.getId(), "!!!kein-base64!!!")
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.BAD_REQUEST, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testGetProfilePicture_notFound() {
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.getProfilePicture(99999L)
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testGetSelf_profilePicture() {
|
||||||
|
// imageData is null -> no base64 in DTO
|
||||||
|
sender.getProfileImage().setImageData(null);
|
||||||
|
userRepository.save(sender);
|
||||||
|
assertNull(userService.getSelf().getBase64ProfilePicture());
|
||||||
|
|
||||||
|
// imageData is set -> base64 in DTO
|
||||||
|
byte[] image = new byte[]{1, 2, 3, 4, 5};
|
||||||
|
sender.getProfileImage().setImageData(image);
|
||||||
|
userRepository.save(sender);
|
||||||
|
assertEquals(ImageBase64Util.encode(image), userService.getSelf().getBase64ProfilePicture());
|
||||||
|
|
||||||
|
// profileImage is null -> no base64 in DTO
|
||||||
|
sender.setProfileImage(null);
|
||||||
|
userRepository.save(sender);
|
||||||
|
userRepository.flush();
|
||||||
|
assertNull(userService.getSelf().getBase64ProfilePicture());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testGetProfilePicture_publicWithoutPicture() {
|
||||||
|
User publicUser = userRepository.save(uniqueUser(4));
|
||||||
|
publicUser.setVisibilityPrivacy(VisibilityPrivacy.PUBLIC);
|
||||||
|
userRepository.save(publicUser);
|
||||||
|
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.getProfilePicture(publicUser.getId())
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testSetProfilePicture_nullEntity() {
|
||||||
|
sender.setProfileImage(null);
|
||||||
|
userRepository.save(sender);
|
||||||
|
userRepository.flush();
|
||||||
|
|
||||||
|
byte[] image = new byte[]{1, 2, 3};
|
||||||
|
String base64Image = ImageBase64Util.encode(image);
|
||||||
|
|
||||||
|
assertDoesNotThrow(() -> userService.setProfilePicture(sender.getId(), base64Image));
|
||||||
|
|
||||||
|
User updated = userRepository.findById(sender.getId()).orElseThrow();
|
||||||
|
assertNotNull(updated.getProfileImage());
|
||||||
|
assertArrayEquals(image, updated.getProfileImage().getImageData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"ADMIN"})
|
||||||
|
void testSetProfilePicture_asAdmin() {
|
||||||
|
sender.getRoles().add(RoleName.ADMIN);
|
||||||
|
userRepository.save(sender);
|
||||||
|
|
||||||
|
// admin sets other users picture -> allowed
|
||||||
|
byte[] image = new byte[]{5, 6, 7};
|
||||||
|
String base64Image = ImageBase64Util.encode(image);
|
||||||
|
assertDoesNotThrow(() -> userService.setProfilePicture(differentUser.getId(), base64Image));
|
||||||
|
assertArrayEquals(image, userRepository.findById(differentUser.getId()).get().getProfileImage().getImageData());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"ADMIN"})
|
||||||
|
void testSetProfilePicture_asAdmin_notFound() {
|
||||||
|
sender.getRoles().add(RoleName.ADMIN);
|
||||||
|
userRepository.save(sender);
|
||||||
|
|
||||||
|
// admin bypasses permission check but user doesnt exist -> NOT_FOUND
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.setProfilePicture(99999L, ImageBase64Util.encode(new byte[]{1}))
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.NOT_FOUND, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testGetProfilePicture_ownPicture_noPrivacyCheck() {
|
||||||
|
// sender accesses own picture
|
||||||
|
byte[] image = new byte[]{1, 2, 3};
|
||||||
|
sender.getProfileImage().setImageData(image);
|
||||||
|
userRepository.save(sender);
|
||||||
|
|
||||||
|
byte[] result = ImageBase64Util.decode(userService.getProfilePicture(sender.getId()).getBase64ProfilePicture());
|
||||||
|
assertArrayEquals(image, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testGetProfilePicture_nonPublicOtherUser_forbidden() {
|
||||||
|
// other user is not public -> FORBIDDEN
|
||||||
|
byte[] image = new byte[]{1, 2, 3};
|
||||||
|
differentUser.getProfileImage().setImageData(image);
|
||||||
|
differentUser.setVisibilityPrivacy(VisibilityPrivacy.NONE);
|
||||||
|
userRepository.save(differentUser);
|
||||||
|
|
||||||
|
ResponseStatusException ex = assertThrows(
|
||||||
|
ResponseStatusException.class,
|
||||||
|
() -> userService.getProfilePicture(differentUser.getId())
|
||||||
|
);
|
||||||
|
assertEquals(HttpStatus.FORBIDDEN, ex.getStatusCode());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@WithMockUser(username = "test1@test.de", roles = {"USER"})
|
||||||
|
void testGetTotalXP() {
|
||||||
|
Long xp = userService.getTotalXP();
|
||||||
|
assertNotNull(xp);
|
||||||
|
assertTrue(xp >= 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -6,6 +6,7 @@ spring.datasource.driver-class-name=org.postgresql.Driver
|
|||||||
spring.jpa.hibernate.ddl-auto=create-drop
|
spring.jpa.hibernate.ddl-auto=create-drop
|
||||||
spring.jpa.show-sql=true
|
spring.jpa.show-sql=true
|
||||||
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
|
||||||
|
spring.flyway.enabled=false
|
||||||
logging.level.org.springframework.security=Trace
|
logging.level.org.springframework.security=Trace
|
||||||
springdoc.api-docs.path=/v3/api-docs
|
springdoc.api-docs.path=/v3/api-docs
|
||||||
springdoc.swagger-ui.path=/swagger-ui.html
|
springdoc.swagger-ui.path=/swagger-ui.html
|
||||||
|
|||||||
Reference in New Issue
Block a user