Merge branch 'email-service' into 'dev'

Email Service

See merge request cse2115/2023-2024/group-12/team-12a!45
This commit is contained in:
Sandi Fazakas 2024-01-10 19:41:24 +01:00
commit 4b22198c04
42 changed files with 2652 additions and 678 deletions

View file

@ -50,6 +50,7 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-mail'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-webflux
implementation 'org.springframework.boot:spring-boot-starter-webflux'

View file

@ -1,8 +1,11 @@
package nl.tudelft.sem.yumyumnow.order;
import nl.tudelft.sem.yumyumnow.order.config.NotificationConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
/**

View file

@ -0,0 +1,46 @@
package nl.tudelft.sem.yumyumnow.order.config;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.io.IOException;
import nl.tudelft.sem.yumyumnow.order.external.notification.MockMailSender;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.mail.MailSender;
/**
* A configuration class for email.
*/
@Configuration
@ComponentScan(basePackageClasses = {MockMailSender.class})
public class EmailConfig {
@Value("${notification.config}")
private Resource notificationConfigFile;
/**
* A bean that can send emails.
*
* @return a JavaMailSender.
*/
@Bean
public MailSender getJavaMailService() {
return new MockMailSender();
}
/**
* A bean that can read the notification config file.
*
* @return a NotificationConfig.
* @throws JsonProcessingException when the config file is not valid.
*/
@Bean
public NotificationConfig getNotificationConfig() throws IOException {
final ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
return mapper.readValue(notificationConfigFile.getFile(), NotificationConfig.class);
}
}

View file

@ -0,0 +1,43 @@
package nl.tudelft.sem.yumyumnow.order.config;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import lombok.Setter;
import org.order.model.Status;
/**
* A configuration class for notifications.
*/
@Setter
@Getter
public class NotificationConfig {
@JsonProperty
private Email email;
/**
* A configuration class for email.
*/
@Setter
@Getter
public static class Email {
// getters and setters
@JsonProperty
private List<Status.StatusEnum> statuses;
@JsonProperty
private Map<String, Template> templates;
/**
* A configuration class for email templates.
*/
@Setter
@Getter
public static class Template {
@JsonProperty
private String subject;
@JsonProperty
private String body;
}
}
}

View file

