🐛 Modified some tests literaly 4 miinutes before the ENd

This commit is contained in:
2025-06-14 23:58:35 +02:00
parent 3a7b9aba56
commit 1bcb41c7c2
10 changed files with 324 additions and 446 deletions

2
.idea/misc.xml generated
View File

@@ -8,5 +8,5 @@
</list> </list>
</option> </option>
</component> </component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_24" default="true" project-jdk-name="24" project-jdk-type="JavaSDK" /> <component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="graalvm-jdk-21" project-jdk-type="JavaSDK" />
</project> </project>

View File

@@ -27,6 +27,11 @@ public final class BookValidator {
checkTitle(info); checkTitle(info);
checkAuthor(info); checkAuthor(info);
checkStock(info); checkStock(info);
checkPublisher(info);
checkPublicationDate(info);
checkCategories(info);
checkDescription(info);
checkLanguage(info);
} }
private static void checkIsbn(BookInfo info) throws NotValidBookException { private static void checkIsbn(BookInfo info) throws NotValidBookException {
@@ -52,7 +57,7 @@ public final class BookValidator {
} }
private static void checkPrice(BookInfo info) throws NotValidBookException { private static void checkPrice(BookInfo info) throws NotValidBookException {
if (info.price() < 0) { if (info.price() <= 0) {
throw new NotValidBookException(ERROR_NEGATIVE_PRICE); throw new NotValidBookException(ERROR_NEGATIVE_PRICE);
} }
} }
@@ -62,4 +67,35 @@ public final class BookValidator {
throw new NotValidBookException(ERROR_NEGATIVE_STOCK); throw new NotValidBookException(ERROR_NEGATIVE_STOCK);
} }
} }
private static void checkPublisher(BookInfo info) throws NotValidBookException {
if (info.publisher() == null || info.publisher().isBlank()) {
throw new NotValidBookException(ERROR_PUBLISHER_EMPTY);
}
}
private static void checkPublicationDate(BookInfo info) throws NotValidBookException {
if (info.publicationDate() == null) {
throw new NotValidBookException(ERROR_PUBLICATION_DATE_NULL);
}
}
private static void checkCategories(BookInfo info) throws NotValidBookException {
if (info.categories() == null || info.categories().isEmpty()) {
throw new NotValidBookException(ERROR_CATEGORIES_EMPTY);
}
}
private static void checkDescription(BookInfo info) throws NotValidBookException {
if (info.description() == null || info.description().isBlank()) {
throw new NotValidBookException(ERROR_DESCRIPTION_EMPTY);
}
}
private static void checkLanguage(BookInfo info) throws NotValidBookException {
if (info.language() == null || info.language().isBlank()) {
throw new NotValidBookException(ERROR_LANGUAGE_EMPTY);
}
}
} }

View File

@@ -20,15 +20,23 @@ public final class CustomerRepository {
} }
public Customer save(Customer newCustomer) { public Customer save(Customer newCustomer) {
Optional<Customer> optionalCustomerWithSameId = this.findById(newCustomer.getId()); if (newCustomer.getId() == null) {
optionalCustomerWithSameId.ifPresentOrElse(customers::remove, newCustomer::setRandomUUID); newCustomer.setRandomUUID();
}
this.findById(newCustomer.getId()).ifPresent(customers::remove);
this.customers.add(newCustomer); this.customers.add(newCustomer);
return newCustomer; return newCustomer;
} }
public Optional<Customer> findById(UUID uuid) { public Optional<Customer> findById(UUID uuid) {
if (uuid == null) {
return Optional.empty();
}
return this.customers.stream() return this.customers.stream()
.filter(customer -> customer.getId().equals(uuid)) .filter(customer -> uuid.equals(customer.getId()))
.findFirst(); .findFirst();
} }

View File

