From 39915373001ac4db46d48861148b069e8b6e32b8 Mon Sep 17 00:00:00 2001
From: Matthis Bauer <mb420@hdm-stuttgart.de>
Date: Sun, 14 Jan 2024 15:23:11 +0100
Subject: [PATCH] added BracketRound, changed Match logic, added bracket
 creation, created exceptions #25 #24

---
 sth-backend/pom.xml                           |  12 +-
 .../controller/TournamentController.java      |  17 +--
 .../BracketAlreadyInitializedException.java   |  15 +++
 .../exeptions/InsufficientTeamsException.java |  15 +++
 .../sthbackend/mapper/ModelToDTOMapper.java   |  71 ++++++------
 .../hdm/mi/sthbackend/model/BracketRound.java |  19 +++
 .../java/hdm/mi/sthbackend/model/Match.java   |   8 +-
 .../hdm/mi/sthbackend/model/Tournament.java   |  13 ++-
 .../sthbackend/service/TournamentService.java |  96 +++++++++++++---
 .../dummyObjects/dummyTournaments.java        |  48 ++++++++
 .../serviceTests/CreacteBracketTest.java      | 108 ++++++++++++++++++
 .../serviceTests/FillBracketRandomTest.java   |  52 +++++++++
 12 files changed, 410 insertions(+), 64 deletions(-)
 create mode 100644 sth-backend/src/main/java/hdm/mi/sthbackend/exeptions/BracketAlreadyInitializedException.java
 create mode 100644 sth-backend/src/main/java/hdm/mi/sthbackend/exeptions/InsufficientTeamsException.java
 create mode 100644 sth-backend/src/main/java/hdm/mi/sthbackend/model/BracketRound.java
 create mode 100644 sth-backend/src/test/java/hdm/mi/sthbackend/dummyObjects/dummyTournaments.java
 create mode 100644 sth-backend/src/test/java/hdm/mi/sthbackend/serviceTests/CreacteBracketTest.java
 create mode 100644 sth-backend/src/test/java/hdm/mi/sthbackend/serviceTests/FillBracketRandomTest.java

diff --git a/sth-backend/pom.xml b/sth-backend/pom.xml
index 18c77c9..539b22f 100644
--- a/sth-backend/pom.xml
+++ b/sth-backend/pom.xml
@@ -21,6 +21,11 @@
 			<groupId>org.springframework.boot</groupId>
 			<artifactId>spring-boot-starter-security</artifactId>
 		</dependency>
+		<dependency>
+			<groupId>org.mockito</groupId>
+			<artifactId>mockito-core</artifactId>
+			<version>5.8.0</version>
+		</dependency>
 		<dependency>
 			<groupId>org.springframework.boot</groupId>
 			<artifactId>spring-boot-starter-web</artifactId>
@@ -61,8 +66,13 @@
 			<artifactId>spring-boot-starter-data-mongodb</artifactId>
 			<version>3.2.0</version>
 		</dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
 
-	</dependencies>
+    </dependencies>
 
 	<build>
 		<plugins>
diff --git a/sth-backend/src/main/java/hdm/mi/sthbackend/controller/TournamentController.java b/sth-backend/src/main/java/hdm/mi/sthbackend/controller/TournamentController.java
index 8a90615..16288fb 100644
--- a/sth-backend/src/main/java/hdm/mi/sthbackend/controller/TournamentController.java
+++ b/sth-backend/src/main/java/hdm/mi/sthbackend/controller/TournamentController.java
@@ -7,6 +7,7 @@ import hdm.mi.sthbackend.dto.TeamDTO;
 import hdm.mi.sthbackend.dto.TournamentDTO;
 import hdm.mi.sthbackend.exeptions.*;
 import hdm.mi.sthbackend.model.Match;
+import hdm.mi.sthbackend.model.Tournament;
 import hdm.mi.sthbackend.service.TournamentService;
 import hdm.mi.sthbackend.types.TeamMatchScore;
 import hdm.mi.sthbackend.types.TeamName;
@@ -56,6 +57,10 @@ public class TournamentController {
                                          @PathVariable UUID teamId) throws TournamentIdNotFoundException, TeamIdNotFoundException {
         return service.deleteAndRemoveTeamFromTournament(tournamentId, teamId);
     }