@ -65,7 +65,7 @@ public class SpringConfig {
*
* @return a real users-microservice service
*/
@Profile("!dev")
@Profile("!dev & !mockUsersMicroservice")
@Primary
@Bean
public UsersMicroservice getUsersMicroserviceService() {

View file

@ -2,11 +2,10 @@ package nl.tudelft.sem.yumyumnow.order.controllers;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import java.util.LinkedList;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import nl.tudelft.sem.yumyumnow.order.domain.order.OrderService;
import nl.tudelft.sem.yumyumnow.order.external.notification.EmailService;
import nl.tudelft.sem.yumyumnow.order.utils.UserDetailsParser;
import org.order.api.OrderApi;
import org.order.model.Location;
@ -33,20 +32,23 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class OrderController implements OrderApi {
private final transient OrderService orderService;
private final transient UserDetailsParser userDetailsParser;
private final OrderService orderService;
private final UserDetailsParser userDetailsParser;
private final EmailService emailService;
/**
* Constructs a new {@code OrderController} with the specified {@code OrderService}.
*
* @param orderService the service responsible for order-related operations (must not be {@code null})
* @param orderService the service responsible for order-related operations (must not be {@code null})
* @param userDetailsParser the auth manager.
*/
@Autowired
public OrderController(OrderService orderService, UserDetailsParser userDetailsParser) {
public OrderController(OrderService orderService, UserDetailsParser userDetailsParser, EmailService emailService) {
this.orderService = orderService;
this.userDetailsParser = userDetailsParser;
this.emailService = emailService;
}
private boolean isVendorOfOrder(Long userId, Long orderId) throws UserDetailsParser.InvalidHeaderException {
@ -75,25 +77,20 @@ public class OrderController implements OrderApi {
}
/**
* GET /order/{orderId}/status : Get status
* Returns the status of the order requested.
* If the user is a customer, then the customer must be the one that ordered the order.
* If the user is a vendor, it should be a vendor the order is for. Admins can do so always.
* GET /order/{orderId}/status : Get status Returns the status of the order requested. If the user is a customer,
* then the customer must be the one that ordered the order. If the user is a vendor, it should be a vendor the
* order is for. Admins can do so always.
*
* @param orderId the ID of the order (required)
* @param userId the ID of the user making the request (required)
* @return Success (status code 200)
* or Unauthorized (status code 401)
* or Order not found (status code 404)
* @return Success (status code 200) or Unauthorized (status code 401) or Order not found (status code 404)
*/
@Override
public ResponseEntity<Status> getStatus(
@Parameter(name = "orderId", description = "ID of the order", required = true, in = ParameterIn.PATH)
@PathVariable("orderId") Long orderId,
@NotNull @Parameter(name = "userId", description = "ID of the user",
required = true, in = ParameterIn.HEADER)
@PathVariable("orderId") Long orderId, @NotNull
@Parameter(name = "userId", description = "ID of the user", required = true, in = ParameterIn.HEADER)
@RequestHeader(value = "userId", required = true) Long userId) {
// Check if order exists
@ -121,22 +118,15 @@ public class OrderController implements OrderApi {
/**
* PUT /order/{orderId}/status : Update status
* This will update the status of the order. Only the vendor the order is for and admins can do this.
* The status must be one of the following: &#x60;pending&#x60;,
* &#x60;accepted&#x60;,
* &#x60;rejected&#x60;,
* &#x60;preparing&#x60;,
* &#x60;given to courier&#x60;,
* &#x60;on-transit&#x60;
* and &#x60;delivered.&#x60;
* PUT /order/{orderId}/status : Update status This will update the status of the order. Only the vendor the order
* is for and admins can do this. The status must be one of the following: &#x60;pending&#x60;,
* &#x60;accepted&#x60;, &#x60;rejected&#x60;, &#x60;preparing&#x60;, &#x60;given to courier&#x60;,
* &#x60;on-transit&#x60; and &#x60;delivered.&#x60;
*
* @param orderId (required)
* @param userId (required)
* @param updateStatusRequest (optional)
* @return Success (status code 200)
* or Unauthorized (status code 401)
* or Order not found (status code 404)
* @param orderId (required)
* @param userId (required)
* @param updateStatusRequest (optional)
* @return Success (status code 200) or Unauthorized (status code 401) or Order not found (status code 404)
*/
@Override
public ResponseEntity<Void> updateStatus(
@ -144,13 +134,12 @@ public class OrderController implements OrderApi {
@PathVariable("orderId") Long orderId,
@NotNull @Parameter(name = "userId", description = "", required = true, in = ParameterIn.HEADER)
@RequestHeader(value = "userId", required = true) Long userId,
@Parameter(name = "UpdateStatusRequest", description = "") @Valid
@RequestBody(required = false) UpdateStatusRequest updateStatusRequest) {
@Parameter(name = "UpdateStatusRequest", description = "") @Valid @RequestBody(required = false)
UpdateStatusRequest updateStatusRequest) {
//Check if Order exists
if (!orderService.doesOrderExist(orderId)) {
throw new NotFoundException("Order with id " + orderId + " does not exist");
}
Order order = orderService.getOrder(orderId)
.orElseThrow(() -> new NotFoundException("Order with id " + orderId + " does not exist"));
// Check if its Vendor of the Order or Admin
try {
@ -163,13 +152,23 @@ public class OrderController implements OrderApi {
}
if (updateStatusRequest == null || updateStatusRequest.getStatus() == null) {
if (updateStatusRequest == null || updateStatusRequest.getStatus() == null) {
throw new BadRequestException("Status is null, bad request!");
}
try {
orderService.updateStatus(orderId, new Status()
.status(Status.StatusEnum.fromValue(updateStatusRequest.getStatus())));
Status.StatusEnum newStatus = Status.StatusEnum.fromValue(updateStatusRequest.getStatus());
Status.StatusEnum oldStatus = order.getStatus().getStatus();
if (newStatus != oldStatus) {
orderService.updateStatus(orderId, new Status().status(newStatus));
// Email the customer according to the status
try {
emailService.statusMail(order.getCustomerId(), orderId, newStatus);
} catch (EmailService.NoEmailAddressException e) {
System.err.printf("No email address found for customer with id %d, so no email was sent%n",
order.getCustomerId());
}
}
return new ResponseEntity<>(HttpStatus.OK);
} catch (IllegalArgumentException e) {
throw new BadRequestException("Status is not a valid type, bad request!");
@ -179,27 +178,23 @@ public class OrderController implements OrderApi {
/**
* POST /order : Make an order
* Only customers can create an order. If address is left empty, the home address of the user is used.
* The addresses will be stored as GPS-coordinates.
* The time of the order will be added by the microservice and the rating will initially be empty.
* This will return a link to the payment service if a non-cash payment method is provided.
* What should happen is the order should have status \\&#x60;pending\\&#x60;
* until the payment service makes a request signifying that the payment was accepted.
* POST /order : Make an order Only customers can create an order. If address is left empty, the home address of
* the user is used. The addresses will be stored as GPS-coordinates. The time of the order will be added by the
* microservice and the rating will initially be empty. This will return a link to the payment service if a non-cash
* payment method is provided. What should happen is the order should have status \\&#x60;pending\\&#x60; until the
* payment service makes a request signifying that the payment was accepted.
*
* @param userId the user calling the endpoint (required)
* @param order (optional)
* @return Success (status code 200)
* or Bad request (status code 400)
* or Unauthorized (status code 401)
* @return Success (status code 200) or Bad request (status code 400) or Unauthorized (status code 401)
*/
@Override
public ResponseEntity<Order200Response> order(
@NotNull @Parameter(name = "userId", description = "the user calling the endpoint",
required = true, in = ParameterIn.HEADER)
@RequestHeader(value = "userId", required = true) Long userId,
@Parameter(name = "Order", description = "") @Valid @RequestBody(required = false) Order order
) {
public ResponseEntity<Order200Response> order(@NotNull @Parameter(name = "userId",
description = "the user calling the endpoint",
required = true,
in = ParameterIn.HEADER) @RequestHeader(value = "userId", required = true) Long userId,
@Parameter(name = "Order", description = "") @Valid
@RequestBody(required = false) Order order) {
Location deliveryLocation;
String role;
try {
@ -235,8 +230,8 @@ public class OrderController implements OrderApi {
// Either customer id is null (assign userId as customer id)
// or customer id should be a customer and match the userId
if (role.equals("customer")) {
if (order.getCustomerId() == null
|| (order.getCustomerId().equals(userId) && isCustomer(order.getCustomerId()))) {
if (order.getCustomerId() == null || (order.getCustomerId().equals(userId) && isCustomer(
order.getCustomerId()))) {
customerId = userId;
} else {
throw new BadRequestException("Customer Id should be null or match the userId");
@ -267,15 +262,11 @@ public class OrderController implements OrderApi {
throw new BadRequestException("Vendor with id " + order.getVendorId() + " does not exist");
}
// Check if there is a price provided
if (order.getPrice() == null) {
throw new BadRequestException("Price is invalid, bad request!");
}
// Check if List of dishes is provided
if (order.getDishes() == null || order.getDishes().isEmpty()) {
throw new BadRequestException("list of dishes is invalid, bad request!");
@ -285,42 +276,38 @@ public class OrderController implements OrderApi {
if (order.getDishes().size() < order.getDishRequirements().size()) {
throw new BadRequestException("There is not a matching list of dish requirements");
}
orderService.createOrder(
customerId,
order.getVendorId(),
deliveryLocation,
order.getDishes(),
order.getDishRequirements(),
order.getPrice(),
order.getComment());
Order newOrder = orderService.createOrder(customerId, order.getVendorId(), deliveryLocation, order.getDishes(),
order.getDishRequirements(), order.getPrice(), order.getComment());
Order200Response order200Response = new Order200Response();
// Email the customer that the order is pending
try {
emailService.statusMail(newOrder.getCustomerId(), newOrder.getId(), newOrder.getStatus().getStatus());
} catch (EmailService.NoEmailAddressException e) {
System.err.printf("No email address found for customer with id %d, so no email was sent%n",
newOrder.getCustomerId());
}
return new ResponseEntity<>(order200Response, HttpStatus.OK);
}
/**
* PUT /order/{orderId}/address : Update the address of an order
* This will update the location of an order.
* Only an admin should be able to update address of an order.
* The address will be stored as a GPS-location.
* PUT /order/{orderId}/address : Update the address of an order This will update the location of an order. Only an
* admin should be able to update address of an order. The address will be stored as a GPS-location.
*
* @param orderId (required)
* @param userId the user calling the endpoint (required)
* @param updateAddressRequest (optional)
* @return Success (status code 200)
* or Unauthorized (status code 401)
* or Order not found (status code 404)
* @param orderId (required)
* @param userId the user calling the endpoint (required)
* @param updateAddressRequest (optional)
* @return Success (status code 200) or Unauthorized (status code 401) or Order not found (status code 404)
*/
@Override
public ResponseEntity<Void> updateAddress(
@Parameter(name = "orderId", description = "", required = true, in = ParameterIn.PATH)
@PathVariable("orderId") Long orderId,
@NotNull @Parameter(name = "userId", description = "the user calling the endpoint",
required = true, in = ParameterIn.HEADER)
@RequestHeader(value = "userId", required = true) Long userId,
@Parameter(name = "UpdateAddressRequest", description = "")
@Valid @RequestBody(required = false) UpdateAddressRequest updateAddressRequest
) {
@PathVariable("orderId") Long orderId, @NotNull @Parameter(name = "userId",
description = "the user calling the endpoint",
required = true,
in = ParameterIn.HEADER) @RequestHeader(value = "userId", required = true) Long userId,
@Parameter(name = "UpdateAddressRequest", description = "") @Valid @RequestBody(required = false)
UpdateAddressRequest updateAddressRequest) {
// Check if order exists
if (!orderService.doesOrderExist(orderId)) {
throw new NotFoundException("Order with id " + orderId + " does not exist");
@ -342,7 +329,7 @@ public class OrderController implements OrderApi {
throw new BadRequestException("Latitude or longitude are null, bad request!");
}
orderService.updateDeliveryAddress(orderId, updateAddressRequest.getAddress());
orderService.updateDeliveryAddress(orderId, updateAddressRequest.getAddress());
return new ResponseEntity<>(HttpStatus.OK);
}
@ -350,7 +337,7 @@ public class OrderController implements OrderApi {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public String handleNotFoundException(RuntimeException e) {
public String handleNotFoundException(RuntimeException e) {
return e.getMessage();
}
@ -364,7 +351,7 @@ public class OrderController implements OrderApi {
@ExceptionHandler(UnauthorizedException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public String handleUnauthorizedException(RuntimeException e) {
public String handleUnauthorizedException(RuntimeException e) {
return e.getMessage();
}
@ -379,7 +366,7 @@ public class OrderController implements OrderApi {
@ExceptionHandler(BadRequestException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public String handleBadRequestException(RuntimeException e) {
public String handleBadRequestException(RuntimeException e) {
return e.getMessage();
}
@ -391,4 +378,3 @@ public class OrderController implements OrderApi {
}
}

View file

@ -1,9 +1,10 @@
package nl.tudelft.sem.yumyumnow.order.external;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import lombok.NonNull;
import java.util.stream.Stream;
import org.order.model.Customer;
import org.order.model.Location;
import org.order.model.User;
@ -14,9 +15,9 @@ import reactor.core.publisher.Flux;
* Mock Interface for the users-microservice.
*/
public class MockUsersMicroserviceService implements UsersMicroservice {
private final transient Collection<Customer> customers;
private final transient Collection<Vendor> vendors;
private final transient Collection<User> admins;
private final Collection<Customer> customers;
private final Collection<Vendor> vendors;
private final Collection<User> admins;
/**
* Instantiates a new Users microservice.
@ -25,12 +26,11 @@ public class MockUsersMicroserviceService implements UsersMicroservice {
* @param customers the customers.
* @param admins the admins.
*/
public MockUsersMicroserviceService(@NonNull Collection<Customer> customers,
@NonNull Collection<Vendor> vendors,
@NonNull Collection<User> admins) {
this.customers = customers;
this.vendors = vendors;
this.admins = admins;
public MockUsersMicroserviceService(Collection<Customer> customers, Collection<Vendor> vendors,
Collection<User> admins) {
this.customers = Optional.ofNullable(customers).orElse(Collections.emptySet());
this.vendors = Optional.ofNullable(vendors).orElse(Collections.emptySet());
this.admins = Optional.ofNullable(admins).orElse(Collections.emptySet());
}
/**
@ -63,6 +63,39 @@ public class MockUsersMicroserviceService implements UsersMicroservice {
return Optional.empty();
}
/**
* Gets the user details.
*
* @param id the id of the user.
* @return the user.
*/
@Override
public Optional<User> getUser(Long id) {
return Stream.concat(customers.stream()
.map(customer -> new User().id(customer.getId())
.firstName(customer.getFirstName())
.lastName(customer.getLastName())), Stream.concat(vendors.stream()
.map(vendor -> new User().id(vendor.getId())
.firstName(vendor.getFirstName())
.lastName(vendor.getLastName())), admins.stream()))
.filter(user -> user.getId().equals(id))
.findFirst();
}
/**
* Gets the email of a user.
*
* @param id the id of the user.
* @return the email of the user.
*/
@Override
public Optional<String> getEmail(Long id) {
return customers.stream()
.filter(customer -> customer.getId().equals(id))
.findFirst()
.map(Customer::getEmailAddress);
}
/** Get the allergies of a user.
* @param id the id of the user. the id of the user to get the allergy of.
@ -92,13 +125,10 @@ public class MockUsersMicroserviceService implements UsersMicroservice {
*/
@Override
public Optional<Location> getHomeAddress(Long userId) {
// Retrieve location from user
Optional<Location> matchingCustomer = customers.stream()
return customers.stream()
.filter(customer -> customer.getId().equals(userId))
.findFirst()
.map(Customer::getHomeLocation);
return matchingCustomer;
.map(org.order.model.Customer::getHomeLocation);
}

View file

@ -2,6 +2,7 @@ package nl.tudelft.sem.yumyumnow.order.external;
import java.util.Optional;
import org.order.model.Location;
import org.order.model.User;
import org.order.model.Vendor;
import reactor.core.publisher.Flux;
@ -25,6 +26,15 @@ public interface UsersMicroservice {
*/
Optional<String> getRole(Long id);
/**
* Gets the user details.
*
* @param id the id of the user.
*
* @return the user.
*/
Optional<User> getUser(Long id);
/**
* Gets the default home address of a Customer.
*
@ -34,6 +44,15 @@ public interface UsersMicroservice {
*/
Optional<Location> getHomeAddress(Long userId);
/**
* Gets the email of a user.
*
* @param id the id of the user.
*
* @return the email of the user.
*/
Optional<String> getEmail(Long id);
/** Gets the allergies of a user.
* @param id the id of the user.

View file

@ -6,6 +6,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
import java.util.Optional;
import org.order.model.Location;
import org.order.model.User;
import org.order.model.Vendor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
@ -89,6 +90,32 @@ public class UsersMicroserviceService implements UsersMicroservice {
.blockOptional();
}
/**
* Gets the user details.
*
* @param id the id of the user.
*
* @return the user.
*/
@Override
public Optional<User> getUser(Long id) {
String endpointUrl = apiUrl + "/user/" + id;
return webClientBuilder.build()
.get()
.uri(endpointUrl)
.retrieve()
.onStatus(
// Define the condition for an error status
status -> status.is4xxClientError() || status.is5xxServerError(),
response -> Mono.error(new RuntimeException("Failed to fetch user")))
.bodyToMono(User.class)
.onErrorResume(error -> {
System.err.println(error.getMessage());
return Mono.empty();
})
.blockOptional();
}
/**
* Gets the home address of a user.
*
@ -114,6 +141,34 @@ public class UsersMicroserviceService implements UsersMicroservice {
.blockOptional();
}
/**
* Gets the email of a user.
*
* @param id the id of the user.
* @return the email of the user.
*/
@Override
public Optional<String> getEmail(Long id) {
String endpointUrl = apiUrl + "/customer/" + id;
return webClientBuilder.build()
.get()
.uri(endpointUrl)
.retrieve()
.onStatus(
// Define the condition for an error status
status -> status.is4xxClientError() || status.is5xxServerError(),
response -> Mono.error(new RuntimeException("Failed to fetch email")))
.bodyToMono(String.class)
.flatMap(responseBody ->
Mono.fromCallable(() -> new ObjectMapper().readTree(responseBody).get("email").asText()))
.filter(email -> !email.isEmpty())
.onErrorResume(error -> {
System.err.println(error.getMessage());
return Mono.empty();
})
.blockOptional();
}
@Override
public Flux<String> getAllAllergies(Long id) {
String endpointUrl = apiUrl + "/customer/%d/allergies".formatted(id);

View file

@ -0,0 +1,91 @@
package nl.tudelft.sem.yumyumnow.order.external.notification;
import java.io.Serial;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroservice;
import org.order.model.Status;
import org.order.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Service;
/**
* A service that can send emails.
*/
@Service("emailService")
public class EmailService {
private final MailSender mailSender;
private final UsersMicroservice usersMicroservice;
private final NotificationService notificationService;
/**
* Creates an instance of the email service.
*
* @param mailSender the mail sender
* @param usersMicroservice the users microservice
* @param notificationService the notification service
*/
@Autowired
public EmailService(MailSender mailSender, UsersMicroservice usersMicroservice,
NotificationService notificationService) {
this.mailSender = mailSender;
this.usersMicroservice = usersMicroservice;
this.notificationService = notificationService;
}
/**
* Sends an email.
*
* @param to the recipient
* @param subject the subject of the email
* @param body the body of the email
*/
public void sendMail(String to, String subject, String body) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to);
message.setSubject(subject);
message.setText(body);
mailSender.send(message);
}
/**
* Sends an email to a customer according to what status update occurred.
*
* @param customerId the id of the customer
* @param orderId the id of the order
* @param status the status of the order
* @throws NoEmailAddressException when no email address is found for the customer
* @throws IllegalArgumentException when orderId or customerId is null
*/
public void statusMail(Long customerId, Long orderId, Status.StatusEnum status) throws NoEmailAddressException {
if (orderId == null) {
throw new IllegalArgumentException("orderId cannot be null");
}
if (status == null) {
throw new IllegalArgumentException("customerId cannot be null");
}
if (!notificationService.getEmailStatuses().contains(status)) {
return;
}
String to = usersMicroservice.getEmail(customerId).orElseThrow(NoEmailAddressException::new);
String subject = notificationService.getEmailSubject(status).formatted(orderId);
User user = usersMicroservice.getUser(customerId).orElseThrow();
String body = notificationService.getEmailBody(status).formatted(user.getFirstName(), orderId);
sendMail(to, subject, body);
}
/**
* Exception thrown when no email address is found for a user.
*/
public static class NoEmailAddressException extends Exception {
@Serial
private static final long serialVersionUID = 4706289483152904397L;
/**
* Constructor.
*/
public NoEmailAddressException() {
super("No email address found for this user");
}
}
}

View file

@ -0,0 +1,37 @@
package nl.tudelft.sem.yumyumnow.order.external.notification;
import java.util.Arrays;
import org.springframework.lang.NonNull;
import org.springframework.mail.MailException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
/**
* A mock mail sender.
*/
public class MockMailSender implements MailSender {
/**
* A mock mail sender.
*
* @param simpleMailMessage the message to send.
* @throws MailException when the mail cannot be sent.
*/
@Override
public void send(@NonNull SimpleMailMessage simpleMailMessage) throws MailException {
System.out.printf("Sending mail to %s%nwith subject: %s%nand body:%s%n",
Arrays.toString(simpleMailMessage.getTo()),
simpleMailMessage.getSubject(),
simpleMailMessage.getText());
}
/**
* A mock mail sender.
*
* @param simpleMailMessages the messages to send.
* @throws MailException when the mail cannot be sent.
*/
@Override
public void send(@NonNull SimpleMailMessage... simpleMailMessages) throws MailException {
Arrays.stream(simpleMailMessages).forEach(this::send);
}
}

View file

@ -0,0 +1,54 @@
package nl.tudelft.sem.yumyumnow.order.external.notification;
import java.util.List;
import nl.tudelft.sem.yumyumnow.order.config.NotificationConfig;
import org.order.model.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* A service for notifications.
*/
@Service
public class NotificationService {
private final NotificationConfig notificationConfig;
/**
* Creates an instance of the notification service.
*
* @param notificationConfig the notification config.
*/
@Autowired
public NotificationService(NotificationConfig notificationConfig) {
this.notificationConfig = notificationConfig;
}
/**
* Gets the email statuses.
*
* @return the email statuses.
*/
public List<Status.StatusEnum> getEmailStatuses() {
return notificationConfig.getEmail().getStatuses();
}
/**
* Gets the email subject.
*
* @param status the status.
* @return the email subject.
*/
public String getEmailSubject(Status.StatusEnum status) {
return notificationConfig.getEmail().getTemplates().get(status.getValue()).getSubject();
}
/**
* Gets the email body.
*
* @param status the status.
* @return the email body.
*/
public String getEmailBody(Status.StatusEnum status) {
return notificationConfig.getEmail().getTemplates().get(status.getValue()).getBody();
}
}

View file

@ -15,3 +15,6 @@ admins.file=classpath:mock-properties/admins.properties
# URL of the external users microservice
external.users-microservice.url=http://localhost:6969
# The filepath of the file containing information about the notification rules
notification.config=classpath:notification-config.yml

View file

@ -0,0 +1,60 @@
# A list of statuses for which a customer is notified by email when an order is assigned that status
email:
statuses:
- pending
- accepted
- rejected
- preparing
- given to courier
- on-transit
- delivered
templates:
pending:
subject: Order %d is pending
body: >-
Dear %s,
Your order %d is pending.
Thank you for your order.
- YumYumNow
accepted:
subject: Order %d is accepted
body: >-
Dear %s,
Your order %d is accepted.
Thank you for your order.
- YumYumNow
rejected:
subject: Order %d is rejected
body: >-
Dear %s,
Your order %d is rejected.
Thank you for your order.
- YumYumNow
preparing:
subject: Order %d is being prepared
body: >-
Dear %s,
Your order %d is being prepared.
Thank you for your order.
- YumYumNow
given to courier:
subject: Order %d is given to a courier
body: >-
Dear %s,
Your order %d is given to a courier.
Thank you for your order.
- YumYumNow
on-transit:
subject: Order %d is on transit
body: >-
Dear %s,
Your order %d is on transit.
Thank you for your order.
- YumYumNow
delivered:
subject: Order %d is delivered
body: >-
Dear %s,
Your order %d is delivered.
Thank you for your order.
- YumYumNow

View file

@ -0,0 +1,161 @@
package nl.tudelft.sem.yumyumnow.order.external;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import nl.tudelft.sem.yumyumnow.order.external.notification.EmailService;
import nl.tudelft.sem.yumyumnow.order.external.notification.NotificationService;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.order.model.Status;
import org.order.model.User;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
class EmailServiceTest {
@InjectMocks
private EmailService emailService;
@Mock
private JavaMailSender mailSender;
private AutoCloseable closeable;
@Mock
private UsersMicroservice usersMicroservice;
@Mock
private NotificationService notificationService;
@BeforeEach
void setup() {
closeable = MockitoAnnotations.openMocks(this);
}
@AfterEach
void tearDown() throws Exception {
closeable.close();
}
@Test
void testSendMail_ValidRecipientSubjectBody() {
final String to = "test@example.com";
final String subject = "Test Subject";
final String body = "Test Body";
emailService.sendMail(to, subject, body);
ArgumentCaptor<SimpleMailMessage> argumentCaptor = ArgumentCaptor.forClass(SimpleMailMessage.class);
verify(mailSender, times(1)).send(argumentCaptor.capture());
SimpleMailMessage message = argumentCaptor.getValue();
assertEquals(to, Objects.requireNonNull(message.getTo())[0]);
assertEquals(subject, message.getSubject());
assertEquals(body, message.getText());
}
@Test
void testSendMail_EmptyRecipientSubjectBody() {
emailService.sendMail("", "", "");
verify(mailSender, times(1)).send((SimpleMailMessage) any());
}
@Test
void testSendMail_NullRecipientSubjectBody() {
emailService.sendMail(null, null, null);
verify(mailSender, times(1)).send((SimpleMailMessage) any());
}
@Test
void testStatusMail() throws EmailService.NoEmailAddressException {
final Long customerId = 1L;
final Long orderId = 2L;
final Status.StatusEnum status = Status.StatusEnum.PREPARING;
final String to = "testmail@mail.test";
final String firstName = "John";
final String subject = "Test Subject %d";
final String body = "Test Body %s %d";
when(usersMicroservice.getEmail(customerId)).thenReturn(Optional.of(to));
when(usersMicroservice.getUser(customerId)).thenReturn(Optional.of(new User().firstName(firstName)));
when(notificationService.getEmailSubject(status)).thenReturn(subject);
when(notificationService.getEmailBody(status)).thenReturn(body);
when(notificationService.getEmailStatuses()).thenReturn(List.of(Status.StatusEnum.values()));
emailService.statusMail(customerId, orderId, status);
SimpleMailMessage expectedMessage = new SimpleMailMessage();
expectedMessage.setTo(to);
expectedMessage.setSubject(subject.formatted(orderId));
expectedMessage.setText(body.formatted(firstName, orderId));
verify(mailSender, times(1)).send(expectedMessage);
}
@Test
void testStatusMail_NoEmailAddressException() {
final Long customerId = 1L;
final Long orderId = 2L;
final Status.StatusEnum status = Status.StatusEnum.PREPARING;
when(usersMicroservice.getEmail(customerId)).thenReturn(Optional.empty());
when(notificationService.getEmailStatuses()).thenReturn(List.of(Status.StatusEnum.values()));
assertThatThrownBy(() -> emailService.statusMail(customerId, orderId, status)).isInstanceOf(
EmailService.NoEmailAddressException.class);
verifyNoInteractions(mailSender);
}
@Test
void testStatusMail_NullCustomerId() {
final Long orderId = 2L;
final Status.StatusEnum status = Status.StatusEnum.PREPARING;
when(notificationService.getEmailStatuses()).thenReturn(List.of(Status.StatusEnum.values()));
assertThatThrownBy(() -> emailService.statusMail(null, orderId, status)).isInstanceOf(
EmailService.NoEmailAddressException.class);
verifyNoInteractions(mailSender);
}
@Test
void testStatusMail_NullOrderId() {
final Long customerId = 1L;
final Status.StatusEnum status = Status.StatusEnum.PREPARING;
assertThatThrownBy(() -> emailService.statusMail(customerId, null, status)).isInstanceOf(
IllegalArgumentException.class);
verifyNoInteractions(mailSender);
}
@Test
void testStatusMail_NullStatus() {
final Long customerId = 1L;
final Long orderId = 2L;
assertThatThrownBy(() -> emailService.statusMail(customerId, orderId, null)).isInstanceOf(
IllegalArgumentException.class);
verifyNoInteractions(mailSender);
}
}

View file

@ -1,234 +0,0 @@
package nl.tudelft.sem.yumyumnow.order.external;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.order.model.Customer;
import org.order.model.Location;
import org.order.model.User;
import org.order.model.Vendor;
class MockUsersMicroserviceServiceTest {
@Test
void getAllVendorsAllThere() {
Collection<Vendor> vendors = Stream.builder()
.add(new Vendor().id(1L).firstName("Vendor 1").lastName("The First")
.location(new Location().latitude(1f).longitude(1f)))
.add(new Vendor().id(2L).firstName("Vendor 2").lastName("The Second")
.location(new Location().latitude(2f).longitude(2f)))
.add(new Vendor().id(3L).firstName("Vendor 3").lastName("The Third")
.location(new Location().latitude(3f).longitude(3f))).build().map(vendor -> (Vendor) vendor)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
Collections.emptySet(),
vendors,
Collections.emptySet());
assertEquals(3, mockUsersMicroserviceService.getAllVendors().count().block());
assertTrue(Objects.requireNonNull(mockUsersMicroserviceService.getAllVendors().collectList().block())
.stream().map(Vendor::getId)
.collect(Collectors.toList()).containsAll(Stream.of(1L, 2L,
3L).collect(Collectors.toList())));
}
@Test
void getAllVendorsEmpty() {
Collection<Vendor> vendors = Stream.builder().build().map(vendor -> (Vendor) vendor)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
Collections.emptySet(),
vendors,
Collections.emptySet());
assertEquals(0, mockUsersMicroserviceService.getAllVendors().count().block());
}
@Test
void getAllVendorsOne() {
Collection<Vendor> vendors = Stream.builder()
.add(new Vendor().id(1L).firstName("Vendor 1").lastName("The First")
.location(new Location().latitude(1f).longitude(1f))).build().map(vendor -> (Vendor) vendor)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
Collections.emptySet(),
vendors,
Collections.emptySet());
assertEquals(1, mockUsersMicroserviceService.getAllVendors().count().block());
assertTrue(Objects.requireNonNull(mockUsersMicroserviceService.getAllVendors().collectList().block())
.stream().map(Vendor::getId)
.collect(Collectors.toList()).containsAll(Stream.of(1L)
.collect(Collectors.toList())));
}
@Test
void getAllergens() {
Collection<Customer> customers = Stream.builder()
.add(new Customer().id(1L).allergens(List.of("egg", "yuppie")))
.add(new Customer().id(2L).allergens(List.of("prune")))
.build().map(c -> (Customer) c)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
customers,
Collections.emptySet(),
Collections.emptySet());
assertEquals(2, mockUsersMicroserviceService.getAllAllergies(1L).count().block());
assertTrue(new ArrayList<>(Objects.requireNonNull(
mockUsersMicroserviceService.getAllAllergies(1L).collectList().block()))
.containsAll(Stream.of("egg", "yuppie").collect(Collectors.toList())));
assertEquals(1, mockUsersMicroserviceService.getAllAllergies(2L).count().block());
}
@Test
void getAllergensEmpty() {
Collection<Customer> customers = Stream.builder()
.add(new Customer().id(1L).allergens(List.of("egg", "yuppie")))
.add(new Customer().id(2L).allergens(List.of()))
.build().map(c -> (Customer) c)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
customers,
Collections.emptySet(),
Collections.emptySet());
assertEquals(0, mockUsersMicroserviceService.getAllAllergies(2L).count().block());
}
@Test
void getAllergensNoSuchCustomer() {
Collection<Customer> customers = Stream.builder()
.add(new Customer().id(1L).allergens(List.of("egg", "yuppie")))
.add(new Customer().id(2L).allergens(List.of("brear")))
.build().map(c -> (Customer) c)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
customers,
Collections.emptySet(),
Collections.emptySet());
assertEquals(0, mockUsersMicroserviceService.getAllAllergies(3L).count().block());
}
@Test
void getRoleCustomerAlone() {
Collection<Customer> customers = Stream.builder()
.add(new Customer().id(1L).firstName("Customer 1").lastName("The First")
.homeLocation(new Location().latitude(1f).longitude(1f)))
.build().map(customer -> (Customer) customer)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
customers,
Collections.emptySet(),
Collections.emptySet());
assertTrue(mockUsersMicroserviceService.getRole(1L).isPresent());
assertEquals("customer", mockUsersMicroserviceService.getRole(1L).get());
}
@Test
void getRoleVendorAlone() {
Collection<Vendor> vendors = Stream.builder()
.add(new Vendor().id(1L).firstName("Vendor 1").lastName("The First")
.location(new Location().latitude(1f).longitude(1f)))
.build().map(vendor -> (Vendor) vendor)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
Collections.emptySet(),
vendors,
Collections.emptySet());
assertTrue(mockUsersMicroserviceService.getRole(1L).isPresent());
assertEquals("vendor", mockUsersMicroserviceService.getRole(1L).get());
}
@Test
void getRoleAdminAlone() {
Collection<User> admins = Stream.builder()
.add(new User().id(1L).firstName("Admin 1").lastName("The First"))
.build().map(user -> (User) user)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
Collections.emptySet(),
Collections.emptySet(),
admins);
assertTrue(mockUsersMicroserviceService.getRole(1L).isPresent());
assertEquals("admin", mockUsersMicroserviceService.getRole(1L).get());
}
@Test
void getRolePopulated() {
Collection<Vendor> vendors = Stream.builder()
.add(new Vendor().id(4L).firstName("Vendor 1").lastName("The First")
.location(new Location().latitude(1f).longitude(1f)))
.add(new Vendor().id(5L).firstName("Vendor 2").lastName("The Second")
.location(new Location().latitude(2f).longitude(2f)))
.add(new Vendor().id(6L).firstName("Vendor 3").lastName("The Third")
.location(new Location().latitude(3f).longitude(3f))).build().map(vendor -> (Vendor) vendor)
.collect(Collectors.toList());
Collection<Customer> customers = Stream.builder()
.add(new Customer().id(1L).firstName("Customer 1").lastName("The First")
.homeLocation(new Location().latitude(1f).longitude(1f)))
.add(new Customer().id(2L).firstName("Customer 2").lastName("The Second")
.homeLocation(new Location().latitude(2f).longitude(2f)))
.add(new Customer().id(3L).firstName("Customer 3").lastName("The Third")
.homeLocation(new Location().latitude(3f).longitude(3f)))
.build().map(customer -> (Customer) customer)
.collect(Collectors.toList());
Collection<User> admins = Stream.builder()
.add(new User().id(7L).firstName("Admin 1").lastName("The First"))
.add(new User().id(8L).firstName("Admin 2").lastName("The Second"))
.add(new User().id(9L).firstName("Admin 3").lastName("The Third"))
.build().map(user -> (User) user)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
customers,
vendors,
admins);
assertTrue(mockUsersMicroserviceService.getRole(1L).isPresent());
assertEquals("customer", mockUsersMicroserviceService.getRole(1L).get());
assertTrue(mockUsersMicroserviceService.getRole(4L).isPresent());
assertEquals("vendor", mockUsersMicroserviceService.getRole(4L).get());
assertTrue(mockUsersMicroserviceService.getRole(7L).isPresent());
assertEquals("admin", mockUsersMicroserviceService.getRole(7L).get());
}
@Test
void getRoleNotFound() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
Collections.emptySet(),
Collections.emptySet(),
Collections.emptySet());
assertTrue(mockUsersMicroserviceService.getRole(1L).isEmpty());
}
@Test
void getHomeAddressTest() {
Collection<Customer> customers = Stream.builder()
.add(new Customer().id(1L).firstName("Customer 1").lastName("The First")
.homeLocation(new Location().latitude(1f).longitude(2f)))
.build().map(customer -> (Customer) customer)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(
customers,
Collections.emptySet(),
Collections.emptySet());
assertTrue(mockUsersMicroserviceService.getHomeAddress(1L).isPresent());
assertEquals(1f, mockUsersMicroserviceService.getHomeAddress(1L).get().getLatitude());
assertEquals(2f, mockUsersMicroserviceService.getHomeAddress(1L).get().getLongitude());
}
}

View file

@ -1,336 +0,0 @@
package nl.tudelft.sem.yumyumnow.order.external;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import nl.tudelft.sem.yumyumnow.order.profiles.usersmicroservice.UserMicroserviceVendor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.order.model.Location;
import org.order.model.Vendor;
import org.springframework.web.reactive.function.client.WebClient;
@WireMockTest
class UsersMicroserviceServiceTest {
private transient UsersMicroserviceService usersMicroserviceService;
@BeforeEach
void setUp() {
WireMockServer wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().dynamicPort());
wireMockServer.start();
WireMock.configureFor(wireMockServer.port());
usersMicroserviceService = new UsersMicroserviceService(WebClient.builder());
usersMicroserviceService.setApiUrl(wireMockServer.baseUrl());
}
@Test
void getAllVendors() throws JsonProcessingException {
List<UserMicroserviceVendor> vendors = List.of(
new UserMicroserviceVendor().id(1L).firstName("Vendor1")
.location(new Location().latitude(0f).longitude(1f)),
new UserMicroserviceVendor().id(2L).firstName("Vendor2")
.location(new Location().latitude(2f).longitude(0f)),
new UserMicroserviceVendor().id(3L).firstName("Vendor3")
.location(new Location().latitude(2f).longitude(2f))
);
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(vendors);
WireMock.stubFor(WireMock.get("/vendors")
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertEquals(3, usersMicroserviceService.getAllVendors().count().block());
assertTrue(Objects.requireNonNull(usersMicroserviceService.getAllVendors().collectList().block())
.stream().map(Vendor::getId)
.collect(Collectors.toList()).containsAll(List.of(1L, 2L, 3L)));
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/vendors")));
}
@Test
void getAllVendorsEmpty() throws JsonProcessingException {
List<UserMicroserviceVendor> vendors = List.of();
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(vendors);
WireMock.stubFor(WireMock.get("/vendors")
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertEquals(0, usersMicroserviceService.getAllVendors().count().block());
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/vendors")));
}
@Test
void getAllVendorsOne() throws JsonProcessingException {
List<UserMicroserviceVendor> vendors = List.of(
new UserMicroserviceVendor().id(1L).firstName("Vendor1")
.location(new Location().latitude(0f).longitude(1f))
);
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(vendors);
WireMock.stubFor(WireMock.get("/vendors")
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertEquals(1, usersMicroserviceService.getAllVendors().count().block());
assertTrue(Objects.requireNonNull(usersMicroserviceService.getAllVendors().collectList().block())
.stream().map(Vendor::getId)
.collect(Collectors.toList()).contains(1L));
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/vendors")));
}
@Test
void getAllVendorsError() throws JsonProcessingException {
List<UserMicroserviceVendor> vendors = List.of(
new UserMicroserviceVendor().id(1L).firstName("Vendor1")
.location(new Location().latitude(0f).longitude(1f))
);
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(vendors);
WireMock.stubFor(WireMock.get("/vendors")
.willReturn(aResponse()
.withStatus(500)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertEquals(0, usersMicroserviceService.getAllVendors().count().block());
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/vendors")));
}
@Test
void testGetHomeAddressSuccess() {
Long userId = 123L;
Location expectedLocation = new Location().latitude(1f).longitude(2f);
WireMock.stubFor(WireMock.get(urlEqualTo("/customer/" + userId + "/home_address"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("{\"latitude\": 1.0, \"longitude\": 2.0}")));
assertTrue(usersMicroserviceService.getHomeAddress(userId).isPresent());
assertEquals(expectedLocation, usersMicroserviceService.getHomeAddress(userId).get());
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/customer/" + userId + "/home_address")));
}
@Test
void testGetHomeAddressClientError() {
Long userId = 456L;
WireMock.stubFor(WireMock.get(urlEqualTo("/customer/" + userId + "/home_address"))
.willReturn(aResponse().withStatus(404))); // Simulate a 404 Not Found error
Assertions.assertFalse(usersMicroserviceService.getHomeAddress(userId).isPresent());
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/customer/" + userId + "/home_address")));
}
@Test
void testGetHomeAddressServerError() {
Long userId = 789L;
WireMock.stubFor(WireMock.get(urlEqualTo("/customer/" + userId + "/home_address"))
.willReturn(aResponse().withStatus(500))); // Simulate a 500 Internal Server Error
Assertions.assertFalse(usersMicroserviceService.getHomeAddress(userId).isPresent());
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/customer/" + userId + "/home_address")));
}
@Test
void getAllVendors400Response() {
WireMock.stubFor(WireMock.get("/vendors")
.willReturn(WireMock.aResponse()
.withStatus(400)));
assertEquals(0, usersMicroserviceService.getAllVendors().count().block());
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/vendors")));
}
@Test
void getAllVendors500Response() {
WireMock.stubFor(WireMock.get("/vendors")
.willReturn(WireMock.aResponse()
.withStatus(500)));
assertEquals(0, usersMicroserviceService.getAllVendors().count().block());
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/vendors")));
}
@Test
void getRoleVendor() {
WireMock.stubFor(WireMock.get("/user/1/type")
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"type": "vendor"
}
""")));
assertTrue(usersMicroserviceService.getRole(1L).isPresent());
assertEquals("vendor", usersMicroserviceService.getRole(1L).get());
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/user/1/type")));
}
@Test
void getRoleCustomer() {
WireMock.stubFor(WireMock.get("/user/1/type")
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"type": "customer"
}
""")));
assertTrue(usersMicroserviceService.getRole(1L).isPresent());
assertEquals("customer", usersMicroserviceService.getRole(1L).get());
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/user/1/type")));
}
@Test
void getRoleAdmin() {
WireMock.stubFor(WireMock.get("/user/1/type")
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"type": "admin"
}
""")));
assertTrue(usersMicroserviceService.getRole(1L).isPresent());
assertEquals("admin", usersMicroserviceService.getRole(1L).get());
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/user/1/type")));
}
@Test
void getRole400Response() {
WireMock.stubFor(WireMock.get("/user/1/type")
.willReturn(WireMock.aResponse()
.withStatus(400)));
assertTrue(usersMicroserviceService.getRole(1L).isEmpty());
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/user/1/type")));
}
@Test
void getRole500Response() {
WireMock.stubFor(WireMock.get("/user/1/type")
.willReturn(WireMock.aResponse()
.withStatus(500)));
assertTrue(usersMicroserviceService.getRole(1L).isEmpty());
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/user/1/type")));
}
@Test
void getAllergiesOne() throws Exception {
List<String> allergies = List.of("Peenut.");
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(allergies);
WireMock.stubFor(WireMock.get("/customer/1/allergies")
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertEquals(1, usersMicroserviceService.getAllAllergies(1L).count().block());
assertTrue(new ArrayList<>(Objects.requireNonNull(usersMicroserviceService.getAllAllergies(1L)
.collectList().block())).contains("Peenut."));
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/customer/1/allergies")));
}
@Test
void getAllergies() throws Exception {
List<String> allergies = List.of("Pea nut", "Do nut");
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(allergies);
WireMock.stubFor(WireMock.get("/customer/1/allergies")
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertEquals(2, usersMicroserviceService.getAllAllergies(1L).count().block());
assertTrue(new ArrayList<>(Objects.requireNonNull(usersMicroserviceService.getAllAllergies(1L)
.collectList().block())).contains("Pea nut"));
assertTrue(new ArrayList<>(Objects.requireNonNull(usersMicroserviceService.getAllAllergies(1L)
.collectList().block())).contains("Do nut"));
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/customer/1/allergies")));
}
@Test
void getAllergiesZero() throws Exception {
List<String> allergies = List.of();
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(allergies);
WireMock.stubFor(WireMock.get("/customer/1/allergies")
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertEquals(0, usersMicroserviceService.getAllAllergies(1L).count().block());
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/customer/1/allergies")));
}
@Test
void getAllergiesError() throws Exception {
List<String> allergies = List.of("Pea nut", "Do nut");
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(allergies);
WireMock.stubFor(WireMock.get("/customer/1/allergies")
.willReturn(WireMock.aResponse()
.withStatus(500)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertEquals(0, usersMicroserviceService.getAllAllergies(1L).count().block());
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/customer/1/allergies")));
}
}

View file

@ -0,0 +1,34 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.mock;
import static org.assertj.core.api.Assertions.assertThat;
import nl.tudelft.sem.yumyumnow.order.external.MockUsersMicroserviceService;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroservice;
import org.junit.jupiter.api.Test;
class GetAllVendorsTest extends MockUsersMicroserviceServiceTest {
@Test
void getAllVendorsAllThere() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, getManyVendors(), null);
assertThat(mockUsersMicroserviceService.getAllVendors().count().block()).isEqualTo(3);
assertThat(mockUsersMicroserviceService.getAllVendors().collectList().block()).containsAnyElementsOf(
getManyVendors());
}
@Test
void getAllVendorsEmpty() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, null, null);
assertThat(mockUsersMicroserviceService.getAllVendors().count().block()).isEqualTo(0);
}
@Test
void getAllVendorsOne() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, getAloneVendor(), null);
assertThat(mockUsersMicroserviceService.getAllVendors().count().block()).isEqualTo(1);
assertThat(mockUsersMicroserviceService.getAllVendors().collectList().block()).containsExactlyElementsOf(
getAloneVendor());
}
}

View file

@ -0,0 +1,63 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.mock;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import nl.tudelft.sem.yumyumnow.order.external.MockUsersMicroserviceService;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroservice;
import org.junit.jupiter.api.Test;
import org.order.model.Customer;
/**
* Tests the getAllergens method of the mock users-microservice.
*/
public class GetAllergensTest extends MockUsersMicroserviceServiceTest {
@Test
void getAllergens() {
Collection<Customer> customers = Stream.builder()
.add(new Customer().id(1L).allergens(List.of("egg", "yuppie")))
.add(new Customer().id(2L).allergens(List.of("prune")))
.build()
.map(c -> (Customer) c)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(customers, Collections.emptySet(), Collections.emptySet());
assertThat(mockUsersMicroserviceService.getAllAllergies(1L).count().block()).isEqualTo(2);
assertThat(mockUsersMicroserviceService.getAllAllergies(1L).collectList().block()).containsExactlyInAnyOrder(
"egg", "yuppie");
assertThat(mockUsersMicroserviceService.getAllAllergies(2L).count().block()).isEqualTo(1);
}
@Test
void getAllergensEmpty() {
Collection<Customer> customers = Stream.builder()
.add(new Customer().id(1L).allergens(List.of("egg", "yuppie")))
.add(new Customer().id(2L).allergens(List.of()))
.build()
.map(c -> (Customer) c)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(customers, Collections.emptySet(), Collections.emptySet());
assertThat(mockUsersMicroserviceService.getAllAllergies(2L).count().block()).isEqualTo(0);
}
@Test
void getAllergensNoSuchCustomer() {
Collection<Customer> customers = Stream.builder()
.add(new Customer().id(1L).allergens(List.of("egg", "yuppie")))
.add(new Customer().id(2L).allergens(List.of("brear")))
.build()
.map(c -> (Customer) c)
.collect(Collectors.toList());
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(customers, Collections.emptySet(), Collections.emptySet());
assertThat(mockUsersMicroserviceService.getAllAllergies(3L).count().block()).isEqualTo(0);
}
}

View file

@ -0,0 +1,60 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.mock;
import static org.assertj.core.api.Assertions.assertThat;
import nl.tudelft.sem.yumyumnow.order.external.MockUsersMicroserviceService;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroservice;
import org.junit.jupiter.api.Test;
class GetEmailTest extends MockUsersMicroserviceServiceTest {
@Test
void getEmailCustomerAlone() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(getAloneCustomer(), null, null);
assertThat(mockUsersMicroserviceService.getEmail(getCustomerIds()[0])).hasValue(getCustomerEmails()[0]);
}
@Test
void getEmailCustomerPopulated() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(getManyCustomers(), null, null);
assertThat(mockUsersMicroserviceService.getEmail(getCustomerIds()[0])).hasValue(getCustomerEmails()[0]);
assertThat(mockUsersMicroserviceService.getEmail(getCustomerIds()[1])).hasValue(getCustomerEmails()[1]);
assertThat(mockUsersMicroserviceService.getEmail(getCustomerIds()[2])).hasValue(getCustomerEmails()[2]);
}
@Test
void getEmailNoUsers() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, null, null);
assertThat(mockUsersMicroserviceService.getEmail(1L)).isEmpty();
}
@Test
void getEmailNoCustomers() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(null, getManyVendors(), getManyAdmins());
assertThat(mockUsersMicroserviceService.getEmail(getCustomerIds()[0])).isEmpty();
assertThat(mockUsersMicroserviceService.getEmail(getVendorIds()[0])).isEmpty();
assertThat(mockUsersMicroserviceService.getEmail(getAdminIds()[0])).isEmpty();
}
@Test
void getEmailAllPopulated() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(getManyCustomers(), getManyVendors(), getManyAdmins());
assertThat(mockUsersMicroserviceService.getEmail(getCustomerIds()[0])).hasValue(getCustomerEmails()[0]);
assertThat(mockUsersMicroserviceService.getEmail(getCustomerIds()[1])).hasValue(getCustomerEmails()[1]);
assertThat(mockUsersMicroserviceService.getEmail(getCustomerIds()[2])).hasValue(getCustomerEmails()[2]);
assertThat(mockUsersMicroserviceService.getEmail(getVendorIds()[0])).isEmpty();
assertThat(mockUsersMicroserviceService.getEmail(getVendorIds()[1])).isEmpty();
assertThat(mockUsersMicroserviceService.getEmail(getVendorIds()[2])).isEmpty();
assertThat(mockUsersMicroserviceService.getEmail(getAdminIds()[0])).isEmpty();
assertThat(mockUsersMicroserviceService.getEmail(getAdminIds()[1])).isEmpty();
assertThat(mockUsersMicroserviceService.getEmail(getAdminIds()[2])).isEmpty();
}
}

View file

@ -0,0 +1,45 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.mock;
import static org.assertj.core.api.Assertions.assertThat;
import nl.tudelft.sem.yumyumnow.order.external.MockUsersMicroserviceService;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroservice;
import org.junit.jupiter.api.Test;
class GetHomeAddressTest extends MockUsersMicroserviceServiceTest {
@Test
void getHomeAddressPopulated() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(getManyCustomers(), getManyVendors(), getManyAdmins());
assertThat(mockUsersMicroserviceService.getHomeAddress(getCustomerIds()[0])).hasValue(
getCustomerLocations()[0]);
assertThat(mockUsersMicroserviceService.getHomeAddress(getCustomerIds()[1])).hasValue(
getCustomerLocations()[1]);
assertThat(mockUsersMicroserviceService.getHomeAddress(getCustomerIds()[2])).hasValue(
getCustomerLocations()[2]);
assertThat(mockUsersMicroserviceService.getHomeAddress(getVendorIds()[0])).isEmpty();
assertThat(mockUsersMicroserviceService.getHomeAddress(getVendorIds()[1])).isEmpty();
assertThat(mockUsersMicroserviceService.getHomeAddress(getVendorIds()[2])).isEmpty();
assertThat(mockUsersMicroserviceService.getHomeAddress(getAdminIds()[0])).isEmpty();
assertThat(mockUsersMicroserviceService.getHomeAddress(getAdminIds()[1])).isEmpty();
assertThat(mockUsersMicroserviceService.getHomeAddress(getAdminIds()[2])).isEmpty();
}
@Test
void getHomeAddressNoUsers() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, null, null);
assertThat(mockUsersMicroserviceService.getHomeAddress(1L)).isEmpty();
}
@Test
void getHomeAddressSetNoCustomers() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(null, getManyVendors(), getManyAdmins());
assertThat(mockUsersMicroserviceService.getHomeAddress(getCustomerIds()[0])).isEmpty();
assertThat(mockUsersMicroserviceService.getHomeAddress(getVendorIds()[0])).isEmpty();
assertThat(mockUsersMicroserviceService.getHomeAddress(getAdminIds()[0])).isEmpty();
}
}

View file

@ -0,0 +1,53 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.mock;
import static org.assertj.core.api.Assertions.assertThat;
import nl.tudelft.sem.yumyumnow.order.external.MockUsersMicroserviceService;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroservice;
import org.junit.jupiter.api.Test;
class GetRoleTest extends MockUsersMicroserviceServiceTest {
@Test
void getRoleCustomerAlone() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(getAloneCustomer(), null, null);
assertThat(mockUsersMicroserviceService.getRole(getCustomerIds()[0])).hasValue("customer");
}
@Test
void getRoleVendorAlone() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, getAloneVendor(), null);
assertThat(mockUsersMicroserviceService.getRole(getVendorIds()[0])).hasValue("vendor");
}
@Test
void getRoleAdminAlone() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, null, getAloneAdmin());
assertThat(mockUsersMicroserviceService.getRole(getAdminIds()[0])).hasValue("admin");
}
@Test
void getRolePopulated() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(getManyCustomers(), getManyVendors(), getManyAdmins());
assertThat(mockUsersMicroserviceService.getRole(getCustomerIds()[0])).contains("customer");
assertThat(mockUsersMicroserviceService.getRole(getCustomerIds()[1])).contains("customer");
assertThat(mockUsersMicroserviceService.getRole(getCustomerIds()[2])).contains("customer");
assertThat(mockUsersMicroserviceService.getRole(getVendorIds()[0])).contains("vendor");
assertThat(mockUsersMicroserviceService.getRole(getVendorIds()[1])).contains("vendor");
assertThat(mockUsersMicroserviceService.getRole(getVendorIds()[2])).contains("vendor");
assertThat(mockUsersMicroserviceService.getRole(getAdminIds()[0])).contains("admin");
assertThat(mockUsersMicroserviceService.getRole(getAdminIds()[1])).contains("admin");
assertThat(mockUsersMicroserviceService.getRole(getAdminIds()[2])).contains("admin");
}
@Test
void getRoleNotFound() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, null, null);
assertThat(mockUsersMicroserviceService.getRole(1L)).isEmpty();
}
}

View file

@ -0,0 +1,141 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.mock;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Optional;
import nl.tudelft.sem.yumyumnow.order.external.MockUsersMicroserviceService;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroservice;
import org.junit.jupiter.api.Test;
import org.order.model.User;
class GetUserTest extends MockUsersMicroserviceServiceTest {
@Test
void getUserCustomerAlone() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(getAloneCustomer(), null, null);
Optional<User> u = mockUsersMicroserviceService.getUser(getCustomerIds()[0]);
assertThat(u).map(User::getFirstName).hasValue("Customer 1");
assertThat(u).map(User::getLastName).hasValue("The First");
}
@Test
void getUserCustomerMany() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(getManyCustomers(), null, null);
Optional<User> u1 = mockUsersMicroserviceService.getUser(getCustomerIds()[0]);
Optional<User> u2 = mockUsersMicroserviceService.getUser(getCustomerIds()[1]);
Optional<User> u3 = mockUsersMicroserviceService.getUser(getCustomerIds()[2]);
assertThat(u1).map(User::getFirstName).hasValue("Customer 1");
assertThat(u2).map(User::getFirstName).hasValue("Customer 2");
assertThat(u3).map(User::getFirstName).hasValue("Customer 3");
assertThat(u1).map(User::getLastName).hasValue("The First");
assertThat(u2).map(User::getLastName).hasValue("The Second");
assertThat(u3).map(User::getLastName).hasValue("The Third");
}
@Test
void getUserVendorAlone() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, getAloneVendor(), null);
Optional<User> u = mockUsersMicroserviceService.getUser(getVendorIds()[0]);
assertThat(u).map(User::getFirstName).hasValue("Vendor 1");
assertThat(u).map(User::getLastName).hasValue("The First");
}
@Test
void getUserVendorMany() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, getManyVendors(), null);
Optional<User> u1 = mockUsersMicroserviceService.getUser(getVendorIds()[0]);
Optional<User> u2 = mockUsersMicroserviceService.getUser(getVendorIds()[1]);
Optional<User> u3 = mockUsersMicroserviceService.getUser(getVendorIds()[2]);
assertThat(u1).map(User::getFirstName).hasValue("Vendor 1");
assertThat(u2).map(User::getFirstName).hasValue("Vendor 2");
assertThat(u3).map(User::getFirstName).hasValue("Vendor 3");
assertThat(u1).map(User::getLastName).hasValue("The First");
assertThat(u2).map(User::getLastName).hasValue("The Second");
assertThat(u3).map(User::getLastName).hasValue("The Third");
}
@Test
void getUserAdminAlone() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, null, getAloneAdmin());
Optional<User> u = mockUsersMicroserviceService.getUser(getAdminIds()[0]);
assertThat(u).map(User::getFirstName).hasValue("Admin 1");
assertThat(u).map(User::getLastName).hasValue("The First");
}
@Test
void getUserAdminMany() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, null, getManyAdmins());
Optional<User> u1 = mockUsersMicroserviceService.getUser(getAdminIds()[0]);
Optional<User> u2 = mockUsersMicroserviceService.getUser(getAdminIds()[1]);
Optional<User> u3 = mockUsersMicroserviceService.getUser(getAdminIds()[2]);
assertThat(u1).map(User::getFirstName).hasValue("Admin 1");
assertThat(u2).map(User::getFirstName).hasValue("Admin 2");
assertThat(u3).map(User::getFirstName).hasValue("Admin 3");
assertThat(u1).map(User::getLastName).hasValue("The First");
assertThat(u2).map(User::getLastName).hasValue("The Second");
assertThat(u3).map(User::getLastName).hasValue("The Third");
}
@Test
void getUserNotFound() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, null, null);
assertThat(mockUsersMicroserviceService.getUser(1L)).isEmpty();
}
@Test
void getUserPopulated() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(getManyCustomers(), getManyVendors(), getManyAdmins());
Optional<User> u1 = mockUsersMicroserviceService.getUser(getCustomerIds()[0]);
Optional<User> u2 = mockUsersMicroserviceService.getUser(getCustomerIds()[1]);
Optional<User> u3 = mockUsersMicroserviceService.getUser(getCustomerIds()[2]);
Optional<User> u4 = mockUsersMicroserviceService.getUser(getVendorIds()[0]);
Optional<User> u5 = mockUsersMicroserviceService.getUser(getVendorIds()[1]);
Optional<User> u6 = mockUsersMicroserviceService.getUser(getVendorIds()[2]);
Optional<User> u7 = mockUsersMicroserviceService.getUser(getAdminIds()[0]);
Optional<User> u8 = mockUsersMicroserviceService.getUser(getAdminIds()[1]);
Optional<User> u9 = mockUsersMicroserviceService.getUser(getAdminIds()[2]);
assertThat(u1).map(User::getFirstName).hasValue("Customer 1");
assertThat(u2).map(User::getFirstName).hasValue("Customer 2");
assertThat(u3).map(User::getFirstName).hasValue("Customer 3");
assertThat(u4).map(User::getFirstName).hasValue("Vendor 1");
assertThat(u5).map(User::getFirstName).hasValue("Vendor 2");
assertThat(u6).map(User::getFirstName).hasValue("Vendor 3");
assertThat(u7).map(User::getFirstName).hasValue("Admin 1");
assertThat(u8).map(User::getFirstName).hasValue("Admin 2");
assertThat(u9).map(User::getFirstName).hasValue("Admin 3");
assertThat(u1).map(User::getLastName).hasValue("The First");
assertThat(u2).map(User::getLastName).hasValue("The Second");
assertThat(u3).map(User::getLastName).hasValue("The Third");
assertThat(u4).map(User::getLastName).hasValue("The First");
assertThat(u5).map(User::getLastName).hasValue("The Second");
assertThat(u6).map(User::getLastName).hasValue("The Third");
assertThat(u7).map(User::getLastName).hasValue("The First");
assertThat(u8).map(User::getLastName).hasValue("The Second");
assertThat(u9).map(User::getLastName).hasValue("The Third");
}
@Test
void getUserNotFoundPopulated() {
UsersMicroservice mockUsersMicroserviceService =
new MockUsersMicroserviceService(getManyCustomers(), getManyVendors(), getManyAdmins());
assertThat(mockUsersMicroserviceService.getUser(-1L)).isEmpty();
}
}

View file

@ -0,0 +1,112 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.mock;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Set;
import nl.tudelft.sem.yumyumnow.order.external.MockUsersMicroserviceService;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroservice;
import org.junit.jupiter.api.Test;
import org.order.model.Customer;
import org.order.model.Location;
import org.order.model.User;
import org.order.model.Vendor;
class MockUsersMicroserviceServiceTest {
private final Long[] customerIds = {1L, 2L, 3L};
private final Long[] vendorIds = {4L, 5L, 6L};
private final Long[] adminIds = {7L, 8L, 9L};
private final String[] customerEmails = {"1@mail.com", "2@mail.com", "3@mail.com"};
private final Location[] customerLocations = {
new Location().latitude(1.0f).longitude(1.0f),
new Location().latitude(2.0f).longitude(2.0f),
new Location().latitude(3.0f).longitude(3.0f)
};
private final Set<Customer> aloneCustomer = Set.of(new Customer().id(customerIds[0])
.firstName("Customer 1")
.lastName("The First")
.emailAddress(customerEmails[0])
.homeLocation(customerLocations[0]));
private final Set<Customer> manyCustomers = Set.of(aloneCustomer.iterator().next(),
new Customer().id(customerIds[1])
.firstName("Customer 2")
.lastName("The Second")
.emailAddress(customerEmails[1])
.homeLocation(customerLocations[1]), new Customer().id(customerIds[2])
.firstName("Customer 3")
.lastName("The Third")
.emailAddress(customerEmails[2])
.homeLocation(customerLocations[2]));
private final Set<Vendor> aloneVendor = Set.of(new Vendor().id(vendorIds[0])
.firstName("Vendor 1")
.lastName("The First")
.location(new Location().latitude(1.0f).longitude(1.0f))
.radius(1.0f));
private final Set<Vendor> manyVendors = Set.of(aloneVendor.iterator().next(), new Vendor().id(vendorIds[1])
.firstName("Vendor 2")
.lastName("The Second")
.location(new Location().latitude(2.0f).longitude(2.0f))
.radius(2.0f), new Vendor().id(vendorIds[2])
.firstName("Vendor 3")
.lastName("The Third")
.location(new Location().latitude(3.0f).longitude(3.0f))
.radius(3.0f));
private final Set<User> aloneAdmin = Set.of(new User().id(adminIds[0]).firstName("Admin 1").lastName("The First"));
private final Set<User> manyAdmins =
Set.of(aloneAdmin.iterator().next(), new User().id(adminIds[1]).firstName("Admin 2").lastName("The Second"),
new User().id(adminIds[2]).firstName("Admin 3").lastName("The Third"));
@Test
void nullInitialization() {
UsersMicroservice mockUsersMicroserviceService = new MockUsersMicroserviceService(null, null, null);
assertThat(mockUsersMicroserviceService.getAllVendors().count().block()).isEqualTo(0);
assertThat(mockUsersMicroserviceService.getRole(1L)).isEmpty();
assertThat(mockUsersMicroserviceService.getUser(1L)).isEmpty();
assertThat(mockUsersMicroserviceService.getEmail(1L)).isEmpty();
assertThat(mockUsersMicroserviceService.getHomeAddress(1L)).isEmpty();
}
protected Long[] getCustomerIds() {
return customerIds;
}
protected Long[] getVendorIds() {
return vendorIds;
}
protected Long[] getAdminIds() {
return adminIds;
}
protected String[] getCustomerEmails() {
return customerEmails;
}
protected org.order.model.Location[] getCustomerLocations() {
return customerLocations;
}
protected java.util.Set<org.order.model.Customer> getAloneCustomer() {
return aloneCustomer;
}
protected java.util.Set<org.order.model.Customer> getManyCustomers() {
return manyCustomers;
}
protected java.util.Set<org.order.model.Vendor> getAloneVendor() {
return aloneVendor;
}
protected java.util.Set<org.order.model.Vendor> getManyVendors() {
return manyVendors;
}
protected java.util.Set<org.order.model.User> getAloneAdmin() {
return aloneAdmin;
}
protected java.util.Set<org.order.model.User> getManyAdmins() {
return manyAdmins;
}
}

View file

@ -0,0 +1,75 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.service;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.github.tomakehurst.wiremock.client.WireMock;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.order.model.Vendor;
class GetAllVendorsTest extends UsersMicroserviceServiceTest {
@Test
void getAllVendorsEmpty() throws JsonProcessingException {
String jsonBody = objectMapper.writeValueAsString(List.of());
WireMock.stubFor(WireMock.get("/vendors")
.willReturn(aResponse().withStatus(HttpServletResponse.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertThat(getUsersMicroserviceService().getAllVendors().count().block()).isEqualTo(0);
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/vendors")));
}
@Test
void getAllVendorsOne() throws JsonProcessingException {
String jsonBody = objectMapper.writeValueAsString(getAloneVendor());
WireMock.stubFor(WireMock.get("/vendors")
.willReturn(aResponse().withStatus(HttpServletResponse.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertThat(getUsersMicroserviceService().getAllVendors().count().block()).isEqualTo(1);
assertThat(getUsersMicroserviceService().getAllVendors().collectList().block()).map(Vendor::getId)
.containsExactly(getIds()[0]);
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/vendors")));
}
@Test
void getAllVendorsMany() throws JsonProcessingException {
String jsonBody = objectMapper.writeValueAsString(getManyVendors());
WireMock.stubFor(WireMock.get("/vendors")
.willReturn(aResponse().withStatus(HttpServletResponse.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertThat(getUsersMicroserviceService().getAllVendors().count().block()).isEqualTo(3);
assertThat(getUsersMicroserviceService().getAllVendors().collectList().block()).map(Vendor::getId)
.containsExactlyInAnyOrderElementsOf(Arrays.asList(getIds()));
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/vendors")));
}
@Test
void getAllVendors400Response() {
WireMock.stubFor(WireMock.get("/vendors").willReturn(aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)));
assertThat(getUsersMicroserviceService().getAllVendors().count().block()).isEqualTo(0);
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/vendors")));
}
@Test
void getAllVendors500Response() {
WireMock.stubFor(
WireMock.get("/vendors").willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
assertThat(getUsersMicroserviceService().getAllVendors().count().block()).isEqualTo(0);
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/vendors")));
}
}

View file

@ -0,0 +1,86 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.service;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.client.WireMock;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
/**
* Tests the getAllVendors method from the UsersMicroserviceService class.
*/
public class GetAllergensTest extends UsersMicroserviceServiceTest {
@Test
void getAllergiesOne() throws Exception {
List<String> allergies = List.of("Peenut.");
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(allergies);
WireMock.stubFor(WireMock.get("/customer/1/allergies")
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertThat(getUsersMicroserviceService().getAllAllergies(1L).count().block()).isEqualTo(1);
assertThat(getUsersMicroserviceService().getAllAllergies(1L).collectList().block()).containsExactly("Peenut.");
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/customer/1/allergies")));
}
@Test
void getAllergies() throws Exception {
List<String> allergies = List.of("Pea nut", "Do nut");
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(allergies);
WireMock.stubFor(WireMock.get("/customer/1/allergies")
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertThat(getUsersMicroserviceService().getAllAllergies(1L).count().block()).isEqualTo(2);
assertThat(getUsersMicroserviceService().getAllAllergies(1L).collectList().block()).containsExactly("Pea nut",
"Do nut");
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/customer/1/allergies")));
}
@Test
void getAllergiesZero() throws Exception {
List<String> allergies = List.of();
ObjectMapper objectMapper = new ObjectMapper();
String jsonBody = objectMapper.writeValueAsString(allergies);
WireMock.stubFor(WireMock.get("/customer/1/allergies")
.willReturn(WireMock.aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertThat(getUsersMicroserviceService().getAllAllergies(1L).count().block()).isEqualTo(0);
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/customer/1/allergies")));
}
@Test
void getAllergies400Response() {
WireMock.stubFor(WireMock.get("/customer/1/allergies")
.willReturn(WireMock.aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)));
assertThat(getUsersMicroserviceService().getAllAllergies(1L).count().block()).isEqualTo(0);
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/customer/1/allergies")));
}
@Test
void getAllergies500Response() {
WireMock.stubFor(WireMock.get("/customer/1/allergies")
.willReturn(WireMock.aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
assertThat(getUsersMicroserviceService().getAllAllergies(1L).count().block()).isEqualTo(0);
WireMock.verify(WireMock.getRequestedFor(WireMock.urlEqualTo("/customer/1/allergies")));
}
}

View file

@ -0,0 +1,69 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.service;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.tomakehurst.wiremock.client.WireMock;
import javax.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
class GetEmailTest extends UsersMicroserviceServiceTest {
@Test
void getEmail() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/customer/%d".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"id": 1,
"firstName": "John",
"lastName": "James",
"email": "john@mail.com"
}
""")));
assertThat(getUsersMicroserviceService().getEmail(userId)).hasValue("john@mail.com");
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/customer/%d".formatted(userId))));
}
@Test
void getEmail400Response() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/customer/%d".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_BAD_REQUEST)));
assertThat(getUsersMicroserviceService().getEmail(userId)).isEmpty();
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/customer/%d".formatted(userId))));
}
@Test
void getEmail500Response() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/customer/%d".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
assertThat(getUsersMicroserviceService().getEmail(userId)).isEmpty();
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/customer/%d".formatted(userId))));
}
@Test
void getEmailEmpty() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/customer/%d".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"id": 1,
"firstName": "John",
"lastName": "James",
"email": ""
}
""")));
assertThat(getUsersMicroserviceService().getEmail(userId)).isEmpty();
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/customer/%d".formatted(userId))));
}
}

View file

@ -0,0 +1,43 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.service;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.tomakehurst.wiremock.client.WireMock;
import javax.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
class GetHomeAddressTest extends UsersMicroserviceServiceTest {
@Test
void testGetHomeAddressSuccess() {
Long userId = 1L;
WireMock.stubFor(WireMock.get(urlEqualTo("/customer/%d/home_address".formatted(userId)))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody("{\"latitude\": 1.0, \"longitude\": 2.0}")));
assertThat(getUsersMicroserviceService().getHomeAddress(userId)).hasValue(getLocations()[1]);
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/customer/%d/home_address".formatted(userId))));
}
@Test
void testGetHomeAddressClientError() {
Long userId = 1L;
WireMock.stubFor(WireMock.get(urlEqualTo("/customer/%d/home_address".formatted(userId)))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)));
assertThat(getUsersMicroserviceService().getHomeAddress(userId)).isEmpty();
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/customer/%d/home_address".formatted(userId))));
}
@Test
void testGetHomeAddressServerError() {
Long userId = 1L;
WireMock.stubFor(WireMock.get(urlEqualTo("/customer/%d/home_address".formatted(userId)))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
assertThat(getUsersMicroserviceService().getHomeAddress(userId)).isEmpty();
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/customer/%d/home_address".formatted(userId))));
}
}

View file

@ -0,0 +1,80 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.service;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.github.tomakehurst.wiremock.client.WireMock;
import javax.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
class GetRoleTest extends UsersMicroserviceServiceTest {
@Test
void getRoleVendor() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/user/%d/type".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"type": "vendor"
}
""")));
assertThat(getUsersMicroserviceService().getRole(userId)).hasValue("vendor");
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/user/%d/type".formatted(userId))));
}
@Test
void getRoleCustomer() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/user/%d/type".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"type": "customer"
}
""")));
assertThat(getUsersMicroserviceService().getRole(userId)).hasValue("customer");
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/user/%d/type".formatted(userId))));
}
@Test
void getRoleAdmin() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/user/%d/type".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody("""
{
"type": "admin"
}
""")));
assertThat(getUsersMicroserviceService().getRole(userId)).hasValue("admin");
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/user/%d/type".formatted(userId))));
}
@Test
void getRole400Response() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/user/%d/type".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_BAD_REQUEST)));
assertTrue(getUsersMicroserviceService().getRole(userId).isEmpty());
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/user/%d/type".formatted(userId))));
}
@Test
void getRole500Response() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/user/%d/type".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
assertTrue(getUsersMicroserviceService().getRole(userId).isEmpty());
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/user/%d/type".formatted(userId))));
}
}

View file

@ -0,0 +1,64 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.service;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.assertj.core.api.Assertions.assertThat;
import com.github.tomakehurst.wiremock.client.WireMock;
import javax.servlet.http.HttpServletResponse;
import org.junit.jupiter.api.Test;
import org.order.model.User;
class GetUserTest extends UsersMicroserviceServiceTest {
@Test
void getUserEmpty() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/user/%d".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)
.withHeader("Content-Type", "application/json")));
assertThat(getUsersMicroserviceService().getUser(userId)).isEmpty();
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/user/%d".formatted(userId))));
}
@Test
void getUser() {
Long userId = 1L;
String jsonBody = """
{
"id": %d,
"firstName": "John",
"lastName": "James",
"email": "john@gmail.com"
}""".formatted(userId);
WireMock.stubFor(WireMock.get("/user/%d".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_OK)
.withHeader("Content-Type", "application/json")
.withBody(jsonBody)));
assertThat(getUsersMicroserviceService().getUser(userId)).hasValue(
new User().id(userId).firstName("John").lastName("James"));
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/user/%d".formatted(userId))));
}
@Test
void getUser400Response() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/user/%d".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_NOT_FOUND)));
assertThat(getUsersMicroserviceService().getUser(userId)).isEmpty();
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/user/%d".formatted(userId))));
}
@Test
void getUser500Response() {
Long userId = 1L;
WireMock.stubFor(WireMock.get("/user/%d".formatted(userId))
.willReturn(aResponse().withStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)));
assertThat(getUsersMicroserviceService().getUser(userId)).isEmpty();
WireMock.verify(WireMock.getRequestedFor(urlEqualTo("/user/%d".formatted(userId))));
}
}

View file

@ -0,0 +1,67 @@
package nl.tudelft.sem.yumyumnow.order.external.usersmicroservice.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.core.WireMockConfiguration;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import java.util.Set;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroserviceService;
import nl.tudelft.sem.yumyumnow.order.profiles.usersmicroservice.UserMicroserviceVendor;
import org.junit.jupiter.api.BeforeEach;
import org.order.model.Location;
import org.springframework.web.reactive.function.client.WebClient;
@WireMockTest
class UsersMicroserviceServiceTest {
protected static final ObjectMapper objectMapper = new ObjectMapper();
private final Long[] ids = {1L, 2L, 3L};
private final String[] names = {"name1", "name1", "name3"};
private final Location[] locations = {
new Location().latitude(0.0f).longitude(0.0f),
new Location().latitude(1.0f).longitude(2.0f),
new Location().latitude(2.0f).longitude(3.0f)
};
private final Set<UserMicroserviceVendor> aloneVendor =
Set.of(new UserMicroserviceVendor().id(ids[0]).firstName(names[0]).location(locations[0]));
private final Set<UserMicroserviceVendor> manyVendors = Set.of(aloneVendor.iterator().next(),
new UserMicroserviceVendor().id(ids[1]).firstName(names[1]).location(locations[1]),
new UserMicroserviceVendor().id(ids[2]).firstName(names[2]).location(locations[2]));
private UsersMicroserviceService usersMicroserviceService;
@BeforeEach
void setUp() {
WireMockServer wireMockServer = new WireMockServer(WireMockConfiguration.wireMockConfig().dynamicPort());
wireMockServer.start();
WireMock.configureFor(wireMockServer.port());
usersMicroserviceService = new UsersMicroserviceService(WebClient.builder());
usersMicroserviceService.setApiUrl(wireMockServer.baseUrl());
}
protected Long[] getIds() {
return ids;
}
protected String[] getNames() {
return names;
}
protected Location[] getLocations() {
return locations;
}
protected Set<UserMicroserviceVendor> getAloneVendor() {
return aloneVendor;
}
protected Set<UserMicroserviceVendor> getManyVendors() {
return manyVendors;
}
protected UsersMicroserviceService getUsersMicroserviceService() {
return usersMicroserviceService;
}
}

View file

@ -0,0 +1,143 @@
package nl.tudelft.sem.yumyumnow.order.integration.notification;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.order.model.Order;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.test.context.TestPropertySource;
@SuppressWarnings("SpringBootApplicationProperties")
@TestPropertySource(properties = "notification.config=classpath:notification/all-statuses.yml")
class AllStatusesTest extends EmailServiceIntegrationTest {
@Test
void testSendMail_CreateOrder() throws Exception {
final String jsonToSend =
"{\"vendorId\": %d, \"dishes\": [1,2], \"dishRequirements\": [\"\",\"\"], \"price\": 20}".formatted(
getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getCustomerIds()[0])
.content(jsonToSend));
final String to = getCustomerEmails()[0];
final String subject = "Order %d is pending".formatted(1);
final String body = "Dear %s, Your order %d is pending. Thank you for your order. - YumYumNow".formatted(
getCustomerNames()[0], 1);
final SimpleMailMessage expectedMessage = new SimpleMailMessage();
expectedMessage.setTo(to);
expectedMessage.setSubject(subject);
expectedMessage.setText(body);
verify(getMailSender()).send(expectedMessage);
}
@Test
void testSendMail_CreateOrder_noEmailAddress() throws Exception {
when(getUsersMicroservice().getEmail(anyLong())).thenReturn(Optional.empty());
final String jsonToSend =
"{\"vendorId\": %d, \"dishes\": [1,2], \"dishRequirements\": [\"\",\"\"], \"price\": 20}".formatted(
getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getCustomerIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(put("/order/%d/status".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
final String to = getCustomerEmails()[0];
final String subject = "Order %d is accepted".formatted(order.getId());
final String body = "Dear %s, Your order %d is accepted. Thank you for your order. - YumYumNow".formatted(
getCustomerNames()[0], order.getId());
final SimpleMailMessage expectedMessage = new SimpleMailMessage();
expectedMessage.setTo(to);
expectedMessage.setSubject(subject);
expectedMessage.setText(body);
verify(getMailSender()).send(expectedMessage);
}
@Test
void testSendMail_UpdateOrderStatus_noEmailAddress() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
when(getUsersMicroservice().getEmail(anyLong())).thenReturn(Optional.empty());
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_noOrder() throws Exception {
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(1)).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderByAdmin() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getAdminIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_CreateOrderByAdmin() throws Exception {
final String jsonToSend = """
{
"customerId": %d,
"vendorId": %d,
"dishes": [1,2],
"dishRequirements": ["",""],
"price": 20
}""".formatted(getCustomerIds()[0], getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getAdminIds()[0])
.content(jsonToSend));
final String to = getCustomerEmails()[0];
final String subject = "Order %d is pending".formatted(1);
final String body = "Dear %s, Your order %d is pending. Thank you for your order. - YumYumNow".formatted(
getCustomerNames()[0], 1);
final SimpleMailMessage expectedMessage = new SimpleMailMessage();
expectedMessage.setTo(to);
expectedMessage.setSubject(subject);
expectedMessage.setText(body);
verify(getMailSender()).send(expectedMessage);
}
}

View file

@ -0,0 +1,136 @@
package nl.tudelft.sem.yumyumnow.order.integration.notification;
import static org.mockito.Mockito.when;
import java.util.Optional;
import nl.tudelft.sem.yumyumnow.order.domain.order.OrderService;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroservice;
import nl.tudelft.sem.yumyumnow.order.utils.UserDetailsParser;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.MockitoAnnotations;
import org.order.model.Location;
import org.order.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.MailSender;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.web.servlet.MockMvc;
/**
* Integration tests for the email service.
*/
@SpringBootTest
@ExtendWith(SpringExtension.class)
// activate profiles to have spring use mocks during auto-injection of certain beans.
@ActiveProfiles({"test", "mockUserDetailsParser", "mockMailSender", "mockUsersMicroservice"})
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
@AutoConfigureMockMvc
class EmailServiceIntegrationTest {
@Autowired
private MockMvc mockMvc;
@Autowired
private UsersMicroservice usersMicroservice;
@Autowired
private OrderService orderService;
@Autowired
private UserDetailsParser userDetailsParser;
@Autowired
private MailSender mailSender;
private AutoCloseable closeable;
private final Long[] customerIds = {1L, 2L};
private final Long[] vendorIds = {3L, 4L};
private final Long[] adminIds = {5L};
private final String[] customerEmails = {"1@mail.com", "2@mail.com"};
private final String[] customerNames = {"1", "2"};
private final Location[] customerLocations = {
new Location().latitude(1.0f).longitude(1.0f), new Location().latitude(2.0f).longitude(2.0f)
};
@BeforeEach
void setUp() throws UserDetailsParser.InvalidHeaderException {
closeable = MockitoAnnotations.openMocks(this);
// Mock user details parser so that the test ids correspond with users. If not, throw invalid header exception.
when(userDetailsParser.parseRole(customerIds[0])).thenReturn("customer");
when(userDetailsParser.parseRole(customerIds[1])).thenReturn("customer");
when(userDetailsParser.parseRole(vendorIds[0])).thenReturn("vendor");
when(userDetailsParser.parseRole(vendorIds[1])).thenReturn("vendor");
when(userDetailsParser.parseRole(adminIds[0])).thenReturn("admin");
// Mock the users details parser so that the test customer ids have default addresses.
when(userDetailsParser.getHomeAddress(customerIds[0])).thenReturn(customerLocations[0]);
when(userDetailsParser.getHomeAddress(customerIds[1])).thenReturn(customerLocations[1]);
// Mock the users microservice service so that the test customer ids have emails.
when(usersMicroservice.getEmail(customerIds[0])).thenReturn(Optional.of(customerEmails[0]));
when(usersMicroservice.getEmail(customerIds[1])).thenReturn(Optional.of(customerEmails[1]));
// Mock the users microservice service so that the test customer ids have names.
when(usersMicroservice.getUser(customerIds[0])).thenReturn(Optional.of(new User().firstName(customerNames[0])));
when(usersMicroservice.getUser(customerIds[1])).thenReturn(Optional.of(new User().firstName(customerNames[1])));
}
@AfterEach
void tearDown() throws Exception {
closeable.close();
}
protected MockMvc getMockMvc() {
return mockMvc;
}
protected UsersMicroservice getUsersMicroservice() {
return usersMicroservice;
}
protected OrderService getOrderService() {
return orderService;
}
protected UserDetailsParser getUserDetailsParser() {
return userDetailsParser;
}
protected MailSender getMailSender() {
return mailSender;
}
protected AutoCloseable getCloseable() {
return closeable;
}
protected Long[] getCustomerIds() {
return customerIds;
}
protected Long[] getVendorIds() {
return vendorIds;
}
protected Long[] getAdminIds() {
return adminIds;
}
protected String[] getCustomerEmails() {
return customerEmails;
}
protected String[] getCustomerNames() {
return customerNames;
}
protected Location[] getCustomerLocations() {
return customerLocations;
}
}

View file

@ -0,0 +1,123 @@
package nl.tudelft.sem.yumyumnow.order.integration.notification;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.order.model.Order;
import org.springframework.http.MediaType;
import org.springframework.test.context.TestPropertySource;
@SuppressWarnings("SpringBootApplicationProperties")
@TestPropertySource(properties = "notification.config=classpath:notification/only-rejected.yml")
class NoStatusesTest extends EmailServiceIntegrationTest {
@Test
void testSendMail_CreateOrder() throws Exception {
final String jsonToSend =
"{\"vendorId\": %d, \"dishes\": [1,2], \"dishRequirements\": [\"\",\"\"], \"price\": 20}".formatted(
getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getCustomerIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_CreateOrder_noEmailAddress() throws Exception {
when(getUsersMicroservice().getEmail(anyLong())).thenReturn(Optional.empty());
final String jsonToSend =
"{\"vendorId\": %d, \"dishes\": [1,2], \"dishRequirements\": [\"\",\"\"], \"price\": 20}".formatted(
getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getCustomerIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_Accepted() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(put("/order/%d/status".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_noEmailAddress() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
when(getUsersMicroservice().getEmail(anyLong())).thenReturn(Optional.empty());
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_noOrder() throws Exception {
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(1)).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderByAdmin() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getAdminIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_CreateOrderByAdmin() throws Exception {
final String jsonToSend = """
{
"customerId": %d,
"vendorId": %d,
"dishes": [1,2],
"dishRequirements": ["",""],
"price": 20
}""".formatted(getCustomerIds()[0], getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getAdminIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_ToPending() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
getMockMvc().perform(put("/order/%d/status".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content("{\"status\": \"pending\"}"));
verifyNoInteractions(getMailSender());
}
}

View file

@ -0,0 +1,135 @@
package nl.tudelft.sem.yumyumnow.order.integration.notification;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.order.model.Order;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.test.context.TestPropertySource;
@SuppressWarnings("SpringBootApplicationProperties")
@TestPropertySource(properties = "notification.config=classpath:notification/not-pending.yml")
class NotPendingTest extends EmailServiceIntegrationTest {
@Test
void testSendMail_CreateOrder() throws Exception {
final String jsonToSend =
"{\"vendorId\": %d, \"dishes\": [1,2], \"dishRequirements\": [\"\",\"\"], \"price\": 20}".formatted(
getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getCustomerIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_CreateOrder_noEmailAddress() throws Exception {
when(getUsersMicroservice().getEmail(anyLong())).thenReturn(Optional.empty());
final String jsonToSend =
"{\"vendorId\": %d, \"dishes\": [1,2], \"dishRequirements\": [\"\",\"\"], \"price\": 20}".formatted(
getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getCustomerIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(put("/order/%d/status".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
final String to = getCustomerEmails()[0];
final String subject = "Order %d is accepted".formatted(order.getId());
final String body = "Dear %s, Your order %d is accepted. Thank you for your order. - YumYumNow".formatted(
getCustomerNames()[0], order.getId());
final SimpleMailMessage expectedMessage = new SimpleMailMessage();
expectedMessage.setTo(to);
expectedMessage.setSubject(subject);
expectedMessage.setText(body);
verify(getMailSender()).send(expectedMessage);
}
@Test
void testSendMail_UpdateOrderStatus_noEmailAddress() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
when(getUsersMicroservice().getEmail(anyLong())).thenReturn(Optional.empty());
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_noOrder() throws Exception {
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(1)).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderByAdmin() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getAdminIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_CreateOrderByAdmin() throws Exception {
final String jsonToSend = """
{
"customerId": %d,
"vendorId": %d,
"dishes": [1,2],
"dishRequirements": ["",""],
"price": 20
}""".formatted(getCustomerIds()[0], getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getAdminIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_ToPending() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
getMockMvc().perform(put("/order/%d/status".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content("{\"status\": \"pending\"}"));
verifyNoInteractions(getMailSender());
}
}

View file

@ -0,0 +1,148 @@
package nl.tudelft.sem.yumyumnow.order.integration.notification;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import java.util.Optional;
import org.junit.jupiter.api.Test;
import org.order.model.Order;
import org.springframework.http.MediaType;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.test.context.TestPropertySource;
@SuppressWarnings("SpringBootApplicationProperties")
@TestPropertySource(properties = "notification.config=classpath:notification/only-rejected.yml")
class OnlyRejectedTest extends EmailServiceIntegrationTest {
@Test
void testSendMail_CreateOrder() throws Exception {
final String jsonToSend =
"{\"vendorId\": %d, \"dishes\": [1,2], \"dishRequirements\": [\"\",\"\"], \"price\": 20}".formatted(
getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getCustomerIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_CreateOrder_noEmailAddress() throws Exception {
when(getUsersMicroservice().getEmail(anyLong())).thenReturn(Optional.empty());
final String jsonToSend =
"{\"vendorId\": %d, \"dishes\": [1,2], \"dishRequirements\": [\"\",\"\"], \"price\": 20}".formatted(
getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getCustomerIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_Rejected() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
final String jsonToSend = "{\"status\": \"rejected\"}";
getMockMvc().perform(put("/order/%d/status".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
final String to = getCustomerEmails()[0];
final String subject = "Order %d is rejected".formatted(order.getId());
final String body = "Dear %s, Your order %d is rejected. Thank you for your order. - YumYumNow".formatted(
getCustomerNames()[0], order.getId());
final SimpleMailMessage expectedMessage = new SimpleMailMessage();
expectedMessage.setTo(to);
expectedMessage.setSubject(subject);
expectedMessage.setText(body);
verify(getMailSender()).send(expectedMessage);
}
@Test
void testSendMail_UpdateOrderStatus_Accepted() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(put("/order/%d/status".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_noEmailAddress() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
when(getUsersMicroservice().getEmail(anyLong())).thenReturn(Optional.empty());
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_noOrder() throws Exception {
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(1)).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderByAdmin() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
final String jsonToSend = "{\"status\": \"accepted\"}";
getMockMvc().perform(post("/order/%d".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getAdminIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_CreateOrderByAdmin() throws Exception {
final String jsonToSend = """
{
"customerId": %d,
"vendorId": %d,
"dishes": [1,2],
"dishRequirements": ["",""],
"price": 20
}""".formatted(getCustomerIds()[0], getVendorIds()[0]);
getMockMvc().perform(post("/order").contentType(MediaType.APPLICATION_JSON)
.header("userId", getAdminIds()[0])
.content(jsonToSend));
verifyNoInteractions(getMailSender());
}
@Test
void testSendMail_UpdateOrderStatus_ToPending() throws Exception {
final Order order =
getOrderService().createOrder(getCustomerIds()[0], getVendorIds()[0], null, null, null, null, null);
getMockMvc().perform(put("/order/%d/status".formatted(order.getId())).contentType(MediaType.APPLICATION_JSON)
.header("userId", getVendorIds()[0])
.content("{\"status\": \"pending\"}"));
verifyNoInteractions(getMailSender());
}
}

View file

@ -0,0 +1,26 @@
package nl.tudelft.sem.yumyumnow.order.profiles;
import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.mail.MailSender;
/**
* Configuration class for the mock mail sender.
*/
@Configuration
public class MockMailSenderConfig {
/**
* Creates a mock mail sender.
*
* @return the mock mail sender.
*/
@Profile("mockMailSender")
@Primary
@Bean
public MailSender mockMailSender() {
return Mockito.mock(MailSender.class);
}
}

View file

@ -0,0 +1,26 @@
package nl.tudelft.sem.yumyumnow.order.profiles;
import nl.tudelft.sem.yumyumnow.order.external.UsersMicroservice;
import org.mockito.Mockito;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
/**
* Configuration class for the mock users-microservice.
*/
@Configuration
public class MockUsersMicroserviceConfig {
/**
* Creates a mock users-microservice.
*
* @return the mock users-microservice.
*/
@Profile("mockUsersMicroservice")
@Primary
@Bean
public UsersMicroservice mockUserMicroservice() {
return Mockito.mock(UsersMicroservice.class);
}
}

View file

@ -0,0 +1,60 @@
# A list of statuses for which a customer is notified by email when an order is assigned that status
email:
statuses:
- pending
- accepted
- rejected
- preparing
- given to courier
- on-transit
- delivered
templates:
pending:
subject: Order %d is pending
body: >-
Dear %s,
Your order %d is pending.
Thank you for your order.
- YumYumNow
accepted:
subject: Order %d is accepted
body: >-
Dear %s,
Your order %d is accepted.
Thank you for your order.
- YumYumNow
rejected:
subject: Order %d is rejected
body: >-
Dear %s,
Your order %d is rejected.
Thank you for your order.
- YumYumNow
preparing:
subject: Order %d is being prepared
body: >-
Dear %s,
Your order %d is being prepared.
Thank you for your order.
- YumYumNow
given to courier:
subject: Order %d is given to a courier
body: >-
Dear %s,
Your order %d is given to a courier.
Thank you for your order.
- YumYumNow
on-transit:
subject: Order %d is on transit
body: >-
Dear %s,
Your order %d is on transit.
Thank you for your order.
- YumYumNow
delivered:
subject: Order %d is delivered
body: >-
Dear %s,
Your order %d is delivered.
Thank you for your order.
- YumYumNow

View file

@ -0,0 +1,53 @@
# A list of statuses for which a customer is notified by email when an order is assigned that status
email:
statuses:
templates:
pending:
subject: Order %d is pending
body: >-
Dear %s,
Your order %d is pending.
Thank you for your order.
- YumYumNow
accepted:
subject: Order %d is accepted
body: >-
Dear %s,
Your order %d is accepted.
Thank you for your order.
- YumYumNow
rejected:
subject: Order %d is rejected
body: >-
Dear %s,
Your order %d is rejected.
Thank you for your order.
- YumYumNow
preparing:
subject: Order %d is being prepared
body: >-
Dear %s,
Your order %d is being prepared.
Thank you for your order.
- YumYumNow
given to courier:
subject: Order %d is given to a courier
body: >-
Dear %s,
Your order %d is given to a courier.
Thank you for your order.
- YumYumNow
on-transit:
subject: Order %d is on transit
body: >-
Dear %s,
Your order %d is on transit.
Thank you for your order.
- YumYumNow
delivered:
subject: Order %d is delivered
body: >-
Dear %s,
Your order %d is delivered.
Thank you for your order.
- YumYumNow

View file

@ -0,0 +1,59 @@
# A list of statuses for which a customer is notified by email when an order is assigned that status
email:
statuses:
- accepted
- rejected
- preparing
- given to courier
- on-transit
- delivered
templates:
pending:
subject: Order %d is pending
body: >-
Dear %s,
Your order %d is pending.
Thank you for your order.
- YumYumNow
accepted:
subject: Order %d is accepted
body: >-
Dear %s,
Your order %d is accepted.
Thank you for your order.
- YumYumNow
rejected:
subject: Order %d is rejected
body: >-
Dear %s,
Your order %d is rejected.
Thank you for your order.
- YumYumNow
preparing:
subject: Order %d is being prepared
body: >-
Dear %s,
Your order %d is being prepared.
Thank you for your order.
- YumYumNow
given to courier:
subject: Order %d is given to a courier
body: >-
Dear %s,
Your order %d is given to a courier.
Thank you for your order.
- YumYumNow
on-transit:
subject: Order %d is on transit
body: >-
Dear %s,
Your order %d is on transit.
Thank you for your order.
- YumYumNow
delivered:
subject: Order %d is delivered
body: >-
Dear %s,
Your order %d is delivered.
Thank you for your order.
- YumYumNow

View file

@ -0,0 +1,54 @@
# A list of statuses for which a customer is notified by email when an order is assigned that status
email:
statuses:
- rejected
templates:
pending:
subject: Order %d is pending
body: >-
Dear %s,
Your order %d is pending.
Thank you for your order.
- YumYumNow
accepted:
subject: Order %d is accepted
body: >-
Dear %s,
Your order %d is accepted.
Thank you for your order.
- YumYumNow
rejected:
subject: Order %d is rejected
body: >-
Dear %s,
Your order %d is rejected.
Thank you for your order.
- YumYumNow
preparing:
subject: Order %d is being prepared
body: >-
Dear %s,
Your order %d is being prepared.
Thank you for your order.
- YumYumNow
given to courier:
subject: Order %d is given to a courier
body: >-
Dear %s,
Your order %d is given to a courier.
Thank you for your order.
- YumYumNow
on-transit:
subject: Order %d is on transit
body: >-
Dear %s,
Your order %d is on transit.
Thank you for your order.
- YumYumNow
delivered:
subject: Order %d is delivered
body: >-
Dear %s,
Your order %d is delivered.
Thank you for your order.
- YumYumNow