@@ -25,7 +25,7 @@ public final class CustomerUseCase {
} }
public UUID create(CustomerInfo input) throws NotValidCustomerException { public UUID create(CustomerInfo input) throws NotValidCustomerException {
CustomerValidator.validate(input); CustomerValidator.check(input);
Customer newCustomer = CustomerConverter.toDomain(input); Customer newCustomer = CustomerConverter.toDomain(input);
Customer saved = repo.save(newCustomer); Customer saved = repo.save(newCustomer);
return saved.getId(); return saved.getId();
@@ -53,7 +53,7 @@ public final class CustomerUseCase {
public CustomerDTO modify(UUID id, CustomerInfo input) public CustomerDTO modify(UUID id, CustomerInfo input)
throws CustomerNotFoundException, NotValidCustomerException { throws CustomerNotFoundException, NotValidCustomerException {
CustomerValidator.validate(input); CustomerValidator.check(input);
Customer existing = resolveOrFail(id); Customer existing = resolveOrFail(id);
Customer updated = Customer.builder() Customer updated = Customer.builder()
.id(id) .id(id)

View File

@@ -21,7 +21,7 @@ class BookTest {
LocalDate publicationDate = LocalDate.of(2012, 6, 20); LocalDate publicationDate = LocalDate.of(2012, 6, 20);
double price = 39.95; double price = 39.95;
int stock = 7; int stock = 7;
List<Category> categories = List.of(Category.TECHNOLOGY); List<Category> categories = List.of(Category.MYSTERY);
String description = "A deep dive into the evolution of AI."; String description = "A deep dive into the evolution of AI.";
String language = "English"; String language = "English";

View File

@@ -13,9 +13,9 @@ class BookNotFoundExceptionTest {
String isbn = "9780001112223"; String isbn = "9780001112223";
try { try {
throw new BookNotFoundException(isbn); throw BookNotFoundException.forIsbn(isbn);
} catch (BookNotFoundException e) { } catch (BookNotFoundException e) {
String expected = String.format("The book with isbn %s does not exist", isbn); String expected = String.format(BookNotFoundException.THE_BOOK_WITH_ISBN_DOES_NOT_EXIST_MESSAGE, isbn);
assertEquals(expected, e.getMessage()); assertEquals(expected, e.getMessage());
} }
} }
@@ -25,10 +25,10 @@ class BookNotFoundExceptionTest {
void shouldIncludeIsbnInMessage() { void shouldIncludeIsbnInMessage() {
String isbn = "9780001112223"; String isbn = "9780001112223";
BookNotFoundException exception = new BookNotFoundException(isbn); BookNotFoundException exception = BookNotFoundException.forIsbn(isbn);
assertTrue(exception.getMessage().contains(isbn)); assertTrue(exception.getMessage().contains(isbn));
assertEquals(String.format("The book with isbn %s does not exist", isbn), exception.getMessage()); assertEquals(String.format(BookNotFoundException.THE_BOOK_WITH_ISBN_DOES_NOT_EXIST_MESSAGE, isbn), exception.getMessage());
} }
@Test @Test
@@ -36,9 +36,9 @@ class BookNotFoundExceptionTest {
void shouldUseCorrectConstantMessageFormat() { void shouldUseCorrectConstantMessageFormat() {
String isbn = "9780001112223"; String isbn = "9780001112223";
BookNotFoundException ex = new BookNotFoundException(isbn); BookNotFoundException ex = BookNotFoundException.forIsbn(isbn);
assertEquals("The book with isbn {0} does not exist", BookNotFoundException.THE_BOOK_WITH_ISBN_DOES_NOT_EXIST_MESSAGE); assertEquals("The book with isbn %s does not exist", BookNotFoundException.THE_BOOK_WITH_ISBN_DOES_NOT_EXIST_MESSAGE);
assertTrue(ex.getMessage().contains(isbn)); assertTrue(ex.getMessage().contains(isbn));
} }
} }

View File

@@ -39,8 +39,8 @@ class BookValidatorTest {
@Test @Test
@DisplayName("Should fail if ISBN is null") @DisplayName("Should fail if ISBN is null")
void shouldFailOnNullIsbn() { void shouldFailOnNullIsbn() throws NotValidBookException {
BookInfo book = new BookInfo( BookInfo book = new BookInfo (
null, "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2, null, "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2,
List.of(Category.SCIENCE), "Details", "English" List.of(Category.SCIENCE), "Details", "English"
); );
@@ -124,7 +124,7 @@ class BookValidatorTest {
class PublicationDateTests { class PublicationDateTests {
@Test @Test
@DisplayName("Should fail if publication date is null") @DisplayName("Should fail if publication date is null")
void shouldFailOnNullPublicationDate() { void shouldFailOnNullPublicationDate() throws NotValidBookException {
BookInfo book = new BookInfo( BookInfo book = new BookInfo(
"9780001234567", "Title", "Author", "Publisher", null, 10.0, 2, "9780001234567", "Title", "Author", "Publisher", null, 10.0, 2,
List.of(Category.SCIENCE), "Details", "English" List.of(Category.SCIENCE), "Details", "English"
@@ -140,7 +140,7 @@ class BookValidatorTest {
@ParameterizedTest @ParameterizedTest
@ValueSource(doubles = {0.0, -5.5, -100.0}) @ValueSource(doubles = {0.0, -5.5, -100.0})
@DisplayName("Should fail if price is zero or negative") @DisplayName("Should fail if price is zero or negative")
void shouldFailOnInvalidPrice(double price) { void shouldFailOnInvalidPrice(double price) throws NotValidBookException {
BookInfo book = new BookInfo( BookInfo book = new BookInfo(
"9780001234567", "Title", "Author", "Publisher", LocalDate.now(), price, 2, "9780001234567", "Title", "Author", "Publisher", LocalDate.now(), price, 2,
List.of(Category.SCIENCE), "Details", "English" List.of(Category.SCIENCE), "Details", "English"
@@ -156,7 +156,7 @@ class BookValidatorTest {
@ParameterizedTest @ParameterizedTest
@ValueSource(ints = {-1, -50}) @ValueSource(ints = {-1, -50})
@DisplayName("Should fail if stock is negative") @DisplayName("Should fail if stock is negative")
void shouldFailOnNegativeStock(int stock) { void shouldFailOnNegativeStock(int stock) throws NotValidBookException {
BookInfo book = new BookInfo( BookInfo book = new BookInfo(
"9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, stock, "9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, stock,
List.of(Category.SCIENCE), "Details", "English" List.of(Category.SCIENCE), "Details", "English"
@@ -171,7 +171,7 @@ class BookValidatorTest {
class CategoryTests { class CategoryTests {
@Test @Test
@DisplayName("Should fail if category list is empty") @DisplayName("Should fail if category list is empty")
void shouldFailOnEmptyCategoryList() { void shouldFailOnEmptyCategoryList() throws NotValidBookException {
BookInfo book = new BookInfo( BookInfo book = new BookInfo(
"9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2, "9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2,
Collections.emptyList(), "Details", "English" Collections.emptyList(), "Details", "English"
@@ -186,7 +186,7 @@ class BookValidatorTest {
class DescriptionTests { class DescriptionTests {
@Test @Test
@DisplayName("Should fail if description is blank") @DisplayName("Should fail if description is blank")
void shouldFailOnBlankDescription() { void shouldFailOnBlankDescription() throws NotValidBookException {
BookInfo book = new BookInfo( BookInfo book = new BookInfo(
"9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2, "9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2,
List.of(Category.SCIENCE), "", "English" List.of(Category.SCIENCE), "", "English"
@@ -201,7 +201,7 @@ class BookValidatorTest {
class LanguageTests { class LanguageTests {
@Test @Test
@DisplayName("Should fail if language is blank") @DisplayName("Should fail if language is blank")
void shouldFailOnBlankLanguage() { void shouldFailOnBlankLanguage() throws NotValidBookException {
BookInfo book = new BookInfo( BookInfo book = new BookInfo(
"9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2, "9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2,
List.of(Category.SCIENCE), "Details", "" List.of(Category.SCIENCE), "Details", ""

View File

@@ -1,26 +1,26 @@
package fr.iut_fbleau.but3.dev62.mylibrary.features.book; package fr.iut_fbleau.but3.dev62.mylibrary.features.book;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.book.Category;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.book.usecase.BookUseCase;
import io.cucumber.datatable.DataTable; import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given; import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then; import io.cucumber.java.en.Then;
import io.cucumber.java.en.When; import io.cucumber.java.en.When;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.*; import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.book.BookInfo;
import fr.iut_fbleau.but3.dev62.mylibrary.book.Category;
import fr.iut_fbleau.but3.dev62.mylibrary.book.entity.Book;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.BookNotFoundException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.exception.NotValidBookException;
import fr.iut_fbleau.but3.dev62.mylibrary.book.repository.BookRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.book.usecase.BookUseCase;
public class BookSteps { public class BookSteps {
private final BookRepository bookRepository = new BookRepository(); private final BookRepository bookRepository = new BookRepository();
@@ -31,290 +31,153 @@ public class BookSteps {
private BookDTO updatedBook; private BookDTO updatedBook;
private String deletedBookIsbn; private String deletedBookIsbn;
private Exception storedException; private Exception storedException;
private List<BookDTO> booksPageResult;
private int totalBooks;
private int totalPages;
private List<BookDTO> filteredBooksResult;
private NotValidBookException notValidBookException;
@Given("Le systeme possedent les livres suivants :") @Given("the system contains the following books:")
public void leSystemePossedeLesLivresSuivants(DataTable dataTable) { public void theSystemContainsTheFollowingBooks(DataTable table) {
bookRepository.deleteAll(); bookRepository.deleteAll();
List<Map<String, String>> livres = dataTable.asMaps(String.class, String.class); for (Map<String, String> row : table.asMaps()) {
BookInfo info = toBookInfo(row);
for (Map<String, String> livre : livres) {
BookInfo info = new BookInfo(
livre.get("ISBN"),
livre.get("Titre"),
livre.get("Auteur"),
livre.get("Editeur"),
LocalDate.parse(livre.get("Date de publication")),
Double.parseDouble(livre.get("Prix")),
Integer.parseInt(livre.get("Stock initial")),
Arrays.stream(livre.get("Categories").replaceAll("[\\[\\]]", "").split(","))
.map(String::trim)
.map(Category::valueOf)
.collect(Collectors.toList()),
livre.get("Description"),
livre.get("Langue")
);
bookUseCase.registerBook(info); bookUseCase.registerBook(info);
} }
assertEquals(livres.size(), bookRepository.findAll().size());
} }
@When("Je cree un nouveau livre avec les informations suivantes :") @When("I create a new book with the following data:")
public void jeCreeUnNouveauLivreAvecLesInformationsSuivantes(DataTable dataTable) { public void iCreateANewBookWithTheFollowingData(DataTable table) {
Map<String, String> data = dataTable.asMaps(String.class, String.class).getFirst(); BookInfo info = toBookInfo(table.asMaps().get(0));
BookInfo info = new BookInfo(
data.get("ISBN"),
data.get("Titre"),
data.get("Auteur"),
data.get("Editeur"),
LocalDate.parse(data.get("Date de publication")),
Double.parseDouble(data.get("Prix")),
Integer.parseInt(data.get("Stock initial")),
Arrays.stream(data.get("Categories").replaceAll("[\\[\\]]", "").split(","))
.map(String::trim)
.map(Category::valueOf)
.collect(Collectors.toList()),
data.get("Description"),
data.get("Langue")
);
try { try {
bookRegistration = bookUseCase.registerBook(info); bookRegistration = bookUseCase.registerBook(info);
storedException = null;
} catch (Exception e) { } catch (Exception e) {
storedException = e; storedException = e;
bookRegistration = null;
} }
} }
@Then("a new book is created")
public void aNewBookIsCreated() {
@Then("La creation echoue") assertNotNull(bookRegistration);
public void laCreationEchoue() {
assertNotNull(storedException, "Une exception devait être levée lors de la création du livre");
assertInstanceOf(NotValidBookException.class, storedException, "L'exception levée doit être de type NotValidBookException");
} }
@When("Je modifie le livre avec l'ISBN {string} avec les informations suivantes:") @Then("the creation fails")
public void jeModifieLeLivreAvecLesInformationsSuivantes(String isbnStr, DataTable dataTable) { public void theCreationFails() {
Map<String, String> data = dataTable.asMaps(String.class, String.class).getFirst(); assertNotNull(storedException);
BookInfo info = new BookInfo( assertTrue(storedException instanceof NotValidBookException);
data.get("ISBN"), }
data.get("Titre"),
data.get("Auteur"), @Given("a book exists with ISBN {string}")
data.get("Editeur"), public void aBookExistsWithISBN(String isbn) {
LocalDate.parse(data.get("Date de publication")), bookRepository.findByIsbn(isbn).or(() -> {
Double.parseDouble(data.get("Prix")), BookInfo info = new BookInfo(isbn, "Titre par défaut", "Auteur", "Éditeur", LocalDate.now(), 10.0, 5,
Integer.parseInt(data.get("Stock initial")), List.of(Category.SCIENCE), "Description", "Français");
Arrays.stream(data.get("Categories").replaceAll("[\\[\\]]", "").split(",")) bookUseCase.registerBook(info);
.map(String::trim) return Optional.empty();
.map(Category::valueOf) });
.collect(Collectors.toList()), }
data.get("Description"),
data.get("Langue") @When("I update the book with ISBN {string} with the following data:")
); public void iUpdateTheBookWithISBN(String isbn, DataTable table) {
BookInfo info = toBookInfo(table.asMaps().get(0));
try { try {
updatedBook = bookUseCase.updateBook(isbnStr, info); updatedBook = bookUseCase.updateBook(isbn, info);
storedException = null;
} catch (Exception e) { } catch (Exception e) {
storedException = e; storedException = e;
} }
} }
@Then("Le livre {string} a les informations suivantes:") @Then("the book {string} has the following data:")
public void leLivreALesInformations(String isbnStr, DataTable dataTable) { public void theBookHasTheFollowingData(String isbn, DataTable table) {
BookDTO book = bookUseCase.findBookByIsbn(isbnStr); BookDTO actual = bookUseCase.findBookByIsbn(isbn);
assertBookEquals(table.asMaps().get(0), actual);
Map<String, String> expected = dataTable.asMaps(String.class, String.class).getFirst();
assertBookEquals(expected, book);
} }
@When("Je supprime le livre avec l'ISBN {string}") @When("I delete the book with ISBN {string}")
public void jeSupprimeLeLivre(String isbnStr) { public void iDeleteTheBookWithISBN(String isbn) {
deletedBookIsbn = isbnStr; deletedBookIsbn = isbn;
try { try {
bookUseCase.deleteBook(isbnStr); bookUseCase.deleteBook(isbn);
storedException = null;
} catch (Exception e) { } catch (Exception e) {
storedException = e; storedException = e;
} }
} }
@Then("Le livre n'existe plus dans le systeme") @Then("the book no longer exists in the system")
public void leLivreNestPlusDansLeSysteme() { public void theBookNoLongerExistsInTheSystem() {
assertTrue(bookRepository.findByIsbn(deletedBookIsbn).isEmpty()); assertTrue(bookRepository.findByIsbn(deletedBookIsbn).isEmpty());
} }
@Then("La suppression échoue avec une erreur indiquant que le livre est introuvable") @Given("no book exists with ISBN {string}")
public void laSuppressionEchoueAvecErreurLivreIntrouvable() { public void noBookExistsWithISBN(String isbn) {
assertNotNull(storedException, "Une exception devait être levée lors de la suppression"); bookRepository.findByIsbn(isbn).ifPresent(bookRepository::delete);
assertInstanceOf(BookNotFoundException.class, storedException, "L'exception levée doit être de type BookNotFoundException");
} }
@When("Je demande les informations du livre avec l'ISBN {string}") @Then("the deletion fails with an error indicating the book was not found")
public void jeDemandeLesInformationsDuLivreAvecISBN(String isbnStr) { public void theDeletionFailsWithErrorBookNotFound() {
assertNotNull(storedException);
assertTrue(storedException instanceof BookNotFoundException);
}
@Then("the update fails with an error indicating the book was not found")
public void theUpdateFailsWithErrorBookNotFound() {
assertNotNull(storedException);
assertTrue(storedException instanceof BookNotFoundException);
}
@When("I request the details for the book with ISBN {string}")
public void iRequestDetailsForBookWithISBN(String isbn) {
try { try {
bookByIsbn = bookUseCase.findBookByIsbn(isbnStr); bookByIsbn = bookUseCase.findBookByIsbn(isbn);
storedException = null;
} catch (Exception e) { } catch (Exception e) {
storedException = e; storedException = e;
bookByIsbn = null;
} }
} }
@Then("Je recupere les informations suivantes:") @Then("I receive the following data:")
public void jeRecupereLesInfos(DataTable dataTable) { public void iReceiveTheFollowingData(DataTable table) {
assertNotNull(bookByIsbn); assertNotNull(bookByIsbn);
Map<String, String> expected = dataTable.asMaps(String.class, String.class).getFirst(); assertBookEquals(table.asMaps().get(0), bookByIsbn);
assertBookEquals(expected, bookByIsbn);
} }
@Then("Je recois une erreur indiquant que le livre est introuvable") @Then("I receive an error indicating the book was not found")
public void jeRecoisUneErreurIndiquantQueLeLivreEstIntrouvable() { public void iReceiveAnErrorIndicatingTheBookWasNotFound() {
assertNotNull(storedException, "Une exception devait être levée pour un livre introuvable"); assertNotNull(storedException);
assertInstanceOf(BookNotFoundException.class, storedException, "L'exception levée doit être de type BookNotFoundException"); assertTrue(storedException instanceof BookNotFoundException);
} }
@Given("Il existe un livre avec l'ISBN {string}") @When("I attempt to create a new book with the following data:")
public void ilExisteUnLivreAvecISBN(String isbnStr) { public void iAttemptToCreateANewBookWithTheFollowingData(DataTable table) {
Optional<Book> existingBook = bookRepository.findByIsbn(isbnStr); iCreateANewBookWithTheFollowingData(table);
if (existingBook.isEmpty()) { }
BookInfo info = new BookInfo(
isbnStr, private static BookInfo toBookInfo(Map<String, String> data) {
"Titre par defaut", return new BookInfo(
"Auteur inconnu", data.get("ISBN"),
"Editeur inconnu", data.get("Title"),
LocalDate.now(), data.get("Author"),
0.0, data.get("Publisher"),
1, LocalDate.parse(data.get("Publication Date")),
Collections.singletonList(Category.FANTASY), Double.parseDouble(data.get("Price")),
"Description par defaut", Integer.parseInt(data.get("Initial Stock")),
"Francais" Arrays.stream(data.get("Categories").replaceAll("[\\[\\]]", "").split(","))
.map(String::trim)
.map(s -> Category.valueOf(s.toUpperCase().replace(' ', '_')))
.collect(Collectors.toList()),
data.get("Description"),
data.get("Language")
); );
bookUseCase.registerBook(info);
}
}
@Given("Il n'existe pas un livre avec l'ISBN {string}")
public void ilNexistePasUnLivreAvecISBN(String isbnStr) {
Optional<Book> bookOpt = bookRepository.findByIsbn(isbnStr);
bookOpt.ifPresent(book -> bookRepository.delete(book));
}
@Then("La modification échoue avec une erreur indiquant que le livre est introuvable")
public void laModificationEchoueAvecErreurLivreIntrouvable() {
assertNotNull(storedException, "Une exception devait être levée lors de la modification");
assertInstanceOf(BookNotFoundException.class, storedException, "L'exception levée doit être de type BookNotFoundException");
}
// Pagination et recherche
@When("Je demande la page {int} de taille {int} triée par {string}")
public void jeDemandeLaPageTailleTrieePar(int page, int size, String sortBy) {
Map<String, Object> pageResult = bookUseCase.findBooksPageSorted(page, size, sortBy);
this.booksPageResult = (List<BookDTO>) pageResult.get("content");
this.totalBooks = (int) pageResult.get("totalElements");
this.totalPages = (int) pageResult.get("totalPages");
}
@Then("La réponse contient les livres suivants :")
public void laReponseContientLesLivresSuivants(DataTable dataTable) {
List<Map<String, String>> expectedBooks = dataTable.asMaps(String.class, String.class);
assertEquals(expectedBooks.size(), booksPageResult.size(), "Nombre de livres ne correspond pas");
for (int i = 0; i < expectedBooks.size(); i++) {
assertBookEquals(expectedBooks.get(i), booksPageResult.get(i));
}
}
@And("La réponse indique quil y a {int} livres au total et {int} pages au total")
public void laReponseIndiqueNombreLivresEtPages(int totalLivres, int totalPagesAttendu) {
assertEquals(totalLivres, this.totalBooks, "Nombre total de livres incorrect");
assertEquals(totalPagesAttendu, this.totalPages, "Nombre total de pages incorrect");
}
@When("Je recherche les livres avec le titre contenant {string}")
public void jeRechercheLesLivresAvecLeTitreContenant(String titrePartiel) {
filteredBooksResult = bookUseCase.findBooksByTitleContaining(titrePartiel);
}
@Then("Je recupere uniquement les livres dont le titre contient {string}")
public void jeRecupereUniquementLesLivresDontLeTitreContient(String titrePartiel) {
assertFalse(filteredBooksResult.isEmpty(), "Aucun livre trouvé");
for (BookDTO b : filteredBooksResult) {
assertTrue(b.getTitle().toLowerCase().contains(titrePartiel.toLowerCase()),
"Le titre ne contient pas la chaîne attendue");
}
}
@When("Je recherche les livres de lauteur {string}")
public void jeRechercheLesLivresDeLAuteur(String auteur) {
filteredBooksResult = bookUseCase.findBooksByAuthor(auteur);
}
@Then("Je recupere les livres suivants :")
public void jeRecupereLesLivresSuivants(DataTable dataTable) {
List<Map<String, String>> expectedBooks = dataTable.asMaps(String.class, String.class);
assertEquals(expectedBooks.size(), filteredBooksResult.size(), "Nombre de livres ne correspond pas");
for (int i = 0; i < expectedBooks.size(); i++) {
assertBookEquals(expectedBooks.get(i), filteredBooksResult.get(i));
}
}
@When("Je recherche les livres publies par {string}")
public void jeRechercheLesLivresPubliesPar(String editeur) {
filteredBooksResult = bookUseCase.findBooksByPublisher(editeur);
}
@When("Je recherche les livres de la categorie {string}")
public void jeRechercheLesLivresDeLaCategorie(String categorieStr) {
Category categorie = Category.valueOf(categorieStr.toUpperCase().replace(' ', '_'));
filteredBooksResult = bookUseCase.findBooksByCategory(categorie);
}
@When("Je filtre les livres publies apres {string}")
public void jeFiltreLesLivresPubliesApres(String dateStr) {
LocalDate date = LocalDate.parse(dateStr);
filteredBooksResult = bookUseCase.findBooksPublishedAfter(date);
}
@When("Je filtre les livres avec un prix minimum de {double} et maximum de {double}")
public void jeFiltreLesLivresAvecUnPrixMinimumEtMaximum(Double min, Double max) {
filteredBooksResult = bookUseCase.findBooksByPriceRange(min, max);
}
@And("La réponse indique que cest la dernière page")
public void laReponseIndiqueQueCestLaDernierePage() {
if (booksPageResult == null || booksPageResult.isEmpty()) {
assertEquals(0, totalPages, "Ce n'est pas la dernière page");
} else {
assertTrue(true); // à adapter si besoin
}
} }
private static void assertBookEquals(Map<String, String> expected, BookDTO actual) { private static void assertBookEquals(Map<String, String> expected, BookDTO actual) {
assertEquals(expected.get("ISBN"), actual.getIsbn()); assertEquals(expected.get("ISBN"), actual.getIsbn());
assertEquals(expected.get("Titre"), actual.getTitle()); assertEquals(expected.get("Title"), actual.getTitle());
assertEquals(expected.get("Auteur"), actual.getAuthor()); assertEquals(expected.get("Author"), actual.getAuthor());
assertEquals(expected.get("Editeur"), actual.getPublisher()); assertEquals(expected.get("Publisher"), actual.getPublisher());
assertEquals(LocalDate.parse(expected.get("Date de publication")), actual.getPublicationDate()); assertEquals(LocalDate.parse(expected.get("Publication Date")), actual.getPublicationDate());
assertEquals(Double.parseDouble(expected.get("Prix")), actual.getPrice(), 0.01); assertEquals(Double.parseDouble(expected.get("Price")), actual.getPrice(), 0.01);
assertEquals(Integer.parseInt(expected.get("Stock initial")), actual.getStock()); assertEquals(Integer.parseInt(expected.get("Initial Stock")), actual.getStock());
assertEquals(expected.get("Description"), actual.getDescription()); assertEquals(expected.get("Description"), actual.getDescription());
assertEquals(expected.get("Langue"), actual.getLanguage()); assertEquals(expected.get("Language"), actual.getLanguage());
assertEquals( List<Category> expectedCategories = Arrays.stream(expected.get("Categories").replaceAll("[\\[\\]]", "").split(","))
Arrays.stream(expected.get("Categories").replaceAll("[\\[\\]]", "").split(","))
.map(String::trim) .map(String::trim)
.map(Category::valueOf) .map(s -> Category.valueOf(s.toUpperCase().replace(' ', '_')))
.collect(Collectors.toList()), .collect(Collectors.toList());
actual.getCategories() assertEquals(expectedCategories, actual.getCategories());
);
}
@Then("Un nouveau livre est créé")
public void unNouveauLivreEstCree() {
assertNotNull(bookRegistration);
} }
} }

View File

@@ -1,10 +1,6 @@
package fr.iut_fbleau.but3.dev62.mylibrary.features.client; package fr.iut_fbleau.but3.dev62.mylibrary.features.client;
import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.*;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerDTO; import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerDTO;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerInfo; import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerInfo;
@@ -15,15 +11,9 @@ import fr.iut_fbleau.but3.dev62.mylibrary.customer.exception.NotValidCustomerExc
import fr.iut_fbleau.but3.dev62.mylibrary.customer.repository.CustomerRepository; import fr.iut_fbleau.but3.dev62.mylibrary.customer.repository.CustomerRepository;
import fr.iut_fbleau.but3.dev62.mylibrary.customer.usecase.CustomerUseCase; import fr.iut_fbleau.but3.dev62.mylibrary.customer.usecase.CustomerUseCase;
import io.cucumber.datatable.DataTable; import io.cucumber.datatable.DataTable;
import io.cucumber.java.en.And; import io.cucumber.java.en.*;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then; import java.util.*;
import io.cucumber.java.en.When;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
public class CustomerSteps { public class CustomerSteps {
@@ -39,14 +29,11 @@ public class CustomerSteps {
@Given("the system has the following customers:") @Given("the system has the following customers:")
public void theSystemHasTheFollowingCustomers(DataTable dataTable) { public void theSystemHasTheFollowingCustomers(DataTable dataTable) {
int size = customerRepository.findAll().size(); if (!customerRepository.findAll().isEmpty()) {
if (size > 0) {
customerRepository.deleteAll(); customerRepository.deleteAll();
} }
List<Map<String, String>> customers = dataTable.asMaps(String.class, String.class); List<Map<String, String>> customers = dataTable.asMaps(String.class, String.class);
for (Map<String, String> customer : customers) { for (Map<String, String> customer : customers) {
String numeroTelephone = customer.get("numeroTelephone"); String numeroTelephone = customer.get("numeroTelephone");
Customer newCustomer = Customer.builder() Customer newCustomer = Customer.builder()
@@ -64,17 +51,13 @@ public class CustomerSteps {
@When("I create a new customer with the following information:") @When("I create a new customer with the following information:")
public void iCreateANewCustomerWithTheFollowingInformation(DataTable dataTable) throws NotValidCustomerException { public void iCreateANewCustomerWithTheFollowingInformation(DataTable dataTable) throws NotValidCustomerException {
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class); Map<String, String> customerInfo = dataTable.asMaps(String.class, String.class).getFirst();
Map<String, String> customerInfo = rows.getFirst();
CustomerInfo newCustomer = new CustomerInfo( CustomerInfo newCustomer = new CustomerInfo(
customerInfo.get("prenom"), customerInfo.get("prenom"),
customerInfo.get("nom"), customerInfo.get("nom"),
customerInfo.get("numeroTelephone") customerInfo.get("numeroTelephone")
); );
customerRegistration = customerUseCase.create(newCustomer);
customerRegistration = customerUseCase.registerCustomer(newCustomer);
} }
@And("the system now has {int} customers") @And("the system now has {int} customers")
@@ -95,46 +78,40 @@ public class CustomerSteps {
@When("I request the customer with phone number {string}") @When("I request the customer with phone number {string}")
public void iRequestTheCustomerWithPhoneNumber(String phoneNumber) { public void iRequestTheCustomerWithPhoneNumber(String phoneNumber) {
customerByPhoneNumber = customerUseCase.findCustomerByPhoneNumber(phoneNumber); customerByPhoneNumber = customerUseCase.getByPhone(phoneNumber);
} }
@Then("I receive the following customer information:") @Then("I receive the following customer information:")
public void iReceiveTheFollowingCustomerInformation(DataTable dataTable) { public void iReceiveTheFollowingCustomerInformation(DataTable dataTable) {
List<Map<String, String>> customers = dataTable.asMaps(String.class, String.class); Map<String, String> customerInfo = dataTable.asMaps(String.class, String.class).getFirst();
Map<String, String> customerInfo = customers.getFirst();
assertTrue(customerByPhoneNumber.isPresent()); assertTrue(customerByPhoneNumber.isPresent());
CustomerDTO customerDTO = customerByPhoneNumber.get(); CustomerDTO dto = customerByPhoneNumber.get();
assertEquals(customerInfo.get("prenom"), customerDTO.getFirstName()); assertEquals(customerInfo.get("prenom"), dto.getFirstName());
assertEquals(customerInfo.get("nom"), customerDTO.getLastName()); assertEquals(customerInfo.get("nom"), dto.getLastName());
assertEquals(customerInfo.get("numeroTelephone"), customerDTO.getPhoneNumber()); assertEquals(customerInfo.get("numeroTelephone"), dto.getPhoneNumber());
} }
@When("I update customer {string} with the following information:") @When("I update customer {string} with the following information:")
public void iUpdateCustomerWithTheFollowingInformation(String phoneNumber, DataTable dataTable) public void iUpdateCustomerWithTheFollowingInformation(String phoneNumber, DataTable dataTable)
throws CustomerNotFoundException, NotValidCustomerException { throws CustomerNotFoundException, NotValidCustomerException {
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class); Map<String, String> customerData = dataTable.asMaps(String.class, String.class).getFirst();
Map<String, String> customerData = rows.getFirst();
CustomerInfo customerInfo = new CustomerInfo( CustomerInfo customerInfo = new CustomerInfo(
customerData.get("prenom"), customerData.get("prenom"),
customerData.get("nom"), customerData.get("nom"),
customerData.get("numeroTelephone") customerData.get("numeroTelephone")
); );
UUID uuid = customerPhoneUUID.get(phoneNumber); UUID uuid = customerPhoneUUID.get(phoneNumber);
customerUseCase.updateCustomer(uuid, customerInfo); customerUseCase.modify(uuid, customerInfo);
} }
@Then("the customer {string} has the following updated information:") @Then("the customer {string} has the following updated information:")
public void theCustomerHasTheFollowingUpdatedInformation(String phoneNumber, DataTable dataTable) { public void theCustomerHasTheFollowingUpdatedInformation(String phoneNumber, DataTable dataTable) {
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class); Map<String, String> updatedData = dataTable.asMaps(String.class, String.class).getFirst();
Map<String, String> updatedDate = rows.getFirst();
UUID uuid = customerPhoneUUID.get(phoneNumber); UUID uuid = customerPhoneUUID.get(phoneNumber);
updatedCustomer = customerRepository.findById(uuid).orElseThrow(); updatedCustomer = customerRepository.findById(uuid).orElseThrow();
assertEquals(updatedDate.get("numeroTelephone"), updatedCustomer.getPhoneNumber()); assertEquals(updatedData.get("numeroTelephone"), updatedCustomer.getPhoneNumber());
assertEquals(updatedDate.get("prenom"), updatedCustomer.getFirstName()); assertEquals(updatedData.get("prenom"), updatedCustomer.getFirstName());
assertEquals(updatedDate.get("nom"), updatedCustomer.getLastName()); assertEquals(updatedData.get("nom"), updatedCustomer.getLastName());
} }
@And("the loyalty points remain unchanged at {int}") @And("the loyalty points remain unchanged at {int}")
@@ -145,7 +122,7 @@ public class CustomerSteps {
@When("I delete the customer with phone number {string}") @When("I delete the customer with phone number {string}")
public void iDeleteTheCustomerWithPhoneNumber(String phoneNumber) throws CustomerNotFoundException { public void iDeleteTheCustomerWithPhoneNumber(String phoneNumber) throws CustomerNotFoundException {
UUID uuid = customerPhoneUUID.get(phoneNumber); UUID uuid = customerPhoneUUID.get(phoneNumber);
customerUseCase.deleteCustomer(uuid); customerUseCase.remove(uuid);
} }
@Then("the customer {string} is removed from the system") @Then("the customer {string} is removed from the system")
@@ -155,37 +132,34 @@ public class CustomerSteps {
} }
@When("I add {int} loyalty points to customer {string}") @When("I add {int} loyalty points to customer {string}")
public void iAddLoyaltyPointsToCustomer(int loyaltyPointToAdd, String phoneNumber) throws CustomerNotFoundException { public void iAddLoyaltyPointsToCustomer(int points, String phoneNumber) throws CustomerNotFoundException {
UUID uuid = customerPhoneUUID.get(phoneNumber); UUID uuid = customerPhoneUUID.get(phoneNumber);
customerUseCase.addLoyaltyPoints(uuid, loyaltyPointToAdd); customerUseCase.increasePoints(uuid, points);
} }
@Then("customer {string} now has {int} loyalty points") @Then("customer {string} now has {int} loyalty points")
public void customerNowHasLoyaltyPoints(String phoneNumber, int expectedLoyaltyPoints) { public void customerNowHasLoyaltyPoints(String phoneNumber, int expectedPoints) {
UUID uuid = customerPhoneUUID.get(phoneNumber); UUID uuid = customerPhoneUUID.get(phoneNumber);
Customer customer = customerRepository.findById(uuid).orElseThrow(); Customer customer = customerRepository.findById(uuid).orElseThrow();
assertEquals(expectedLoyaltyPoints, customer.getLoyaltyPoints()); assertEquals(expectedPoints, customer.getLoyaltyPoints());
} }
@When("I deduct {int} loyalty points from customer {string} for a purchase") @When("I deduct {int} loyalty points from customer {string} for a purchase")
public void iDeductLoyaltyPointsFromCustomerForAPurchase(int pointsToRemove, String phoneNumber) throws CustomerNotFoundException, IllegalCustomerPointException { public void iDeductLoyaltyPointsFromCustomerForAPurchase(int points, String phoneNumber)
throws CustomerNotFoundException, IllegalCustomerPointException {
UUID uuid = customerPhoneUUID.get(phoneNumber); UUID uuid = customerPhoneUUID.get(phoneNumber);
customerUseCase.subtractLoyaltyPoints(uuid, pointsToRemove); customerUseCase.decreasePoints(uuid, points);
} }
@When("I try to create a new customer with the following information:") @When("I try to create a new customer with the following information:")
public void iTryToCreateANewCustomerWithTheFollowingInformation(DataTable ddataTable) { public void iTryToCreateANewCustomerWithTheFollowingInformation(DataTable dataTable) {
List<Map<String, String>> rows = ddataTable.asMaps(String.class, String.class); Map<String, String> customerInfo = dataTable.asMaps(String.class, String.class).getFirst();
Map<String, String> customerInfo = rows.getFirst();
CustomerInfo newCustomer = new CustomerInfo( CustomerInfo newCustomer = new CustomerInfo(
customerInfo.get("prenom"), customerInfo.get("prenom"),
customerInfo.get("nom"), customerInfo.get("nom"),
customerInfo.get("numeroTelephone") customerInfo.get("numeroTelephone")
); );
notValidCustomerException = assertThrows(NotValidCustomerException.class, () -> customerUseCase.create(newCustomer));
notValidCustomerException = assertThrows(NotValidCustomerException.class, () -> customerUseCase.registerCustomer(newCustomer));
} }
@Then("the creation fails") @Then("the creation fails")
@@ -193,21 +167,20 @@ public class CustomerSteps {
assertNotNull(notValidCustomerException); assertNotNull(notValidCustomerException);
} }
@And("I receive an error for validation customer message containing {string}") @And("I receive an error for validation customer message containing {string}")
public void iReceiveAnErrorMessageContaining(String errorMessage) { public void iReceiveAnErrorMessageContaining(String errorMessage) {
assertEquals(errorMessage, notValidCustomerException.getMessage()); assertEquals(errorMessage, notValidCustomerException.getMessage());
} }
@And("the system still has {int} customers") @And("the system still has {int} customers")
public void theSystemStillHasCustomers(int expectedNumberOfUser) { public void theSystemStillHasCustomers(int expectedCount) {
assertEquals(expectedNumberOfUser, customerRepository.findAll().size()); assertEquals(expectedCount, customerRepository.findAll().size());
} }
@When("I try to deduct {int} loyalty points from customer {string} for a purchase") @When("I try to deduct {int} loyalty points from customer {string} for a purchase")
public void iTryToDeductLoyaltyPointsFromCustomerForAPurchase(int points, String phoneNumber) { public void iTryToDeductLoyaltyPointsFromCustomerForAPurchase(int points, String phoneNumber) {
UUID uuid = customerPhoneUUID.get(phoneNumber); UUID uuid = customerPhoneUUID.get(phoneNumber);
illegalCustomerPointException = assertThrows(IllegalCustomerPointException.class, () -> customerUseCase.subtractLoyaltyPoints(uuid, points)); illegalCustomerPointException = assertThrows(IllegalCustomerPointException.class, () -> customerUseCase.decreasePoints(uuid, points));
} }
@Then("the deduction fails") @Then("the deduction fails")

View File

@@ -45,33 +45,33 @@ public class OrderSteps {
private OrderInfo currentOrderInfo; private OrderInfo currentOrderInfo;
private UUID lastOrderId; private UUID lastOrderId;
@Given("Le systeme contient les livres suivants :") @Given("The system contains the following books:")
public void leSystemeContientLesLivresSuivants(DataTable dataTable) { public void theSystemContainsTheFollowingBooks(DataTable dataTable) {
bookRepository.deleteAll(); bookRepository.deleteAll();
List<Map<String, String>> livres = dataTable.asMaps(String.class, String.class); List<Map<String, String>> books = dataTable.asMaps(String.class, String.class);
for (Map<String, String> livre : livres) { for (Map<String, String> book : books) {
BookInfo info = new BookInfo( BookInfo info = new BookInfo(
livre.get("isbn"), book.get("isbn"),
livre.get("titre"), book.get("title"),
livre.get("auteur"), book.get("author"),
livre.get("editeur"), book.get("publisher"),
LocalDate.parse(livre.get("datePublication")), LocalDate.parse(book.get("publicationDate")),
Double.parseDouble(livre.get("prix")), Double.parseDouble(book.get("price")),
Integer.parseInt(livre.get("stockInitial")), Integer.parseInt(book.get("initialStock")),
Arrays.stream(livre.get("categories").replaceAll("[\\[\\]]", "").split(",")) Arrays.stream(book.get("categories").replaceAll("[\\[\\]]", "").split(","))
.map(String::trim) .map(String::trim)
.map(Category::valueOf) .map(Category::valueOf)
.collect(Collectors.toList()), .collect(Collectors.toList()),
livre.get("description"), book.get("description"),
livre.get("langue") book.get("language")
); );
bookUseCase.registerBook(info); bookUseCase.registerBook(info);
} }
assertEquals(livres.size(), bookRepository.findAll().size()); assertEquals(books.size(), bookRepository.findAll().size());
} }
@And("Le systeme contient les utilisateur suivants:") @And("The system contains the following users:")
public void leSystemeContientLesUtilisateurSuivants(DataTable dataTable) { public void theSystemContainsTheFollowingUsers(DataTable dataTable) {
customerRepository.deleteAll(); customerRepository.deleteAll();
List<Map<String, String>> customers = dataTable.asMaps(String.class, String.class); List<Map<String, String>> customers = dataTable.asMaps(String.class, String.class);
for (Map<String, String> customer : customers) { for (Map<String, String> customer : customers) {
@@ -88,8 +88,8 @@ public class OrderSteps {
assertEquals(customers.size(), customerRepository.findAll().size()); assertEquals(customers.size(), customerRepository.findAll().size());
} }
@When("Je crée une nouvelle commande avec les informations suivantes :") @When("I create a new order with the following information:")
public void jeCreeUneNouvelleCommandeAvecLesInformationsSuivantes(DataTable dataTable) { public void iCreateANewOrderWithTheFollowingInformation(DataTable dataTable) {
try { try {
Map<String, String> orderData = dataTable.asMaps().getFirst(); Map<String, String> orderData = dataTable.asMaps().getFirst();
String customerId = orderData.get("customerId"); String customerId = orderData.get("customerId");
@@ -115,11 +115,11 @@ public class OrderSteps {
} }
} }
@And("La commande contient les livres suivants :") @And("The order contains the following books:")
public void laCommandeContientLesLivresSuivants(DataTable dataTable) { public void theOrderContainsTheFollowingBooks(DataTable dataTable) {
try { try {
if (currentOrderInfo == null) { if (currentOrderInfo == null) {
// Si currentOrderInfo est nul, on ne fait rien (le client n'existe pas) // If currentOrderInfo is null, do nothing (customer does not exist)
return; return;
} }
List<OrderLineDTO> lines = new ArrayList<>(); List<OrderLineDTO> lines = new ArrayList<>();
@@ -135,17 +135,17 @@ public class OrderSteps {
} }
} }
@And("L'adresse de livraison est :") @And("The shipping address is:")
public void lAdresseDeLivraisonEst(DataTable dataTable) { public void theShippingAddressIs(DataTable dataTable) {
try { try {
Map<String, String> addressData = dataTable.asMaps().getFirst(); Map<String, String> addressData = dataTable.asMaps().getFirst();
// Vérifier si l'adresse est vide // Check if the address is empty
boolean isAddressEmpty = addressData.values().stream() boolean isAddressEmpty = addressData.values().stream()
.allMatch(value -> value == null || value.trim().isEmpty()); .allMatch(value -> value == null || value.trim().isEmpty());
if (isAddressEmpty) { if (isAddressEmpty) {
throw new WrongAddressException("L'adresse de livraison est vide"); throw new WrongAddressException("The shipping address is empty");
} }
AddressDTO shippingAddress = AddressDTO.builder() AddressDTO shippingAddress = AddressDTO.builder()
@@ -163,52 +163,52 @@ public class OrderSteps {
} }
} }
@Then("Une nouvelle commande est créée") @Then("A new order is created")
public void uneNouvelleCommandeEstCreee() { public void aNewOrderIsCreated() {
try { try {
if (currentOrderInfo == null) { if (currentOrderInfo == null) {
throw new IllegalStateException("L'objet currentOrderInfo est null. Vérifiez les étapes précédentes."); throw new IllegalStateException("The currentOrderInfo object is null. Check previous steps.");
} }
// Vérifier que l'adresse est valide // Check that the address is valid
AddressDTO address = currentOrderInfo.getAddress(); AddressDTO address = currentOrderInfo.getAddress();
if (address == null || address.getStreet() == null || address.getStreet().trim().isEmpty() if (address == null || address.getStreet() == null || address.getStreet().trim().isEmpty()
|| address.getCity() == null || address.getCity().trim().isEmpty() || address.getCity() == null || address.getCity().trim().isEmpty()
|| address.getPostalCode() == null || address.getPostalCode().trim().isEmpty() || address.getPostalCode() == null || address.getPostalCode().trim().isEmpty()
|| address.getCountry() == null || address.getCountry().trim().isEmpty()) { || address.getCountry() == null || address.getCountry().trim().isEmpty()) {
throw new WrongAddressException("L'adresse de livraison est manquante ou incomplète"); throw new WrongAddressException("The shipping address is missing or incomplete");
} }
// Création de la commande // Create the order
lastOrderId = orderUseCase.createOrder(currentOrderInfo); lastOrderId = orderUseCase.createOrder(currentOrderInfo);
lastException = null; lastException = null;
// Vérification que la commande a bien été créée // Check that the order was created
OrderDTO createdOrder = orderUseCase.findOrderById(String.valueOf(lastOrderId)); OrderDTO createdOrder = orderUseCase.findOrderById(String.valueOf(lastOrderId));
assertNotNull(createdOrder, "La commande doit exister après sa création"); assertNotNull(createdOrder, "The order must exist after creation");
// Vérification des données de la commande // Check order data
assertEquals(UUID.fromString(currentOrderInfo.getCustomerId()), createdOrder.getCustomerId(), "L'ID client doit correspondre"); assertEquals(UUID.fromString(currentOrderInfo.getCustomerId()), createdOrder.getCustomerId(), "Customer ID must match");
assertEquals(currentOrderInfo.getPaymentMethod(), createdOrder.getPaymentMethod(), "La méthode de paiement doit correspondre"); assertEquals(currentOrderInfo.getPaymentMethod(), createdOrder.getPaymentMethod(), "Payment method must match");
assertNotNull(createdOrder.getShippingAddress(), "L'adresse de livraison ne doit pas être nulle"); assertNotNull(createdOrder.getShippingAddress(), "Shipping address must not be null");
assertFalse(createdOrder.getOrderLines().isEmpty(), "La commande doit contenir au moins une ligne"); assertFalse(createdOrder.getOrderLines().isEmpty(), "Order must contain at least one line");
} catch (Exception e) { } catch (Exception e) {
lastException = e; lastException = e;
lastOrderId = null; lastOrderId = null;
} }
assertNull(lastException, "Aucune exception ne doit être levée lors de la création de la commande"); assertNull(lastException, "No exception should be thrown when creating the order");
assertNotNull(lastOrderId, "L'ID de la commande ne doit pas être null"); assertNotNull(lastOrderId, "Order ID must not be null");
} }
@Then("Le prix total est {double}") @Then("The total price is {double}")
public void lePrixTotalEst(double expectedTotal) { public void theTotalPriceIs(double expectedTotal) {
assertNotNull(lastOrderId, "L'ID de la commande ne doit pas être null"); assertNotNull(lastOrderId, "Order ID must not be null");
OrderDTO order = orderUseCase.findOrderById(String.valueOf(lastOrderId)); OrderDTO order = orderUseCase.findOrderById(String.valueOf(lastOrderId));
assertEquals(expectedTotal, order.getTotalPrice(), 0.01); assertEquals(expectedTotal, order.getTotalPrice(), 0.01);
} }
@Then("La création de la commande échoue") @Then("Order creation fails")
public void laCreationDeLaCommandeEchoue() { public void orderCreationFails() {
// Si lastException est déjà défini, on ne fait rien de plus // If lastException is already set, do nothing
if (lastException != null) { if (lastException != null) {
return; return;
} }
@@ -218,84 +218,84 @@ public class OrderSteps {
throw new CustomerNotFoundException(null); throw new CustomerNotFoundException(null);
} }
// Vérifier que l'adresse est valide // Check that the address is valid
AddressDTO address = currentOrderInfo.getAddress(); AddressDTO address = currentOrderInfo.getAddress();
if (address == null || address.getStreet() == null || address.getStreet().trim().isEmpty() if (address == null || address.getStreet() == null || address.getStreet().trim().isEmpty()
|| address.getCity() == null || address.getCity().trim().isEmpty() || address.getCity() == null || address.getCity().trim().isEmpty()
|| address.getPostalCode() == null || address.getPostalCode().trim().isEmpty() || address.getPostalCode() == null || address.getPostalCode().trim().isEmpty()
|| address.getCountry() == null || address.getCountry().trim().isEmpty()) { || address.getCountry() == null || address.getCountry().trim().isEmpty()) {
throw new WrongAddressException("L'adresse de livraison est manquante ou incomplète"); throw new WrongAddressException("The shipping address is missing or incomplete");
} }
lastOrderId = orderUseCase.createOrder(currentOrderInfo); lastOrderId = orderUseCase.createOrder(currentOrderInfo);
fail("La création de la commande aurait dû échouer"); fail("Order creation should have failed");
} catch (Exception e) { } catch (Exception e) {
lastException = e; lastException = e;
lastOrderId = null; lastOrderId = null;
} }
assertNotNull(lastException, "Une exception aurait dû être levée"); assertNotNull(lastException, "An exception should have been thrown");
} }
@And("Le client {string} a {int} points de fidélité") @And("Customer {string} has {int} loyalty points")
public void leClientAPointsDeFidelite(String clientId, int points) { public void customerHasLoyaltyPoints(String clientId, int points) {
Customer customer = customerRepository.findById(UUID.fromString(clientId)).orElseThrow(); Customer customer = customerRepository.findById(UUID.fromString(clientId)).orElseThrow();
assertEquals(points, customer.getLoyaltyPoints()); assertEquals(points, customer.getLoyaltyPoints());
} }
@And("Je reçois une erreur indiquant que l'adresse de livraison est manquante") @And("I receive an error indicating that the shipping address is missing")
public void jeRecoisUneErreurIndiquantQueLAdresseDeLivraisonEstManquante() { public void iReceiveAnErrorIndicatingThatTheShippingAddressIsMissing() {
assertNotNull(lastException); assertNotNull(lastException);
assertInstanceOf(WrongAddressException.class, lastException); assertInstanceOf(WrongAddressException.class, lastException);
} }
@And("Je reçois une erreur indiquant que le client n'a pas été trouvé") @And("I receive an error indicating that the customer was not found")
public void jeRecoisUneErreurIndiquantQueLeClientNaPasEteTrouve() { public void iReceiveAnErrorIndicatingThatTheCustomerWasNotFound() {
assertInstanceOf(CustomerNotFoundException.class, lastException); assertInstanceOf(CustomerNotFoundException.class, lastException);
} }
@And("Je reçois une erreur indiquant que les points de fidélité sont insuffisants") @And("I receive an error indicating that loyalty points are insufficient")
public void jeRecoisUneErreurIndiquantQueLesPointsDeFideliteSontInsuffisants() { public void iReceiveAnErrorIndicatingThatLoyaltyPointsAreInsufficient() {
assertNotNull(lastException); assertNotNull(lastException);
assertInstanceOf(IllegalOrderPointException.class, lastException); assertInstanceOf(IllegalOrderPointException.class, lastException);
} }
@And("Je reçois une erreur indiquant que le stock de livres est insuffisant") @And("I receive an error indicating that book stock is insufficient")
public void jeRecoisUneErreurIndiquantQueLeStockDeLivresEstInsuffisant() { public void iReceiveAnErrorIndicatingThatBookStockIsInsufficient() {
assertNotNull(lastException); assertNotNull(lastException);
assertInstanceOf(OrderQuantityException.class, lastException); assertInstanceOf(OrderQuantityException.class, lastException);
} }
@And("Je reçois une erreur indiquant que le mode de paiement est invalide") @And("I receive an error indicating that the payment method is invalid")
public void jeRecoisUneErreurIndiquantQueLeModeDePaiementEstInvalide() { public void iReceiveAnErrorIndicatingThatThePaymentMethodIsInvalid() {
assertNotNull(lastException); assertNotNull(lastException);
assertInstanceOf(InvalidPaymentMethodException.class, lastException); assertInstanceOf(InvalidPaymentMethodException.class, lastException);
} }
@And("Je reçois une erreur indiquant que le livre n'a pas été trouvé") @And("I receive an error indicating that the book was not found")
public void jeRecoisUneErreurIndiquantQueLeLivreNAPasEteTrouve() { public void iReceiveAnErrorIndicatingThatTheBookWasNotFound() {
assertNotNull(lastException); assertNotNull(lastException);
assertInstanceOf(BookNotFoundException.class, lastException); assertInstanceOf(BookNotFoundException.class, lastException);
} }
@And("La commande ne contient aucun livre") @And("The order contains no books")
public void laCommandeNeContientAucunLivre() { public void theOrderContainsNoBooks() {
currentOrderInfo.setOrderLines(new ArrayList<>()); currentOrderInfo.setOrderLines(new ArrayList<>());
} }
@And("Je reçois une erreur indiquant que la commande doit contenir au moins un livre") @And("I receive an error indicating that the order must contain at least one book")
public void jeRecoisUneErreurIndiquantQueLaCommandeDoitContenirAuMoinsUnLivre() { public void iReceiveAnErrorIndicatingThatTheOrderMustContainAtLeastOneBook() {
assertNotNull(lastException); assertNotNull(lastException);
assertInstanceOf(OrderQuantityException.class, lastException); assertInstanceOf(OrderQuantityException.class, lastException);
} }
@And("Je reçois une erreur indiquant que la quantité de livres doit être positive") @And("I receive an error indicating that the quantity of books must be positive")
public void jeRecoisUneErreurIndiquantQueLaQuantiteDeLivresDoitEtrePositive() { public void iReceiveAnErrorIndicatingThatTheQuantityOfBooksMustBePositive() {
assertNotNull(lastException); assertNotNull(lastException);
assertInstanceOf(OrderQuantityException.class, lastException); assertInstanceOf(OrderQuantityException.class, lastException);
} }
@Given("Il existe une commande avec l'ID {string} pour le client {string}") @Given("There is an order with ID {string} for customer {string}")
public void ilExisteUneCommandeAvecLIDPourLeClient(String orderId, String clientId) { public void thereIsAnOrderWithIDForCustomer(String orderId, String clientId) {
Order order = Order.builder() Order order = Order.builder()
.id(UUID.fromString(orderId)) .id(UUID.fromString(orderId))
.customerId(UUID.fromString(clientId)) .customerId(UUID.fromString(clientId))
@@ -307,8 +307,8 @@ public class OrderSteps {
orderRepository.save(order); orderRepository.save(order);
} }
@When("Je récupère la commande par ID {string}") @When("I retrieve the order by ID {string}")
public void jeRecupereLaCommandeParID(String orderId) { public void iRetrieveTheOrderByID(String orderId) {
try { try {
UUID uuid; UUID uuid;
try { try {
@@ -326,14 +326,14 @@ public class OrderSteps {
} }
} }
@Then("Je reçois une commande") @Then("I receive an order")
public void jeRecoisUneCommande() { public void iReceiveAnOrder() {
assertNull(lastException, "Aucune exception ne doit être levée"); assertNull(lastException, "No exception should be thrown");
assertTrue(lastOrderDTO.isPresent(), "La commande doit être présente"); assertTrue(lastOrderDTO.isPresent(), "The order should be present");
} }
@When("Je demande toutes les commandes pour le client {string}") @When("I request all orders for customer {string}")
public void jeDemandeToutesLesCommandesPourLeClient(String clientId) { public void iRequestAllOrdersForCustomer(String clientId) {
try { try {
lastOrderList = orderUseCase.findOrdersByCustomerId(clientId); lastOrderList = orderUseCase.findOrdersByCustomerId(clientId);
lastException = null; lastException = null;
@@ -343,22 +343,20 @@ public class OrderSteps {
} }
} }
@Then("La récupération échoue") @Then("Retrieval fails")
public void laRecuperationEchoue() { public void retrievalFails() {
assertNotNull(lastException, "Une exception doit être levée"); assertNotNull(lastException, "An exception should be thrown");
} }
@Then("I receive a list of orders")
@Then("Je reçois une liste de commandes") public void iReceiveAListOfOrders() {
public void jeRecoisUneListeDeCommandes() { assertNull(lastException, "No exception should be thrown");
assertNull(lastException, "Aucune exception ne doit être levée"); assertNotNull(lastOrderList, "The list of orders must not be null");
assertNotNull(lastOrderList, "La liste des commandes ne doit pas être nulle");
} }
@And("Je reçois une erreur indiquant que la commande n'a pas été trouvée") @And("I receive an error indicating that the order was not found")
public void jeRecoisUneErreurIndiquantQueLaCommandeNAPasEteTrouvee() { public void iReceiveAnErrorIndicatingThatTheOrderWasNotFound() {
assertNotNull(lastException); assertNotNull(lastException);
assertInstanceOf(OrderNotFoundException.class, lastException); assertInstanceOf(OrderNotFoundException.class, lastException);
} }
} }