forked from pierront/mylibrary-template
🐛 Modified some tests literaly 4 miinutes before the ENd
This commit is contained in:
2
.idea/misc.xml
generated
2
.idea/misc.xml
generated
@@ -8,5 +8,5 @@
|
||||
</list>
|
||||
</option>
|
||||
</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>
|
@@ -27,6 +27,11 @@ public final class BookValidator {
|
||||
checkTitle(info);
|
||||
checkAuthor(info);
|
||||
checkStock(info);
|
||||
checkPublisher(info);
|
||||
checkPublicationDate(info);
|
||||
checkCategories(info);
|
||||
checkDescription(info);
|
||||
checkLanguage(info);
|
||||
}
|
||||
|
||||
private static void checkIsbn(BookInfo info) throws NotValidBookException {
|
||||
@@ -52,7 +57,7 @@ public final class BookValidator {
|
||||
}
|
||||
|
||||
private static void checkPrice(BookInfo info) throws NotValidBookException {
|
||||
if (info.price() < 0) {
|
||||
if (info.price() <= 0) {
|
||||
throw new NotValidBookException(ERROR_NEGATIVE_PRICE);
|
||||
}
|
||||
}
|
||||
@@ -62,4 +67,35 @@ public final class BookValidator {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -20,27 +20,35 @@ public final class CustomerRepository {
|
||||
}
|
||||
|
||||
public Customer save(Customer newCustomer) {
|
||||
Optional<Customer> optionalCustomerWithSameId = this.findById(newCustomer.getId());
|
||||
optionalCustomerWithSameId.ifPresentOrElse(customers::remove, newCustomer::setRandomUUID);
|
||||
if (newCustomer.getId() == null) {
|
||||
newCustomer.setRandomUUID();
|
||||
}
|
||||
|
||||
this.findById(newCustomer.getId()).ifPresent(customers::remove);
|
||||
|
||||
this.customers.add(newCustomer);
|
||||
return newCustomer;
|
||||
}
|
||||
|
||||
public Optional<Customer> findById(UUID uuid) {
|
||||
if (uuid == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return this.customers.stream()
|
||||
.filter(customer -> customer.getId().equals(uuid))
|
||||
.findFirst();
|
||||
.filter(customer -> uuid.equals(customer.getId()))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public boolean existsById(UUID uuid) {
|
||||
return this.customers.stream()
|
||||
.anyMatch(customer -> customer.getId().equals(uuid));
|
||||
.anyMatch(customer -> customer.getId().equals(uuid));
|
||||
}
|
||||
|
||||
public Optional<Customer> findByPhoneNumber(String phoneNumber) {
|
||||
return this.customers.stream()
|
||||
.filter(customer -> customer.getPhoneNumber().equals(phoneNumber))
|
||||
.findFirst();
|
||||
.filter(customer -> customer.getPhoneNumber().equals(phoneNumber))
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
public void delete(Customer customer) {
|
||||
|
@@ -25,7 +25,7 @@ public final class CustomerUseCase {
|
||||
}
|
||||
|
||||
public UUID create(CustomerInfo input) throws NotValidCustomerException {
|
||||
CustomerValidator.validate(input);
|
||||
CustomerValidator.check(input);
|
||||
Customer newCustomer = CustomerConverter.toDomain(input);
|
||||
Customer saved = repo.save(newCustomer);
|
||||
return saved.getId();
|
||||
@@ -53,7 +53,7 @@ public final class CustomerUseCase {
|
||||
|
||||
public CustomerDTO modify(UUID id, CustomerInfo input)
|
||||
throws CustomerNotFoundException, NotValidCustomerException {
|
||||
CustomerValidator.validate(input);
|
||||
CustomerValidator.check(input);
|
||||
Customer existing = resolveOrFail(id);
|
||||
Customer updated = Customer.builder()
|
||||
.id(id)
|
||||
|
@@ -21,7 +21,7 @@ class BookTest {
|
||||
LocalDate publicationDate = LocalDate.of(2012, 6, 20);
|
||||
double price = 39.95;
|
||||
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 language = "English";
|
||||
|
||||
|
@@ -13,9 +13,9 @@ class BookNotFoundExceptionTest {
|
||||
String isbn = "9780001112223";
|
||||
|
||||
try {
|
||||
throw new BookNotFoundException(isbn);
|
||||
throw BookNotFoundException.forIsbn(isbn);
|
||||
} 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());
|
||||
}
|
||||
}
|
||||
@@ -25,10 +25,10 @@ class BookNotFoundExceptionTest {
|
||||
void shouldIncludeIsbnInMessage() {
|
||||
String isbn = "9780001112223";
|
||||
|
||||
BookNotFoundException exception = new BookNotFoundException(isbn);
|
||||
BookNotFoundException exception = BookNotFoundException.forIsbn(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
|
||||
@@ -36,9 +36,9 @@ class BookNotFoundExceptionTest {
|
||||
void shouldUseCorrectConstantMessageFormat() {
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
@@ -39,8 +39,8 @@ class BookValidatorTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("Should fail if ISBN is null")
|
||||
void shouldFailOnNullIsbn() {
|
||||
BookInfo book = new BookInfo(
|
||||
void shouldFailOnNullIsbn() throws NotValidBookException {
|
||||
BookInfo book = new BookInfo (
|
||||
null, "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2,
|
||||
List.of(Category.SCIENCE), "Details", "English"
|
||||
);
|
||||
@@ -124,7 +124,7 @@ class BookValidatorTest {
|
||||
class PublicationDateTests {
|
||||
@Test
|
||||
@DisplayName("Should fail if publication date is null")
|
||||
void shouldFailOnNullPublicationDate() {
|
||||
void shouldFailOnNullPublicationDate() throws NotValidBookException {
|
||||
BookInfo book = new BookInfo(
|
||||
"9780001234567", "Title", "Author", "Publisher", null, 10.0, 2,
|
||||
List.of(Category.SCIENCE), "Details", "English"
|
||||
@@ -140,7 +140,7 @@ class BookValidatorTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(doubles = {0.0, -5.5, -100.0})
|
||||
@DisplayName("Should fail if price is zero or negative")
|
||||
void shouldFailOnInvalidPrice(double price) {
|
||||
void shouldFailOnInvalidPrice(double price) throws NotValidBookException {
|
||||
BookInfo book = new BookInfo(
|
||||
"9780001234567", "Title", "Author", "Publisher", LocalDate.now(), price, 2,
|
||||
List.of(Category.SCIENCE), "Details", "English"
|
||||
@@ -156,7 +156,7 @@ class BookValidatorTest {
|
||||
@ParameterizedTest
|
||||
@ValueSource(ints = {-1, -50})
|
||||
@DisplayName("Should fail if stock is negative")
|
||||
void shouldFailOnNegativeStock(int stock) {
|
||||
void shouldFailOnNegativeStock(int stock) throws NotValidBookException {
|
||||
BookInfo book = new BookInfo(
|
||||
"9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, stock,
|
||||
List.of(Category.SCIENCE), "Details", "English"
|
||||
@@ -171,7 +171,7 @@ class BookValidatorTest {
|
||||
class CategoryTests {
|
||||
@Test
|
||||
@DisplayName("Should fail if category list is empty")
|
||||
void shouldFailOnEmptyCategoryList() {
|
||||
void shouldFailOnEmptyCategoryList() throws NotValidBookException {
|
||||
BookInfo book = new BookInfo(
|
||||
"9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2,
|
||||
Collections.emptyList(), "Details", "English"
|
||||
@@ -186,7 +186,7 @@ class BookValidatorTest {
|
||||
class DescriptionTests {
|
||||
@Test
|
||||
@DisplayName("Should fail if description is blank")
|
||||
void shouldFailOnBlankDescription() {
|
||||
void shouldFailOnBlankDescription() throws NotValidBookException {
|
||||
BookInfo book = new BookInfo(
|
||||
"9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2,
|
||||
List.of(Category.SCIENCE), "", "English"
|
||||
@@ -201,7 +201,7 @@ class BookValidatorTest {
|
||||
class LanguageTests {
|
||||
@Test
|
||||
@DisplayName("Should fail if language is blank")
|
||||
void shouldFailOnBlankLanguage() {
|
||||
void shouldFailOnBlankLanguage() throws NotValidBookException {
|
||||
BookInfo book = new BookInfo(
|
||||
"9780001234567", "Title", "Author", "Publisher", LocalDate.now(), 10.0, 2,
|
||||
List.of(Category.SCIENCE), "Details", ""
|
||||
|
@@ -1,26 +1,26 @@
|
||||
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.java.en.And;
|
||||
import io.cucumber.java.en.Given;
|
||||
import io.cucumber.java.en.Then;
|
||||
import io.cucumber.java.en.When;
|
||||
|
||||
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 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 {
|
||||
|
||||
private final BookRepository bookRepository = new BookRepository();
|
||||
@@ -31,290 +31,153 @@ public class BookSteps {
|
||||
private BookDTO updatedBook;
|
||||
private String deletedBookIsbn;
|
||||
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 :")
|
||||
public void leSystemePossedeLesLivresSuivants(DataTable dataTable) {
|
||||
@Given("the system contains the following books:")
|
||||
public void theSystemContainsTheFollowingBooks(DataTable table) {
|
||||
bookRepository.deleteAll();
|
||||
List<Map<String, String>> livres = dataTable.asMaps(String.class, String.class);
|
||||
|
||||
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")
|
||||
);
|
||||
for (Map<String, String> row : table.asMaps()) {
|
||||
BookInfo info = toBookInfo(row);
|
||||
bookUseCase.registerBook(info);
|
||||
}
|
||||
assertEquals(livres.size(), bookRepository.findAll().size());
|
||||
}
|
||||
|
||||
@When("Je cree un nouveau livre avec les informations suivantes :")
|
||||
public void jeCreeUnNouveauLivreAvecLesInformationsSuivantes(DataTable dataTable) {
|
||||
Map<String, String> data = dataTable.asMaps(String.class, String.class).getFirst();
|
||||
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")
|
||||
);
|
||||
@When("I create a new book with the following data:")
|
||||
public void iCreateANewBookWithTheFollowingData(DataTable table) {
|
||||
BookInfo info = toBookInfo(table.asMaps().get(0));
|
||||
try {
|
||||
bookRegistration = bookUseCase.registerBook(info);
|
||||
storedException = null;
|
||||
} catch (Exception e) {
|
||||
storedException = e;
|
||||
bookRegistration = null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Then("La creation echoue")
|
||||
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");
|
||||
@Then("a new book is created")
|
||||
public void aNewBookIsCreated() {
|
||||
assertNotNull(bookRegistration);
|
||||
}
|
||||
|
||||
@When("Je modifie le livre avec l'ISBN {string} avec les informations suivantes:")
|
||||
public void jeModifieLeLivreAvecLesInformationsSuivantes(String isbnStr, DataTable dataTable) {
|
||||
Map<String, String> data = dataTable.asMaps(String.class, String.class).getFirst();
|
||||
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")
|
||||
);
|
||||
@Then("the creation fails")
|
||||
public void theCreationFails() {
|
||||
assertNotNull(storedException);
|
||||
assertTrue(storedException instanceof NotValidBookException);
|
||||
}
|
||||
|
||||
@Given("a book exists with ISBN {string}")
|
||||
public void aBookExistsWithISBN(String isbn) {
|
||||
bookRepository.findByIsbn(isbn).or(() -> {
|
||||
BookInfo info = new BookInfo(isbn, "Titre par défaut", "Auteur", "Éditeur", LocalDate.now(), 10.0, 5,
|
||||
List.of(Category.SCIENCE), "Description", "Français");
|
||||
bookUseCase.registerBook(info);
|
||||
return Optional.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@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 {
|
||||
updatedBook = bookUseCase.updateBook(isbnStr, info);
|
||||
storedException = null;
|
||||
updatedBook = bookUseCase.updateBook(isbn, info);
|
||||
} catch (Exception e) {
|
||||
storedException = e;
|
||||
}
|
||||
}
|
||||
|
||||
@Then("Le livre {string} a les informations suivantes:")
|
||||
public void leLivreALesInformations(String isbnStr, DataTable dataTable) {
|
||||
BookDTO book = bookUseCase.findBookByIsbn(isbnStr);
|
||||
|
||||
Map<String, String> expected = dataTable.asMaps(String.class, String.class).getFirst();
|
||||
assertBookEquals(expected, book);
|
||||
@Then("the book {string} has the following data:")
|
||||
public void theBookHasTheFollowingData(String isbn, DataTable table) {
|
||||
BookDTO actual = bookUseCase.findBookByIsbn(isbn);
|
||||
assertBookEquals(table.asMaps().get(0), actual);
|
||||
}
|
||||
|
||||
@When("Je supprime le livre avec l'ISBN {string}")
|
||||
public void jeSupprimeLeLivre(String isbnStr) {
|
||||
deletedBookIsbn = isbnStr;
|
||||
@When("I delete the book with ISBN {string}")
|
||||
public void iDeleteTheBookWithISBN(String isbn) {
|
||||
deletedBookIsbn = isbn;
|
||||
try {
|
||||
bookUseCase.deleteBook(isbnStr);
|
||||
storedException = null;
|
||||
bookUseCase.deleteBook(isbn);
|
||||
} catch (Exception e) {
|
||||
storedException = e;
|
||||
}
|
||||
}
|
||||
|
||||
@Then("Le livre n'existe plus dans le systeme")
|
||||
public void leLivreNestPlusDansLeSysteme() {
|
||||
@Then("the book no longer exists in the system")
|
||||
public void theBookNoLongerExistsInTheSystem() {
|
||||
assertTrue(bookRepository.findByIsbn(deletedBookIsbn).isEmpty());
|
||||
}
|
||||
|
||||
@Then("La suppression échoue avec une erreur indiquant que le livre est introuvable")
|
||||
public void laSuppressionEchoueAvecErreurLivreIntrouvable() {
|
||||
assertNotNull(storedException, "Une exception devait être levée lors de la suppression");
|
||||
assertInstanceOf(BookNotFoundException.class, storedException, "L'exception levée doit être de type BookNotFoundException");
|
||||
@Given("no book exists with ISBN {string}")
|
||||
public void noBookExistsWithISBN(String isbn) {
|
||||
bookRepository.findByIsbn(isbn).ifPresent(bookRepository::delete);
|
||||
}
|
||||
|
||||
@When("Je demande les informations du livre avec l'ISBN {string}")
|
||||
public void jeDemandeLesInformationsDuLivreAvecISBN(String isbnStr) {
|
||||
@Then("the deletion fails with an error indicating the book was not found")
|
||||
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 {
|
||||
bookByIsbn = bookUseCase.findBookByIsbn(isbnStr);
|
||||
storedException = null;
|
||||
bookByIsbn = bookUseCase.findBookByIsbn(isbn);
|
||||
} catch (Exception e) {
|
||||
storedException = e;
|
||||
bookByIsbn = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Then("Je recupere les informations suivantes:")
|
||||
public void jeRecupereLesInfos(DataTable dataTable) {
|
||||
@Then("I receive the following data:")
|
||||
public void iReceiveTheFollowingData(DataTable table) {
|
||||
assertNotNull(bookByIsbn);
|
||||
Map<String, String> expected = dataTable.asMaps(String.class, String.class).getFirst();
|
||||
assertBookEquals(expected, bookByIsbn);
|
||||
assertBookEquals(table.asMaps().get(0), bookByIsbn);
|
||||
}
|
||||
|
||||
@Then("Je recois une erreur indiquant que le livre est introuvable")
|
||||
public void jeRecoisUneErreurIndiquantQueLeLivreEstIntrouvable() {
|
||||
assertNotNull(storedException, "Une exception devait être levée pour un livre introuvable");
|
||||
assertInstanceOf(BookNotFoundException.class, storedException, "L'exception levée doit être de type BookNotFoundException");
|
||||
@Then("I receive an error indicating the book was not found")
|
||||
public void iReceiveAnErrorIndicatingTheBookWasNotFound() {
|
||||
assertNotNull(storedException);
|
||||
assertTrue(storedException instanceof BookNotFoundException);
|
||||
}
|
||||
|
||||
@Given("Il existe un livre avec l'ISBN {string}")
|
||||
public void ilExisteUnLivreAvecISBN(String isbnStr) {
|
||||
Optional<Book> existingBook = bookRepository.findByIsbn(isbnStr);
|
||||
if (existingBook.isEmpty()) {
|
||||
BookInfo info = new BookInfo(
|
||||
isbnStr,
|
||||
"Titre par defaut",
|
||||
"Auteur inconnu",
|
||||
"Editeur inconnu",
|
||||
LocalDate.now(),
|
||||
0.0,
|
||||
1,
|
||||
Collections.singletonList(Category.FANTASY),
|
||||
"Description par defaut",
|
||||
"Francais"
|
||||
);
|
||||
bookUseCase.registerBook(info);
|
||||
}
|
||||
@When("I attempt to create a new book with the following data:")
|
||||
public void iAttemptToCreateANewBookWithTheFollowingData(DataTable table) {
|
||||
iCreateANewBookWithTheFollowingData(table);
|
||||
}
|
||||
|
||||
@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 qu’il 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 l’auteur {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 c’est 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 BookInfo toBookInfo(Map<String, String> data) {
|
||||
return new BookInfo(
|
||||
data.get("ISBN"),
|
||||
data.get("Title"),
|
||||
data.get("Author"),
|
||||
data.get("Publisher"),
|
||||
LocalDate.parse(data.get("Publication Date")),
|
||||
Double.parseDouble(data.get("Price")),
|
||||
Integer.parseInt(data.get("Initial Stock")),
|
||||
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")
|
||||
);
|
||||
}
|
||||
|
||||
private static void assertBookEquals(Map<String, String> expected, BookDTO actual) {
|
||||
assertEquals(expected.get("ISBN"), actual.getIsbn());
|
||||
assertEquals(expected.get("Titre"), actual.getTitle());
|
||||
assertEquals(expected.get("Auteur"), actual.getAuthor());
|
||||
assertEquals(expected.get("Editeur"), actual.getPublisher());
|
||||
assertEquals(LocalDate.parse(expected.get("Date de publication")), actual.getPublicationDate());
|
||||
assertEquals(Double.parseDouble(expected.get("Prix")), actual.getPrice(), 0.01);
|
||||
assertEquals(Integer.parseInt(expected.get("Stock initial")), actual.getStock());
|
||||
assertEquals(expected.get("Title"), actual.getTitle());
|
||||
assertEquals(expected.get("Author"), actual.getAuthor());
|
||||
assertEquals(expected.get("Publisher"), actual.getPublisher());
|
||||
assertEquals(LocalDate.parse(expected.get("Publication Date")), actual.getPublicationDate());
|
||||
assertEquals(Double.parseDouble(expected.get("Price")), actual.getPrice(), 0.01);
|
||||
assertEquals(Integer.parseInt(expected.get("Initial Stock")), actual.getStock());
|
||||
assertEquals(expected.get("Description"), actual.getDescription());
|
||||
assertEquals(expected.get("Langue"), actual.getLanguage());
|
||||
assertEquals(
|
||||
Arrays.stream(expected.get("Categories").replaceAll("[\\[\\]]", "").split(","))
|
||||
.map(String::trim)
|
||||
.map(Category::valueOf)
|
||||
.collect(Collectors.toList()),
|
||||
actual.getCategories()
|
||||
);
|
||||
assertEquals(expected.get("Language"), actual.getLanguage());
|
||||
List<Category> expectedCategories = Arrays.stream(expected.get("Categories").replaceAll("[\\[\\]]", "").split(","))
|
||||
.map(String::trim)
|
||||
.map(s -> Category.valueOf(s.toUpperCase().replace(' ', '_')))
|
||||
.collect(Collectors.toList());
|
||||
assertEquals(expectedCategories, actual.getCategories());
|
||||
}
|
||||
|
||||
@Then("Un nouveau livre est créé")
|
||||
public void unNouveauLivreEstCree() {
|
||||
assertNotNull(bookRegistration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,10 +1,6 @@
|
||||
package fr.iut_fbleau.but3.dev62.mylibrary.features.client;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
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 static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import fr.iut_fbleau.but3.dev62.mylibrary.customer.CustomerDTO;
|
||||
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.usecase.CustomerUseCase;
|
||||
import io.cucumber.datatable.DataTable;
|
||||
import io.cucumber.java.en.And;
|
||||
import io.cucumber.java.en.Given;
|
||||
import io.cucumber.java.en.Then;
|
||||
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;
|
||||
import io.cucumber.java.en.*;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
public class CustomerSteps {
|
||||
|
||||
@@ -39,22 +29,19 @@ public class CustomerSteps {
|
||||
|
||||
@Given("the system has the following customers:")
|
||||
public void theSystemHasTheFollowingCustomers(DataTable dataTable) {
|
||||
int size = customerRepository.findAll().size();
|
||||
|
||||
if (size > 0) {
|
||||
if (!customerRepository.findAll().isEmpty()) {
|
||||
customerRepository.deleteAll();
|
||||
}
|
||||
|
||||
List<Map<String, String>> customers = dataTable.asMaps(String.class, String.class);
|
||||
|
||||
for (Map<String, String> customer : customers) {
|
||||
String numeroTelephone = customer.get("numeroTelephone");
|
||||
Customer newCustomer = Customer.builder()
|
||||
.firstName(customer.get("prenom"))
|
||||
.lastName(customer.get("nom"))
|
||||
.phoneNumber(numeroTelephone)
|
||||
.loyaltyPoints(Integer.parseInt(customer.get("pointsFidelite")))
|
||||
.build();
|
||||
.firstName(customer.get("prenom"))
|
||||
.lastName(customer.get("nom"))
|
||||
.phoneNumber(numeroTelephone)
|
||||
.loyaltyPoints(Integer.parseInt(customer.get("pointsFidelite")))
|
||||
.build();
|
||||
Customer save = customerRepository.save(newCustomer);
|
||||
customerPhoneUUID.put(numeroTelephone, save.getId());
|
||||
}
|
||||
@@ -64,17 +51,13 @@ public class CustomerSteps {
|
||||
|
||||
@When("I create a new customer with the following information:")
|
||||
public void iCreateANewCustomerWithTheFollowingInformation(DataTable dataTable) throws NotValidCustomerException {
|
||||
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class);
|
||||
|
||||
Map<String, String> customerInfo = rows.getFirst();
|
||||
|
||||
Map<String, String> customerInfo = dataTable.asMaps(String.class, String.class).getFirst();
|
||||
CustomerInfo newCustomer = new CustomerInfo(
|
||||
customerInfo.get("prenom"),
|
||||
customerInfo.get("nom"),
|
||||
customerInfo.get("numeroTelephone")
|
||||
customerInfo.get("prenom"),
|
||||
customerInfo.get("nom"),
|
||||
customerInfo.get("numeroTelephone")
|
||||
);
|
||||
|
||||
customerRegistration = customerUseCase.registerCustomer(newCustomer);
|
||||
customerRegistration = customerUseCase.create(newCustomer);
|
||||
}
|
||||
|
||||
@And("the system now has {int} customers")
|
||||
@@ -95,46 +78,40 @@ public class CustomerSteps {
|
||||
|
||||
@When("I request the customer with phone number {string}")
|
||||
public void iRequestTheCustomerWithPhoneNumber(String phoneNumber) {
|
||||
customerByPhoneNumber = customerUseCase.findCustomerByPhoneNumber(phoneNumber);
|
||||
customerByPhoneNumber = customerUseCase.getByPhone(phoneNumber);
|
||||
}
|
||||
|
||||
@Then("I receive the following customer information:")
|
||||
public void iReceiveTheFollowingCustomerInformation(DataTable dataTable) {
|
||||
List<Map<String, String>> customers = dataTable.asMaps(String.class, String.class);
|
||||
Map<String, String> customerInfo = customers.getFirst();
|
||||
Map<String, String> customerInfo = dataTable.asMaps(String.class, String.class).getFirst();
|
||||
assertTrue(customerByPhoneNumber.isPresent());
|
||||
CustomerDTO customerDTO = customerByPhoneNumber.get();
|
||||
assertEquals(customerInfo.get("prenom"), customerDTO.getFirstName());
|
||||
assertEquals(customerInfo.get("nom"), customerDTO.getLastName());
|
||||
assertEquals(customerInfo.get("numeroTelephone"), customerDTO.getPhoneNumber());
|
||||
CustomerDTO dto = customerByPhoneNumber.get();
|
||||
assertEquals(customerInfo.get("prenom"), dto.getFirstName());
|
||||
assertEquals(customerInfo.get("nom"), dto.getLastName());
|
||||
assertEquals(customerInfo.get("numeroTelephone"), dto.getPhoneNumber());
|
||||
}
|
||||
|
||||
@When("I update customer {string} with the following information:")
|
||||
public void iUpdateCustomerWithTheFollowingInformation(String phoneNumber, DataTable dataTable)
|
||||
throws CustomerNotFoundException, NotValidCustomerException {
|
||||
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class);
|
||||
|
||||
Map<String, String> customerData = rows.getFirst();
|
||||
throws CustomerNotFoundException, NotValidCustomerException {
|
||||
Map<String, String> customerData = dataTable.asMaps(String.class, String.class).getFirst();
|
||||
CustomerInfo customerInfo = new CustomerInfo(
|
||||
customerData.get("prenom"),
|
||||
customerData.get("nom"),
|
||||
customerData.get("numeroTelephone")
|
||||
customerData.get("prenom"),
|
||||
customerData.get("nom"),
|
||||
customerData.get("numeroTelephone")
|
||||
);
|
||||
UUID uuid = customerPhoneUUID.get(phoneNumber);
|
||||
customerUseCase.updateCustomer(uuid, customerInfo);
|
||||
customerUseCase.modify(uuid, customerInfo);
|
||||
}
|
||||
|
||||
@Then("the customer {string} has the following updated information:")
|
||||
public void theCustomerHasTheFollowingUpdatedInformation(String phoneNumber, DataTable dataTable) {
|
||||
List<Map<String, String>> rows = dataTable.asMaps(String.class, String.class);
|
||||
|
||||
Map<String, String> updatedDate = rows.getFirst();
|
||||
|
||||
Map<String, String> updatedData = dataTable.asMaps(String.class, String.class).getFirst();
|
||||
UUID uuid = customerPhoneUUID.get(phoneNumber);
|
||||
updatedCustomer = customerRepository.findById(uuid).orElseThrow();
|
||||
assertEquals(updatedDate.get("numeroTelephone"), updatedCustomer.getPhoneNumber());
|
||||
assertEquals(updatedDate.get("prenom"), updatedCustomer.getFirstName());
|
||||
assertEquals(updatedDate.get("nom"), updatedCustomer.getLastName());
|
||||
assertEquals(updatedData.get("numeroTelephone"), updatedCustomer.getPhoneNumber());
|
||||
assertEquals(updatedData.get("prenom"), updatedCustomer.getFirstName());
|
||||
assertEquals(updatedData.get("nom"), updatedCustomer.getLastName());
|
||||
}
|
||||
|
||||
@And("the loyalty points remain unchanged at {int}")
|
||||
@@ -145,7 +122,7 @@ public class CustomerSteps {
|
||||
@When("I delete the customer with phone number {string}")
|
||||
public void iDeleteTheCustomerWithPhoneNumber(String phoneNumber) throws CustomerNotFoundException {
|
||||
UUID uuid = customerPhoneUUID.get(phoneNumber);
|
||||
customerUseCase.deleteCustomer(uuid);
|
||||
customerUseCase.remove(uuid);
|
||||
}
|
||||
|
||||
@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}")
|
||||
public void iAddLoyaltyPointsToCustomer(int loyaltyPointToAdd, String phoneNumber) throws CustomerNotFoundException {
|
||||
public void iAddLoyaltyPointsToCustomer(int points, String phoneNumber) throws CustomerNotFoundException {
|
||||
UUID uuid = customerPhoneUUID.get(phoneNumber);
|
||||
customerUseCase.addLoyaltyPoints(uuid, loyaltyPointToAdd);
|
||||
customerUseCase.increasePoints(uuid, 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);
|
||||
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")
|
||||
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);
|
||||
customerUseCase.subtractLoyaltyPoints(uuid, pointsToRemove);
|
||||
customerUseCase.decreasePoints(uuid, points);
|
||||
}
|
||||
|
||||
@When("I try to create a new customer with the following information:")
|
||||
public void iTryToCreateANewCustomerWithTheFollowingInformation(DataTable ddataTable) {
|
||||
List<Map<String, String>> rows = ddataTable.asMaps(String.class, String.class);
|
||||
|
||||
Map<String, String> customerInfo = rows.getFirst();
|
||||
|
||||
public void iTryToCreateANewCustomerWithTheFollowingInformation(DataTable dataTable) {
|
||||
Map<String, String> customerInfo = dataTable.asMaps(String.class, String.class).getFirst();
|
||||
CustomerInfo newCustomer = new CustomerInfo(
|
||||
customerInfo.get("prenom"),
|
||||
customerInfo.get("nom"),
|
||||
customerInfo.get("numeroTelephone")
|
||||
customerInfo.get("prenom"),
|
||||
customerInfo.get("nom"),
|
||||
customerInfo.get("numeroTelephone")
|
||||
);
|
||||
|
||||
notValidCustomerException = assertThrows(NotValidCustomerException.class, () -> customerUseCase.registerCustomer(newCustomer));
|
||||
notValidCustomerException = assertThrows(NotValidCustomerException.class, () -> customerUseCase.create(newCustomer));
|
||||
}
|
||||
|
||||
@Then("the creation fails")
|
||||
@@ -193,21 +167,20 @@ public class CustomerSteps {
|
||||
assertNotNull(notValidCustomerException);
|
||||
}
|
||||
|
||||
|
||||
@And("I receive an error for validation customer message containing {string}")
|
||||
public void iReceiveAnErrorMessageContaining(String errorMessage) {
|
||||
assertEquals(errorMessage, notValidCustomerException.getMessage());
|
||||
}
|
||||
|
||||
@And("the system still has {int} customers")
|
||||
public void theSystemStillHasCustomers(int expectedNumberOfUser) {
|
||||
assertEquals(expectedNumberOfUser, customerRepository.findAll().size());
|
||||
public void theSystemStillHasCustomers(int expectedCount) {
|
||||
assertEquals(expectedCount, customerRepository.findAll().size());
|
||||
}
|
||||
|
||||
@When("I try to deduct {int} loyalty points from customer {string} for a purchase")
|
||||
public void iTryToDeductLoyaltyPointsFromCustomerForAPurchase(int points, String 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")
|
||||
|
@@ -45,33 +45,33 @@ public class OrderSteps {
|
||||
private OrderInfo currentOrderInfo;
|
||||
private UUID lastOrderId;
|
||||
|
||||
@Given("Le systeme contient les livres suivants :")
|
||||
public void leSystemeContientLesLivresSuivants(DataTable dataTable) {
|
||||
@Given("The system contains the following books:")
|
||||
public void theSystemContainsTheFollowingBooks(DataTable dataTable) {
|
||||
bookRepository.deleteAll();
|
||||
List<Map<String, String>> livres = dataTable.asMaps(String.class, String.class);
|
||||
for (Map<String, String> livre : livres) {
|
||||
List<Map<String, String>> books = dataTable.asMaps(String.class, String.class);
|
||||
for (Map<String, String> book : books) {
|
||||
BookInfo info = new BookInfo(
|
||||
livre.get("isbn"),
|
||||
livre.get("titre"),
|
||||
livre.get("auteur"),
|
||||
livre.get("editeur"),
|
||||
LocalDate.parse(livre.get("datePublication")),
|
||||
Double.parseDouble(livre.get("prix")),
|
||||
Integer.parseInt(livre.get("stockInitial")),
|
||||
Arrays.stream(livre.get("categories").replaceAll("[\\[\\]]", "").split(","))
|
||||
book.get("isbn"),
|
||||
book.get("title"),
|
||||
book.get("author"),
|
||||
book.get("publisher"),
|
||||
LocalDate.parse(book.get("publicationDate")),
|
||||
Double.parseDouble(book.get("price")),
|
||||
Integer.parseInt(book.get("initialStock")),
|
||||
Arrays.stream(book.get("categories").replaceAll("[\\[\\]]", "").split(","))
|
||||
.map(String::trim)
|
||||
.map(Category::valueOf)
|
||||
.collect(Collectors.toList()),
|
||||
livre.get("description"),
|
||||
livre.get("langue")
|
||||
book.get("description"),
|
||||
book.get("language")
|
||||
);
|
||||
bookUseCase.registerBook(info);
|
||||
}
|
||||
assertEquals(livres.size(), bookRepository.findAll().size());
|
||||
assertEquals(books.size(), bookRepository.findAll().size());
|
||||
}
|
||||
|
||||
@And("Le systeme contient les utilisateur suivants:")
|
||||
public void leSystemeContientLesUtilisateurSuivants(DataTable dataTable) {
|
||||
@And("The system contains the following users:")
|
||||
public void theSystemContainsTheFollowingUsers(DataTable dataTable) {
|
||||
customerRepository.deleteAll();
|
||||
List<Map<String, String>> customers = dataTable.asMaps(String.class, String.class);
|
||||
for (Map<String, String> customer : customers) {
|
||||
@@ -88,8 +88,8 @@ public class OrderSteps {
|
||||
assertEquals(customers.size(), customerRepository.findAll().size());
|
||||
}
|
||||
|
||||
@When("Je crée une nouvelle commande avec les informations suivantes :")
|
||||
public void jeCreeUneNouvelleCommandeAvecLesInformationsSuivantes(DataTable dataTable) {
|
||||
@When("I create a new order with the following information:")
|
||||
public void iCreateANewOrderWithTheFollowingInformation(DataTable dataTable) {
|
||||
try {
|
||||
Map<String, String> orderData = dataTable.asMaps().getFirst();
|
||||
String customerId = orderData.get("customerId");
|
||||
@@ -115,11 +115,11 @@ public class OrderSteps {
|
||||
}
|
||||
}
|
||||
|
||||
@And("La commande contient les livres suivants :")
|
||||
public void laCommandeContientLesLivresSuivants(DataTable dataTable) {
|
||||
@And("The order contains the following books:")
|
||||
public void theOrderContainsTheFollowingBooks(DataTable dataTable) {
|
||||
try {
|
||||
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;
|
||||
}
|
||||
List<OrderLineDTO> lines = new ArrayList<>();
|
||||
@@ -135,17 +135,17 @@ public class OrderSteps {
|
||||
}
|
||||
}
|
||||
|
||||
@And("L'adresse de livraison est :")
|
||||
public void lAdresseDeLivraisonEst(DataTable dataTable) {
|
||||
@And("The shipping address is:")
|
||||
public void theShippingAddressIs(DataTable dataTable) {
|
||||
try {
|
||||
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()
|
||||
.allMatch(value -> value == null || value.trim().isEmpty());
|
||||
.allMatch(value -> value == null || value.trim().isEmpty());
|
||||
|
||||
if (isAddressEmpty) {
|
||||
throw new WrongAddressException("L'adresse de livraison est vide");
|
||||
throw new WrongAddressException("The shipping address is empty");
|
||||
}
|
||||
|
||||
AddressDTO shippingAddress = AddressDTO.builder()
|
||||
@@ -163,52 +163,52 @@ public class OrderSteps {
|
||||
}
|
||||
}
|
||||
|
||||
@Then("Une nouvelle commande est créée")
|
||||
public void uneNouvelleCommandeEstCreee() {
|
||||
@Then("A new order is created")
|
||||
public void aNewOrderIsCreated() {
|
||||
try {
|
||||
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();
|
||||
if (address == null || address.getStreet() == null || address.getStreet().trim().isEmpty()
|
||||
|| address.getCity() == null || address.getCity().trim().isEmpty()
|
||||
|| address.getPostalCode() == null || address.getPostalCode().trim().isEmpty()
|
||||
|| address.getCountry() == null || address.getCountry().trim().isEmpty()) {
|
||||
throw new WrongAddressException("L'adresse de livraison est manquante ou incomplète");
|
||||
|| address.getCity() == null || address.getCity().trim().isEmpty()
|
||||
|| address.getPostalCode() == null || address.getPostalCode().trim().isEmpty()
|
||||
|| address.getCountry() == null || address.getCountry().trim().isEmpty()) {
|
||||
throw new WrongAddressException("The shipping address is missing or incomplete");
|
||||
}
|
||||
|
||||
// Création de la commande
|
||||
// Create the order
|
||||
lastOrderId = orderUseCase.createOrder(currentOrderInfo);
|
||||
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));
|
||||
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
|
||||
assertEquals(UUID.fromString(currentOrderInfo.getCustomerId()), createdOrder.getCustomerId(), "L'ID client doit correspondre");
|
||||
assertEquals(currentOrderInfo.getPaymentMethod(), createdOrder.getPaymentMethod(), "La méthode de paiement doit correspondre");
|
||||
assertNotNull(createdOrder.getShippingAddress(), "L'adresse de livraison ne doit pas être nulle");
|
||||
assertFalse(createdOrder.getOrderLines().isEmpty(), "La commande doit contenir au moins une ligne");
|
||||
// Check order data
|
||||
assertEquals(UUID.fromString(currentOrderInfo.getCustomerId()), createdOrder.getCustomerId(), "Customer ID must match");
|
||||
assertEquals(currentOrderInfo.getPaymentMethod(), createdOrder.getPaymentMethod(), "Payment method must match");
|
||||
assertNotNull(createdOrder.getShippingAddress(), "Shipping address must not be null");
|
||||
assertFalse(createdOrder.getOrderLines().isEmpty(), "Order must contain at least one line");
|
||||
} catch (Exception e) {
|
||||
lastException = e;
|
||||
lastOrderId = null;
|
||||
}
|
||||
assertNull(lastException, "Aucune exception ne doit être levée lors de la création de la commande");
|
||||
assertNotNull(lastOrderId, "L'ID de la commande ne doit pas être null");
|
||||
assertNull(lastException, "No exception should be thrown when creating the order");
|
||||
assertNotNull(lastOrderId, "Order ID must not be null");
|
||||
}
|
||||
|
||||
@Then("Le prix total est {double}")
|
||||
public void lePrixTotalEst(double expectedTotal) {
|
||||
assertNotNull(lastOrderId, "L'ID de la commande ne doit pas être null");
|
||||
@Then("The total price is {double}")
|
||||
public void theTotalPriceIs(double expectedTotal) {
|
||||
assertNotNull(lastOrderId, "Order ID must not be null");
|
||||
OrderDTO order = orderUseCase.findOrderById(String.valueOf(lastOrderId));
|
||||
assertEquals(expectedTotal, order.getTotalPrice(), 0.01);
|
||||
}
|
||||
|
||||
@Then("La création de la commande échoue")
|
||||
public void laCreationDeLaCommandeEchoue() {
|
||||
// Si lastException est déjà défini, on ne fait rien de plus
|
||||
@Then("Order creation fails")
|
||||
public void orderCreationFails() {
|
||||
// If lastException is already set, do nothing
|
||||
if (lastException != null) {
|
||||
return;
|
||||
}
|
||||
@@ -218,84 +218,84 @@ public class OrderSteps {
|
||||
throw new CustomerNotFoundException(null);
|
||||
}
|
||||
|
||||
// Vérifier que l'adresse est valide
|
||||
// Check that the address is valid
|
||||
AddressDTO address = currentOrderInfo.getAddress();
|
||||
if (address == null || address.getStreet() == null || address.getStreet().trim().isEmpty()
|
||||
|| address.getCity() == null || address.getCity().trim().isEmpty()
|
||||
|| address.getPostalCode() == null || address.getPostalCode().trim().isEmpty()
|
||||
|| address.getCountry() == null || address.getCountry().trim().isEmpty()) {
|
||||
throw new WrongAddressException("L'adresse de livraison est manquante ou incomplète");
|
||||
|| address.getCity() == null || address.getCity().trim().isEmpty()
|
||||
|| address.getPostalCode() == null || address.getPostalCode().trim().isEmpty()
|
||||
|| address.getCountry() == null || address.getCountry().trim().isEmpty()) {
|
||||
throw new WrongAddressException("The shipping address is missing or incomplete");
|
||||
}
|
||||
|
||||
lastOrderId = orderUseCase.createOrder(currentOrderInfo);
|
||||
fail("La création de la commande aurait dû échouer");
|
||||
fail("Order creation should have failed");
|
||||
} catch (Exception e) {
|
||||
lastException = e;
|
||||
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é")
|
||||
public void leClientAPointsDeFidelite(String clientId, int points) {
|
||||
@And("Customer {string} has {int} loyalty points")
|
||||
public void customerHasLoyaltyPoints(String clientId, int points) {
|
||||
Customer customer = customerRepository.findById(UUID.fromString(clientId)).orElseThrow();
|
||||
assertEquals(points, customer.getLoyaltyPoints());
|
||||
}
|
||||
|
||||
@And("Je reçois une erreur indiquant que l'adresse de livraison est manquante")
|
||||
public void jeRecoisUneErreurIndiquantQueLAdresseDeLivraisonEstManquante() {
|
||||
@And("I receive an error indicating that the shipping address is missing")
|
||||
public void iReceiveAnErrorIndicatingThatTheShippingAddressIsMissing() {
|
||||
assertNotNull(lastException);
|
||||
assertInstanceOf(WrongAddressException.class, lastException);
|
||||
}
|
||||
|
||||
@And("Je reçois une erreur indiquant que le client n'a pas été trouvé")
|
||||
public void jeRecoisUneErreurIndiquantQueLeClientNaPasEteTrouve() {
|
||||
@And("I receive an error indicating that the customer was not found")
|
||||
public void iReceiveAnErrorIndicatingThatTheCustomerWasNotFound() {
|
||||
assertInstanceOf(CustomerNotFoundException.class, lastException);
|
||||
}
|
||||
|
||||
@And("Je reçois une erreur indiquant que les points de fidélité sont insuffisants")
|
||||
public void jeRecoisUneErreurIndiquantQueLesPointsDeFideliteSontInsuffisants() {
|
||||
@And("I receive an error indicating that loyalty points are insufficient")
|
||||
public void iReceiveAnErrorIndicatingThatLoyaltyPointsAreInsufficient() {
|
||||
assertNotNull(lastException);
|
||||
assertInstanceOf(IllegalOrderPointException.class, lastException);
|
||||
}
|
||||
|
||||
@And("Je reçois une erreur indiquant que le stock de livres est insuffisant")
|
||||
public void jeRecoisUneErreurIndiquantQueLeStockDeLivresEstInsuffisant() {
|
||||
@And("I receive an error indicating that book stock is insufficient")
|
||||
public void iReceiveAnErrorIndicatingThatBookStockIsInsufficient() {
|
||||
assertNotNull(lastException);
|
||||
assertInstanceOf(OrderQuantityException.class, lastException);
|
||||
}
|
||||
|
||||
@And("Je reçois une erreur indiquant que le mode de paiement est invalide")
|
||||
public void jeRecoisUneErreurIndiquantQueLeModeDePaiementEstInvalide() {
|
||||
@And("I receive an error indicating that the payment method is invalid")
|
||||
public void iReceiveAnErrorIndicatingThatThePaymentMethodIsInvalid() {
|
||||
assertNotNull(lastException);
|
||||
assertInstanceOf(InvalidPaymentMethodException.class, lastException);
|
||||
}
|
||||
|
||||
@And("Je reçois une erreur indiquant que le livre n'a pas été trouvé")
|
||||
public void jeRecoisUneErreurIndiquantQueLeLivreNAPasEteTrouve() {
|
||||
@And("I receive an error indicating that the book was not found")
|
||||
public void iReceiveAnErrorIndicatingThatTheBookWasNotFound() {
|
||||
assertNotNull(lastException);
|
||||
assertInstanceOf(BookNotFoundException.class, lastException);
|
||||
}
|
||||
|
||||
@And("La commande ne contient aucun livre")
|
||||
public void laCommandeNeContientAucunLivre() {
|
||||
@And("The order contains no books")
|
||||
public void theOrderContainsNoBooks() {
|
||||
currentOrderInfo.setOrderLines(new ArrayList<>());
|
||||
}
|
||||
|
||||
@And("Je reçois une erreur indiquant que la commande doit contenir au moins un livre")
|
||||
public void jeRecoisUneErreurIndiquantQueLaCommandeDoitContenirAuMoinsUnLivre() {
|
||||
@And("I receive an error indicating that the order must contain at least one book")
|
||||
public void iReceiveAnErrorIndicatingThatTheOrderMustContainAtLeastOneBook() {
|
||||
assertNotNull(lastException);
|
||||
assertInstanceOf(OrderQuantityException.class, lastException);
|
||||
}
|
||||
|
||||
@And("Je reçois une erreur indiquant que la quantité de livres doit être positive")
|
||||
public void jeRecoisUneErreurIndiquantQueLaQuantiteDeLivresDoitEtrePositive() {
|
||||
@And("I receive an error indicating that the quantity of books must be positive")
|
||||
public void iReceiveAnErrorIndicatingThatTheQuantityOfBooksMustBePositive() {
|
||||
assertNotNull(lastException);
|
||||
assertInstanceOf(OrderQuantityException.class, lastException);
|
||||
}
|
||||
|
||||
@Given("Il existe une commande avec l'ID {string} pour le client {string}")
|
||||
public void ilExisteUneCommandeAvecLIDPourLeClient(String orderId, String clientId) {
|
||||
@Given("There is an order with ID {string} for customer {string}")
|
||||
public void thereIsAnOrderWithIDForCustomer(String orderId, String clientId) {
|
||||
Order order = Order.builder()
|
||||
.id(UUID.fromString(orderId))
|
||||
.customerId(UUID.fromString(clientId))
|
||||
@@ -307,8 +307,8 @@ public class OrderSteps {
|
||||
orderRepository.save(order);
|
||||
}
|
||||
|
||||
@When("Je récupère la commande par ID {string}")
|
||||
public void jeRecupereLaCommandeParID(String orderId) {
|
||||
@When("I retrieve the order by ID {string}")
|
||||
public void iRetrieveTheOrderByID(String orderId) {
|
||||
try {
|
||||
UUID uuid;
|
||||
try {
|
||||
@@ -326,14 +326,14 @@ public class OrderSteps {
|
||||
}
|
||||
}
|
||||
|
||||
@Then("Je reçois une commande")
|
||||
public void jeRecoisUneCommande() {
|
||||
assertNull(lastException, "Aucune exception ne doit être levée");
|
||||
assertTrue(lastOrderDTO.isPresent(), "La commande doit être présente");
|
||||
@Then("I receive an order")
|
||||
public void iReceiveAnOrder() {
|
||||
assertNull(lastException, "No exception should be thrown");
|
||||
assertTrue(lastOrderDTO.isPresent(), "The order should be present");
|
||||
}
|
||||
|
||||
@When("Je demande toutes les commandes pour le client {string}")
|
||||
public void jeDemandeToutesLesCommandesPourLeClient(String clientId) {
|
||||
@When("I request all orders for customer {string}")
|
||||
public void iRequestAllOrdersForCustomer(String clientId) {
|
||||
try {
|
||||
lastOrderList = orderUseCase.findOrdersByCustomerId(clientId);
|
||||
lastException = null;
|
||||
@@ -343,22 +343,20 @@ public class OrderSteps {
|
||||
}
|
||||
}
|
||||
|
||||
@Then("La récupération échoue")
|
||||
public void laRecuperationEchoue() {
|
||||
assertNotNull(lastException, "Une exception doit être levée");
|
||||
@Then("Retrieval fails")
|
||||
public void retrievalFails() {
|
||||
assertNotNull(lastException, "An exception should be thrown");
|
||||
}
|
||||
|
||||
|
||||
@Then("Je reçois une liste de commandes")
|
||||
public void jeRecoisUneListeDeCommandes() {
|
||||
assertNull(lastException, "Aucune exception ne doit être levée");
|
||||
assertNotNull(lastOrderList, "La liste des commandes ne doit pas être nulle");
|
||||
@Then("I receive a list of orders")
|
||||
public void iReceiveAListOfOrders() {
|
||||
assertNull(lastException, "No exception should be thrown");
|
||||
assertNotNull(lastOrderList, "The list of orders must not be null");
|
||||
}
|
||||
|
||||
@And("Je reçois une erreur indiquant que la commande n'a pas été trouvée")
|
||||
public void jeRecoisUneErreurIndiquantQueLaCommandeNAPasEteTrouvee() {
|
||||
@And("I receive an error indicating that the order was not found")
|
||||
public void iReceiveAnErrorIndicatingThatTheOrderWasNotFound() {
|
||||
assertNotNull(lastException);
|
||||
assertInstanceOf(OrderNotFoundException.class, lastException);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Reference in New Issue
Block a user