+    @PatchMapping("tournaments/{tournamentId}/matches/{matchId}/teams/{teamId}/assignTeamToMatch")
+    public Tournament assignTeamToMatch(@PathVariable UUID tournamentId, @PathVariable UUID matchId, @PathVariable UUID teamId, @RequestBody int bracketRound, @RequestBody TeamMatchScore score) throws TournamentIdNotFoundException, MatchIdNotFoundException {
+        return service.assignTeamToMatch(tournamentId, bracketRound, matchId, teamId, score.getScore());
+    }
 
     @PostMapping("/teams/{teamId}/addPlayer")
     public PlayerDTO addPlayerToTeam(@PathVariable UUID teamId,
@@ -79,10 +84,6 @@ public class TournamentController {
     /**
      * Match Endpoints
      */
-    @PatchMapping("matches/{matchId}/teams/{teamId}/assignTeamToMatch")
-    public MatchDTO assignTeamToMatch(@PathVariable UUID matchId, @PathVariable UUID teamId, @RequestBody TeamMatchScore score) throws MatchIdNotFoundException {
-        return service.assignTeamToMatch(matchId, teamId, score.getScore());
-    }
 
     @PatchMapping("matches/{matchId}/teams/{teamId}/updateScore")
     public MatchDTO updateScore(@PathVariable UUID matchId, @PathVariable UUID teamId, @RequestBody TeamMatchScore newScore) throws MatchIdNotFoundException, TeamIdNotFoundException {
@@ -99,17 +100,17 @@ public class TournamentController {
      * Tournament Endpoints
      */
     @GetMapping("/tournaments/{tournamentId}")
-    public TournamentDTO findTournamentById(@PathVariable UUID tournamentId) throws TournamentIdNotFoundException {
+    public Tournament findTournamentById(@PathVariable UUID tournamentId) throws TournamentIdNotFoundException {
         return service.getTournament(tournamentId);
     }
 
     @PostMapping("/tournaments")
-    public TournamentDTO createTournament(@RequestBody TournamentName params) {
-        return service.createTournament(params.getName());
+    public Tournament createTournament(@RequestBody Tournament tournament) {
+        return service.createTournament(tournament);
     }
 
     @DeleteMapping("/tournaments/{tournamentId}")
-    public TournamentDTO deleteTournament(@PathVariable UUID tournamentId) throws TournamentIdNotFoundException {
+    public Tournament deleteTournament(@PathVariable UUID tournamentId) throws TournamentIdNotFoundException {
         return service.deleteTournament(tournamentId);
     }
 
diff --git a/sth-backend/src/main/java/hdm/mi/sthbackend/exeptions/BracketAlreadyInitializedException.java b/sth-backend/src/main/java/hdm/mi/sthbackend/exeptions/BracketAlreadyInitializedException.java
new file mode 100644
index 0000000..e5f0de9
--- /dev/null
+++ b/sth-backend/src/main/java/hdm/mi/sthbackend/exeptions/BracketAlreadyInitializedException.java
@@ -0,0 +1,15 @@
+package hdm.mi.sthbackend.exeptions;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.UUID;
+
+public class BracketAlreadyInitializedException extends Exception{
+    private final Logger log = LogManager.getLogger("BracketAlreadyInitializedException");
+
+    public BracketAlreadyInitializedException(UUID tournamentId){
+        super(String.format("Bracket of %s (tournamentId) already initialized", tournamentId.toString()));
+    }
+
+}
diff --git a/sth-backend/src/main/java/hdm/mi/sthbackend/exeptions/InsufficientTeamsException.java b/sth-backend/src/main/java/hdm/mi/sthbackend/exeptions/InsufficientTeamsException.java
new file mode 100644
index 0000000..34c6cdc
--- /dev/null
+++ b/sth-backend/src/main/java/hdm/mi/sthbackend/exeptions/InsufficientTeamsException.java
@@ -0,0 +1,15 @@
+package hdm.mi.sthbackend.exeptions;
+
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.UUID;
+
+public class InsufficientTeamsException extends Exception{
+    private final Logger log = LogManager.getLogger("InsufficientTeamsException");
+
+    public InsufficientTeamsException(UUID tournamentId){
+        super(String.format("Insufficient Teams in %s.", tournamentId.toString()));
+    }
+
+}
diff --git a/sth-backend/src/main/java/hdm/mi/sthbackend/mapper/ModelToDTOMapper.java b/sth-backend/src/main/java/hdm/mi/sthbackend/mapper/ModelToDTOMapper.java
index 897da40..b9418ca 100644
--- a/sth-backend/src/main/java/hdm/mi/sthbackend/mapper/ModelToDTOMapper.java
+++ b/sth-backend/src/main/java/hdm/mi/sthbackend/mapper/ModelToDTOMapper.java
@@ -46,41 +46,42 @@ public class ModelToDTOMapper {
         this.playerRepository = playerRepository;
     }
 
-    public TournamentDTO mapToTournamentDTO(Tournament tournament) {
-        Map<UUID, Match> matches = new HashMap<>();
-        tournament.getMatches()
-                .forEach(mId -> {
-                    try {
-                        matches.put(mId, matchRepository.findById(mId)
-                                .orElseThrow(() -> new MatchIdNotFoundException(mId)));
-                    } catch (MatchIdNotFoundException e) {
-                        log.debug("Match with id " + mId + " not found");
-                    }
-                });
-        Map<UUID, MatchDTO> mappedMatches = matches.entrySet()
-                .stream()
-                .collect(Collectors.toMap(Entry::getKey, e -> mapToMatchDTO(e.getValue())));
-
-        Map<UUID, Team> teams = new HashMap<>();
-        tournament.getTeams()
-                .forEach(teamId -> {
-                    try {
-                        teams.put(teamId, teamRepository.findById(teamId)
-                                .orElseThrow(() -> new TournamentIdNotFoundException(teamId)));
-                    } catch (TournamentIdNotFoundException e) {
-                        log.debug("Team with id " + teamId + " not found");
-                    }
-                });
-        Map<UUID, TeamDTO> mappedTeams = teams.entrySet()
-                .stream()
-                .collect(Collectors.toMap(Entry::getKey, e -> mapToTeamDTO(e.getValue())));
-        return new TournamentDTO(
-                tournament.getTournamentId(),
-                tournament.getTournamentName(),
-                mappedMatches,
-                mappedTeams
-        );
-    }
+    //todo
+//    public TournamentDTO mapToTournamentDTO(Tournament tournament) {
+//        Map<UUID, Match> matches = new HashMap<>();
+//        tournament.getMatches()
+//                .forEach(mId -> {
+//                    try {
+//                        matches.put(mId, matchRepository.findById(mId)
+//                                .orElseThrow(() -> new MatchIdNotFoundException(mId)));
+//                    } catch (MatchIdNotFoundException e) {
+//                        log.debug("Match with id " + mId + " not found");
+//                    }
+//                });
+//        Map<UUID, MatchDTO> mappedMatches = matches.entrySet()
+//                .stream()
+//                .collect(Collectors.toMap(Entry::getKey, e -> mapToMatchDTO(e.getValue())));
+//
+//        Map<UUID, Team> teams = new HashMap<>();
+//        tournament.getTeams()
+//                .forEach(teamId -> {
+//                    try {
+//                        teams.put(teamId, teamRepository.findById(teamId)
+//                                .orElseThrow(() -> new TournamentIdNotFoundException(teamId)));
+//                    } catch (TournamentIdNotFoundException e) {
+//                        log.debug("Team with id " + teamId + " not found");
+//                    }
+//                });
+//        Map<UUID, TeamDTO> mappedTeams = teams.entrySet()
+//                .stream()
+//                .collect(Collectors.toMap(Entry::getKey, e -> mapToTeamDTO(e.getValue())));
+//        return new TournamentDTO(
+//                tournament.getTournamentId(),
+//                tournament.getTournamentName(),
+//                mappedMatches,
+//                mappedTeams
+//        );
+//    }
 
     public MatchDTO mapToMatchDTO(Match match) {
         return new MatchDTO(
diff --git a/sth-backend/src/main/java/hdm/mi/sthbackend/model/BracketRound.java b/sth-backend/src/main/java/hdm/mi/sthbackend/model/BracketRound.java
new file mode 100644
index 0000000..1875694
--- /dev/null
+++ b/sth-backend/src/main/java/hdm/mi/sthbackend/model/BracketRound.java
@@ -0,0 +1,19 @@
+package hdm.mi.sthbackend.model;
+
+import lombok.Getter;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.*;
+
+public class BracketRound {
+    private final Logger log = LogManager.getLogger("BracketRound");
+    @Getter
+    Map<UUID, Match> matches;
+    int round;
+
+    public BracketRound(int round){
+        this.round = round;
+        matches = new HashMap<>();
+    }
+}
diff --git a/sth-backend/src/main/java/hdm/mi/sthbackend/model/Match.java b/sth-backend/src/main/java/hdm/mi/sthbackend/model/Match.java
index 8041fd1..1eeecc5 100644
--- a/sth-backend/src/main/java/hdm/mi/sthbackend/model/Match.java
+++ b/sth-backend/src/main/java/hdm/mi/sthbackend/model/Match.java
@@ -8,18 +8,19 @@ import org.apache.logging.log4j.Logger;
 import org.springframework.data.annotation.Id;
 import org.springframework.data.mongodb.core.mapping.Document;
 
+import java.util.HashMap;
 import java.util.Map;
 import java.util.UUID;
 
 @Getter
 @Document("Match")
-@AllArgsConstructor
 public class Match {
     private static final Logger log = LogManager.getLogger(Match.class);
 
     @Id
     private UUID matchId;
 
+    @Getter
     private Map<UUID, Integer> teamScores;
 
     @Setter
@@ -30,4 +31,9 @@ public class Match {
 
     @Setter
     private UUID nextMatchId;
+
+    public Match(UUID matchId){
+        this.matchId = matchId;
+        this.teamScores = new HashMap<>();
+    }
 }
diff --git a/sth-backend/src/main/java/hdm/mi/sthbackend/model/Tournament.java b/sth-backend/src/main/java/hdm/mi/sthbackend/model/Tournament.java
index 4012eb1..18356b4 100644
--- a/sth-backend/src/main/java/hdm/mi/sthbackend/model/Tournament.java
+++ b/sth-backend/src/main/java/hdm/mi/sthbackend/model/Tournament.java
@@ -6,6 +6,7 @@ import lombok.Setter;
 import org.springframework.data.annotation.Id;
 import org.springframework.data.mongodb.core.mapping.Document;
 
+import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;
@@ -18,8 +19,14 @@ public class Tournament implements ITournament{
     private UUID tournamentId;
     @Setter
     private String tournamentName;
-
-    private List<UUID> matches;
-
+    @Setter
+    private List<BracketRound> bracket;
     private List<UUID> teams;
+
+    public Tournament(String tournamentName, List<UUID> teams){
+        this.tournamentId = UUID.randomUUID();
+        this.tournamentName = tournamentName;
+        this.teams = teams;
+        this.bracket = new ArrayList<>();
+    }
 }
diff --git a/sth-backend/src/main/java/hdm/mi/sthbackend/service/TournamentService.java b/sth-backend/src/main/java/hdm/mi/sthbackend/service/TournamentService.java
index 857ff61..fadff03 100644
--- a/sth-backend/src/main/java/hdm/mi/sthbackend/service/TournamentService.java
+++ b/sth-backend/src/main/java/hdm/mi/sthbackend/service/TournamentService.java
@@ -6,10 +6,7 @@ import hdm.mi.sthbackend.dto.TeamDTO;
 import hdm.mi.sthbackend.dto.TournamentDTO;
 import hdm.mi.sthbackend.exeptions.*;
 import hdm.mi.sthbackend.mapper.ModelToDTOMapper;
-import hdm.mi.sthbackend.model.Match;
-import hdm.mi.sthbackend.model.Player;
-import hdm.mi.sthbackend.model.Team;
-import hdm.mi.sthbackend.model.Tournament;
+import hdm.mi.sthbackend.model.*;
 import hdm.mi.sthbackend.repository.IMatchRepository;
 import hdm.mi.sthbackend.repository.IPlayerRepository;
 import hdm.mi.sthbackend.repository.ITeamRepository;
@@ -145,11 +142,10 @@ public class TournamentService {
         return teamId;
     }
 
-    public TournamentDTO createTournament(String tournamentName) {
-        Tournament tournament = new Tournament(UUID.randomUUID(), tournamentName, new ArrayList<>(), new ArrayList<>());
+    public Tournament createTournament(Tournament tournament) {
         tournamentRepository.insert(tournament);
         log.debug("created Tournament " + tournament.getTournamentId());
-        return mapper.mapToTournamentDTO(tournament);
+        return tournament;
     }
 
     public UUID determineWinner (UUID matchId) throws MatchIdNotFoundException, WinnerNotDeterminedException {
@@ -166,13 +162,25 @@ public class TournamentService {
         return winnerTeamId;
     }
 
-    public MatchDTO assignTeamToMatch(UUID matchId, UUID teamId, int score) throws MatchIdNotFoundException {
-        Match match = matchRepository.findById(matchId).orElseThrow(() -> new MatchIdNotFoundException(matchId));
+    public Tournament assignTeamToMatch(UUID tournamentId, int bracketRound, UUID matchId, UUID teamId, int score) throws TournamentIdNotFoundException, MatchIdNotFoundException {
+        Tournament tournament = tournamentRepository.findById(tournamentId)
+                .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId));
+        try{
+            tournament
+                    .getBracket()
+                    .get(bracketRound)
+                    .getMatches()
+                    .get(matchId)
+                    .getTeamScores()
+                    .put(teamId, score);
+        }
+        catch (Exception e){
+            throw new MatchIdNotFoundException(matchId);
+        }
 
-        match.getTeamScores().put(teamId,score);
-        matchRepository.save(match);
+        tournamentRepository.save(tournament);
         log.debug("Team " + teamId + " assign to Match " + matchId );
-        return mapper.mapToMatchDTO(match);
+        return tournament;
     }
 
 
@@ -207,23 +215,79 @@ public class TournamentService {
         log.debug("Tournament Name for TournamentID " + tournamentId + " updated to " + newTournamentName);
         return tournamentId;
     }
-    public TournamentDTO getTournament(UUID tournamentId) throws TournamentIdNotFoundException {
+    public Tournament getTournament(UUID tournamentId) throws TournamentIdNotFoundException {
         Tournament tournament = tournamentRepository.findById(tournamentId)
                 .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId));
 
         log.debug(tournament + "is found");
-        return mapper.mapToTournamentDTO(tournament);
+        return tournament;
     }
 
-    public TournamentDTO deleteTournament(UUID tournamentId) throws TournamentIdNotFoundException {
+    public Tournament deleteTournament(UUID tournamentId) throws TournamentIdNotFoundException {
         Tournament tournamentToDelete = tournamentRepository.findById(tournamentId)
                 .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId));
 
         tournamentRepository.delete(tournamentToDelete);
         log.debug("Tournament " + tournamentId + " has been deleted");
-        return mapper.mapToTournamentDTO(tournamentToDelete);
+        return tournamentToDelete;
+    }
+
+    public Tournament createBracket(UUID tournamentId) throws TournamentIdNotFoundException, InsufficientTeamsException, BracketAlreadyInitializedException{
+        Tournament tournament = tournamentRepository.findById(tournamentId)
+                .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId));
+        List<UUID> teams = tournament.getTeams();
+
+        if(teams.size() < 2){
+            throw new InsufficientTeamsException(tournamentId);
+        }
+
+        // log zur Basis 2 von der Anzahl der Teams (aufgerundet)
+        int roundCount = (int) Math.ceil(Math.log(teams.size()) / Math.log(2));
+
+        if(tournament.getBracket().size() == 0){
+            tournament.setBracket(new ArrayList<>());
+            for(int i = 0; i < roundCount; i++){
+                // richtige Anzahl an BracketRounds hinzufügen
+                tournament.getBracket().add(new BracketRound(i));
+
+                // anzahl der matches errechnen
+                int matchCount = (int) (Math.pow(2, roundCount)) / (int) Math.pow(2, i + 1);
+
+                for(int j = 0; j < matchCount; j++){
+                    // matches hinzufügen
+                    UUID matchId = UUID.randomUUID();
+                    tournament.getBracket().get(i).getMatches().put(matchId, new Match(matchId));
+                }
+            }
+        }
+        else{
+            throw new BracketAlreadyInitializedException(tournamentId);
+        }
+        tournamentRepository.save(tournament);
+        return tournament;
     }
 
+    public Tournament fillBracketRandom(UUID tournamentId) throws TournamentIdNotFoundException {
+        Tournament tournament = tournamentRepository.findById(tournamentId)
+                .orElseThrow(() -> new TournamentIdNotFoundException(tournamentId));
+        List<UUID> teams = tournament.getTeams();
+
+        Random random = new Random();
+        for(int i = 0; i < 2; i++){
+            for(Match match: tournament.getBracket().get(0).getMatches().values()){
+                if(teams.size() > 0){
+                    int teamIndex = random.nextInt(0, teams.size());
+                    match.getTeamScores().put(teams.get(teamIndex), 0);
+                    teams.remove(teamIndex);
+                }
+                else{
+                    break;
+                }
+            }
+        }
+        tournamentRepository.save(tournament);
+        return tournament;
+    }
     /*
     Weitere Methoden:
     UpdateTeamScore  Marius
diff --git a/sth-backend/src/test/java/hdm/mi/sthbackend/dummyObjects/dummyTournaments.java b/sth-backend/src/test/java/hdm/mi/sthbackend/dummyObjects/dummyTournaments.java
new file mode 100644
index 0000000..2d5c9ee
--- /dev/null
+++ b/sth-backend/src/test/java/hdm/mi/sthbackend/dummyObjects/dummyTournaments.java
@@ -0,0 +1,48 @@
+package hdm.mi.sthbackend.dummyObjects;
+
+import hdm.mi.sthbackend.model.Tournament;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.UUID;
+
+public class dummyTournaments {
+    private final Logger log = LogManager.getLogger("dummyTournaments");
+    public static UUID dummyTournamentId = UUID.randomUUID();
+
+    public static Tournament t1 = new Tournament(dummyTournamentId, "TestTournament", new ArrayList<>(),
+            new ArrayList<>(Arrays.asList(
+                    UUID.randomUUID(), UUID.randomUUID())));
+    public static Tournament t2 = new Tournament(dummyTournamentId, "TestTournament", new ArrayList<>(),
+            new ArrayList<>(Arrays.asList(
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())));
+    public static Tournament t3 = new Tournament(dummyTournamentId, "TestTournament", new ArrayList<>(),
+            new ArrayList<>(Arrays.asList(
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(),
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())));
+    public static Tournament t4 = new Tournament(dummyTournamentId, "TestTournament", new ArrayList<>(),
+            new ArrayList<>(Arrays.asList(
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(),
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(),
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(),
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())));
+    public static Tournament t11 = new Tournament(dummyTournamentId, "TestTournament", new ArrayList<>(),
+            new ArrayList<>(Arrays.asList(
+                    UUID.randomUUID())));
+    public static Tournament t12 = new Tournament(dummyTournamentId, "TestTournament", new ArrayList<>(),
+            new ArrayList<>(Arrays.asList(
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())));
+    public static Tournament t13 = new Tournament(dummyTournamentId, "TestTournament", new ArrayList<>(),
+            new ArrayList<>(Arrays.asList(
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(),
+                    UUID.randomUUID())));
+    public static Tournament t14 = new Tournament(dummyTournamentId, "TestTournament", new ArrayList<>(),
+            new ArrayList<>(Arrays.asList(
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(),
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(),
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID(),
+                    UUID.randomUUID(), UUID.randomUUID(), UUID.randomUUID())));
+
+}
diff --git a/sth-backend/src/test/java/hdm/mi/sthbackend/serviceTests/CreacteBracketTest.java b/sth-backend/src/test/java/hdm/mi/sthbackend/serviceTests/CreacteBracketTest.java
new file mode 100644
index 0000000..03fc5ea
--- /dev/null
+++ b/sth-backend/src/test/java/hdm/mi/sthbackend/serviceTests/CreacteBracketTest.java
@@ -0,0 +1,108 @@
+package hdm.mi.sthbackend.serviceTests;
+
+import hdm.mi.sthbackend.exeptions.BracketAlreadyInitializedException;
+import hdm.mi.sthbackend.exeptions.InsufficientTeamsException;
+import hdm.mi.sthbackend.exeptions.TournamentIdNotFoundException;
+import hdm.mi.sthbackend.model.Tournament;
+import hdm.mi.sthbackend.repository.ITournamentRepository;
+import hdm.mi.sthbackend.service.TournamentService;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+import org.junit.jupiter.api.Assertions;
+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 static hdm.mi.sthbackend.dummyObjects.dummyTournaments.*;
+import static org.mockito.Mockito.*;
+
+import java.util.Optional;
+
+@ExtendWith(MockitoExtension.class)
+public class CreacteBracketTest {
+
+    @Mock
+    public ITournamentRepository tournamentRepository;
+    @InjectMocks
+    public TournamentService tournamentService;
+
+    private final Logger log = LogManager.getLogger("CreateBracketTest");
+
+    @Test
+    public void create2TeamBracketTest() throws TournamentIdNotFoundException, InsufficientTeamsException, BracketAlreadyInitializedException {
+        when(tournamentRepository.findById(dummyTournamentId)).thenReturn(Optional.of(t1));
+
+        Tournament resultTournament = tournamentService.createBracket(dummyTournamentId);
+        Assertions.assertEquals(1, resultTournament.getBracket().size());
+        Assertions.assertEquals(1, resultTournament.getBracket().get(0).getMatches().size());
+    }
+    @Test
+    public void create4TeamBracketTest() throws TournamentIdNotFoundException, InsufficientTeamsException, BracketAlreadyInitializedException {
+        when(tournamentRepository.findById(dummyTournamentId)).thenReturn(Optional.of(t2));
+
+        Tournament resultTournament = tournamentService.createBracket(dummyTournamentId);
+        Assertions.assertEquals(2, resultTournament.getBracket().size());
+        Assertions.assertEquals(2, resultTournament.getBracket().get(0).getMatches().size());
+        Assertions.assertEquals(1, resultTournament.getBracket().get(1).getMatches().size());
+    }
+    @Test
+    public void create8TeamBracketTest() throws TournamentIdNotFoundException, InsufficientTeamsException, BracketAlreadyInitializedException {
+        when(tournamentRepository.findById(dummyTournamentId)).thenReturn(Optional.of(t3));
+
+        Tournament resultTournament = tournamentService.createBracket(dummyTournamentId);
+        Assertions.assertEquals(3, resultTournament.getBracket().size());
+        Assertions.assertEquals(4, resultTournament.getBracket().get(0).getMatches().size());
+        Assertions.assertEquals(2, resultTournament.getBracket().get(1).getMatches().size());
+        Assertions.assertEquals(1, resultTournament.getBracket().get(2).getMatches().size());
+    }
+    @Test
+    public void create16TeamBracketTest() throws TournamentIdNotFoundException, InsufficientTeamsException, BracketAlreadyInitializedException {
+        when(tournamentRepository.findById(dummyTournamentId)).thenReturn(Optional.of(t4));
+
+        Tournament resultTournament = tournamentService.createBracket(dummyTournamentId);
+        Assertions.assertEquals(4, resultTournament.getBracket().size());
+        Assertions.assertEquals(8, resultTournament.getBracket().get(0).getMatches().size());
+        Assertions.assertEquals(4, resultTournament.getBracket().get(1).getMatches().size());
+        Assertions.assertEquals(2, resultTournament.getBracket().get(2).getMatches().size());
+        Assertions.assertEquals(1, resultTournament.getBracket().get(3).getMatches().size());
+    }
+    @Test
+    public void create1TeamBracketTest(){
+        when(tournamentRepository.findById(dummyTournamentId)).thenReturn(Optional.of(t11));
+
+        Assertions.assertThrows(InsufficientTeamsException.class, () -> tournamentService.createBracket(dummyTournamentId));
+    }
+    @Test
+    public void create3TeamBracketTest() throws TournamentIdNotFoundException, InsufficientTeamsException, BracketAlreadyInitializedException {
+        when(tournamentRepository.findById(dummyTournamentId)).thenReturn(Optional.of(t12));
+
+        Tournament resultTournament = tournamentService.createBracket(dummyTournamentId);
+        Assertions.assertEquals(2, resultTournament.getBracket().size());
+        Assertions.assertEquals(2, resultTournament.getBracket().get(0).getMatches().size());
+        Assertions.assertEquals(1, resultTournament.getBracket().get(1).getMatches().size());
+    }
+    @Test
+    public void create5TeamBracketTest() throws TournamentIdNotFoundException, InsufficientTeamsException, BracketAlreadyInitializedException {
+        when(tournamentRepository.findById(dummyTournamentId)).thenReturn(Optional.of(t13));
+
+        Tournament resultTournament = tournamentService.createBracket(dummyTournamentId);
+        Assertions.assertEquals(3, resultTournament.getBracket().size());
+        Assertions.assertEquals(4, resultTournament.getBracket().get(0).getMatches().size());
+        Assertions.assertEquals(2, resultTournament.getBracket().get(1).getMatches().size());
+        Assertions.assertEquals(1, resultTournament.getBracket().get(2).getMatches().size());
+    }
+    @Test
+    public void create15TeamBracketTest() throws TournamentIdNotFoundException, InsufficientTeamsException, BracketAlreadyInitializedException {
+        when(tournamentRepository.findById(dummyTournamentId)).thenReturn(Optional.of(t14));
+
+        Tournament resultTournament = tournamentService.createBracket(dummyTournamentId);
+        Assertions.assertEquals(4, resultTournament.getBracket().size(), 4);
+        Assertions.assertEquals(8, resultTournament.getBracket().get(0).getMatches().size());
+        Assertions.assertEquals(4, resultTournament.getBracket().get(1).getMatches().size());
+        Assertions.assertEquals(2, resultTournament.getBracket().get(2).getMatches().size());
+        Assertions.assertEquals(1, resultTournament.getBracket().get(3).getMatches().size());
+    }
+
+}
diff --git a/sth-backend/src/test/java/hdm/mi/sthbackend/serviceTests/FillBracketRandomTest.java b/sth-backend/src/test/java/hdm/mi/sthbackend/serviceTests/FillBracketRandomTest.java
new file mode 100644
index 0000000..d977821
--- /dev/null
+++ b/sth-backend/src/test/java/hdm/mi/sthbackend/serviceTests/FillBracketRandomTest.java
@@ -0,0 +1,52 @@
+package hdm.mi.sthbackend.serviceTests;
+
+import hdm.mi.sthbackend.exeptions.TournamentIdNotFoundException;
+import hdm.mi.sthbackend.model.BracketRound;
+import hdm.mi.sthbackend.model.Match;
+import hdm.mi.sthbackend.model.Tournament;
+import hdm.mi.sthbackend.repository.ITournamentRepository;
+import hdm.mi.sthbackend.service.TournamentService;
+import org.apache.logging.log4j.LogManager;
+import org.apache.logging.log4j.Logger;
+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.util.ArrayList;
+import java.util.Optional;
+import java.util.UUID;
+
+import static hdm.mi.sthbackend.dummyObjects.dummyTournaments.*;
+import static org.mockito.Mockito.when;
+
+@ExtendWith(MockitoExtension.class)
+public class FillBracketRandomTest {
+    private final Logger log = LogManager.getLogger("FillBracketTest");
+
+    @Mock
+    ITournamentRepository tournamentRepository;
+    @InjectMocks
+    TournamentService tournamentService;
+
+
+    @Test
+    public void fill2TeamBracketRandomTest() throws TournamentIdNotFoundException {
+        Tournament t1withMatches = t1;
+        t1withMatches.setBracket(new ArrayList<>());
+        t1withMatches.getBracket().add(new BracketRound(0));
+        UUID matchId = UUID.randomUUID();
+        t1withMatches.getBracket().get(0).getMatches().put(matchId, new Match(matchId));
+
+        when(tournamentRepository.findById(dummyTournamentId)).thenReturn(Optional.of(t1withMatches));
+        Tournament t1Filled = tournamentService.fillBracketRandom(dummyTournamentId);
+
+        int teamSum = t1Filled.getBracket()
+                .stream()
+                .flatMap(bracketRound -> bracketRound.getMatches().values().stream())
+                .map(match -> match.getTeamScores().size())
+                .reduce(0, Integer::sum);
+    }
+
+}
-- 
GitLab