Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Integration hard test #64

Merged
merged 11 commits into from
Mar 17, 2024
4 changes: 2 additions & 2 deletions src/main/resources/database-content.sql
Original file line number Diff line number Diff line change
Expand Up @@ -259,8 +259,8 @@ VALUES (10, -1, -1, -1),
(5, -50, -19, -5),
(5, -51, -20, -5);

CREATE
EXTENSION pgcrypto;
CREATE EXTENSION IF NOT EXISTS pgcrypto;

INSERT INTO user_account (id, full_name, password_hash, phone, role_id, speciality_id)
VALUES (-1, 'Иванов Иван Иванович', digest('123456', 'sha256'), '+79260567450', -1, NULL),
(-2, 'Глазов Степан Фёдорович', digest('654321', 'sha256'), '+79310367450', -2, -5),
Expand Down
20 changes: 18 additions & 2 deletions src/test/java/org/example/controller/TestObjects.java
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public class TestObjects {
public static ItemDto special;

public static Long userId;
public static Long userIdTest;
public static Date creationDate;
public static Date deliveryDate;

Expand All @@ -56,15 +57,20 @@ public class TestObjects {
public static RoleDto pharmacistRole;

public static UserAccountDto simpleUser;
public static UserAccountDto testUser;
public static UserAccountDto test2User;
public static UserAccountDto doctor;
public static UserAccountDto pharmacist;

public static CartDto cart;
public static CartDto cartSecUser;
public static CartDto cartTestUser;
public static CartDto cartTest2User;
public static CartToItemDto cartItem1;
public static CartToItemDto cartItem2;
public static CartToItemDto[] cartItems;
public static CartToItemDto[] cartItemsSecUser;
public static CartToItemDto[] cartItemsTestUser;

public static Integer badRequest;
public static Integer notFoundCode;
Expand All @@ -84,6 +90,8 @@ public class TestObjects {
pharmacyId = -1L;
receiptItemId = -1L;

userIdTest = -4L;

SpecialityDto speciality = new SpecialityDto(-1L, "терапевт");

firstPharmacy =
Expand Down Expand Up @@ -130,9 +138,14 @@ public class TestObjects {

simpleUser =
new UserAccountDto(-1L, "Иванов Иван Иванович", "+79260567450", simpleUserRole, null);
pharmacist =
doctor =
new UserAccountDto(-2L, "Глазов Степан Фёдорович", "+79310367450", doctorRole, speciality);
doctor = new UserAccountDto(-3L, "Главный Пётр Петрович", "+79510367450", pharmacistRole, null);
pharmacist =
new UserAccountDto(-3L, "Главный Пётр Петрович", "+79510367450", pharmacistRole, null);
testUser =
new UserAccountDto(-4L, "Я тестовый пользователь", "+79510367457", simpleUserRole, null);
test2User =
new UserAccountDto(-5L, "Я тоже пользователь", "+79510367458", simpleUserRole, null);
itemsFirstOrder = new ItemDto[] {receipt};
itemsSecondOrder = new ItemDto[] {special};
itemsThirdOrder = new ItemDto[] {receipt, special};
Expand Down Expand Up @@ -191,9 +204,12 @@ public class TestObjects {
cartItem2 = new CartToItemDto(special, 1);
cartItems = new CartToItemDto[] {cartItem2, cartItem1};
cartItemsSecUser = new CartToItemDto[] {cartItem2};
cartItemsTestUser = new CartToItemDto[] {cartItem1};

cart = new CartDto(-1L, userId, Arrays.stream(cartItems).toList());
cartSecUser = new CartDto(-2L, -2L, Arrays.stream(cartItemsSecUser).toList());
cartTestUser = new CartDto(-4L, -4L, Arrays.stream(cartItemsSecUser).toList());
cartTest2User = new CartDto(-5L, -5L, Arrays.stream(cartItemsTestUser).toList());

badRequest = 400;
notFoundCode = 404;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ void logoutSuccess() {
@SneakyThrows
void logoutFailed() {
mockMvc
.perform(post("/api/accounts/logout").param("user_id", "-4"))
.perform(post("/api/accounts/logout").param("user_id", "-6"))
.andExpectAll(
status().isNotFound(),
jsonPath("$.*", hasSize(3)),
Expand Down
92 changes: 89 additions & 3 deletions src/test/java/org/example/controller/cart/CartControllerTest.java
Original file line number Diff line number Diff line change
@@ -1,12 +1,21 @@
package org.example.controller.cart;

import static org.example.controller.TestObjects.cartSecUser;
import static org.example.controller.TestObjects.cartTest2User;
import static org.example.controller.TestObjects.cartTestUser;
import static org.example.controller.TestObjects.creationDate;
import static org.example.controller.TestObjects.creationDateStr;
import static org.example.controller.TestObjects.deliveryDate;
import static org.example.controller.TestObjects.deliveryDateStr;
import static org.example.controller.TestObjects.notFound;
import static org.example.controller.TestObjects.notFoundCode;
import static org.example.controller.TestObjects.receipt;
import static org.example.controller.TestObjects.special;
import static org.example.controller.TestObjects.sumPrice;
import static org.example.controller.TestObjects.test2User;
import static org.example.controller.TestObjects.userNotFound;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
Expand All @@ -16,6 +25,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.example.controller.MvcUtil;
import org.example.dto.user.UserAccountDto;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
Expand Down Expand Up @@ -44,7 +54,7 @@ void getAllItemsInCart() {
@SneakyThrows
void getAllItemsInCart_UserNotFound() {
mockMvc
.perform(get("/api/cart/1"))
.perform(get("/api/cart/-6"))
.andExpectAll(status().isNotFound(), jsonPath("$.*", hasSize(3)))
.andExpect(jsonPath("$.code").value(userNotFound))
.andExpect(jsonPath("$.status").value(notFoundCode))
Expand All @@ -70,7 +80,7 @@ void addItemToCart() {
void addItemToCart_UserNotFound() {
mockMvc
.perform(
post("/api/cart/add").param("item_id", "-1").param("user_id", "1").param("count", "1"))
post("/api/cart/add").param("item_id", "-1").param("user_id", "-6").param("count", "1"))
.andExpectAll(status().isNotFound(), jsonPath("$.*", hasSize(3)))
.andExpect(jsonPath("$.code").value(userNotFound))
.andExpect(jsonPath("$.status").value(notFoundCode))
Expand Down Expand Up @@ -103,10 +113,86 @@ void deleteItemFromCart() {
@SneakyThrows
void deleteItemFromCart_UserNotFound() {
mockMvc
.perform(delete("/api/cart/delete").param("item_id", "-1").param("user_id", "1"))
.perform(delete("/api/cart/delete").param("item_id", "-1").param("user_id", "-6"))
.andExpectAll(status().isNotFound(), jsonPath("$.*", hasSize(3)))
.andExpect(jsonPath("$.code").value(userNotFound))
.andExpect(jsonPath("$.status").value(notFoundCode))
.andExpect(jsonPath("$.message").value(userNotFound));
}

// тут начинаются сложные тесты

// тут УДАЛЯЕТСЯ из корзины, при перезапуске тестов нужно обновить тестовую бд !!
// просмотр корзины пользователя и размещение заказа
@Test
@SneakyThrows
void getCartInfoAndPlaceOrder() {
ResultActions result = mockMvc.perform(get("/api/cart/-4")).andExpect(status().isOk());
mvcUtil.assertContentEquals(result, objectMapper.writeValueAsString(cartTestUser));

mockMvc
.perform(
post("/api/order")
.param("user_id", String.valueOf(-4L))
.param("creation_date", creationDate.toString())
.param("delivery_date", deliveryDate.toString())
.param("sum_price", String.valueOf(sumPrice))
.param("pharmacy_id", "-1")
.param("items", "-2"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.user_id").value(-4L))
.andExpect(jsonPath("$.creation_date").value(creationDateStr))
.andExpect(jsonPath("$.delivery_date").value(deliveryDateStr))
.andExpect(jsonPath("$.sum_price").value(String.valueOf(sumPrice)))
.andExpect(jsonPath("$.pharmacy.id").value("-1"));
}

// добавление препарата в корзину и его удаление из корзины
@Test
@SneakyThrows
void addItemIntoCartAndDeleteItemFromCart() {
ResultActions result =
mockMvc
.perform(
post("/api/cart/add")
.param("item_id", "-1")
.param("user_id", "-2")
.param("count", "1"))
.andExpect(status().isOk());
mvcUtil.assertContentEquals(result, objectMapper.writeValueAsString(receipt));

ResultActions result2 =
mockMvc
.perform(delete("/api/cart/delete").param("item_id", "-1").param("user_id", "-2"))
.andExpect(status().isOk());
mvcUtil.assertContentEquals(result2, objectMapper.writeValueAsString(receipt));
}

// аутентификация пользователя, добавление товара в корзину и просмотр корзины
@Test
@SneakyThrows
void authUserAddItemIntoCartAndCheckCart() {
ResultActions result =
mockMvc
.perform(
post("/api/accounts/login")
.param("phone", "+79510367458")
.param("password", "12345"))
.andExpect(status().isOk());
UserAccountDto resultDto = mvcUtil.readResponseValue(UserAccountDto.class, result);
assertEquals(test2User, resultDto);

ResultActions result2 =
mockMvc
.perform(
post("/api/cart/add")
.param("item_id", "-1")
.param("user_id", "-5")
.param("count", "2"))
.andExpect(status().isOk());
mvcUtil.assertContentEquals(result2, objectMapper.writeValueAsString(receipt));

ResultActions result3 = mockMvc.perform(get("/api/cart/-5")).andExpect(status().isOk());
mvcUtil.assertContentEquals(result3, objectMapper.writeValueAsString(cartTest2User));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
import static org.example.controller.TestObjects.*;
import static org.hamcrest.Matchers.hasSize;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import lombok.SneakyThrows;
import org.example.controller.MvcUtil;
import org.example.dto.item.ItemDto;
import org.example.dto.user.UserAccountDto;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
Expand Down Expand Up @@ -83,4 +86,49 @@ void getAllItemsBySpecId() {
ItemDto[] resultDto = mvcUtil.readResponseValue(ItemDto[].class, result);
assertArrayEquals(new ItemDto[] {special}, resultDto);
}

// аутентификация пользователя фармацевта и просмотр всех препаратов
@Test
@SneakyThrows
void getAllItemsByDoc() {
ResultActions result =
mockMvc
.perform(
post("/api/accounts/login")
.param("phone", doctor.phone())
.param("password", "654321"))
.andExpect(status().isOk());
UserAccountDto resultDto = mvcUtil.readResponseValue(UserAccountDto.class, result);
assertEquals(doctor, resultDto);

ResultActions resultItem =
mockMvc
.perform(get("/api/item/doc/all?user_id=" + resultDto.id()))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)));
ItemDto[] resultItemDto = mvcUtil.readResponseValue(ItemDto[].class, resultItem);
assertArrayEquals(new ItemDto[] {special, receipt}, resultItemDto);
}

// аутентификация пользователя фармацевта и просмотр всех препаратов
@Test
@SneakyThrows
void getAllItemsBySpec() {
ResultActions result =
mockMvc
.perform(
post("/api/accounts/login")
.param("phone", doctor.phone())
.param("password", "654321"))
.andExpect(status().isOk());
UserAccountDto resultDto = mvcUtil.readResponseValue(UserAccountDto.class, result);
assertEquals(doctor, resultDto);
ResultActions resultItem =
mockMvc
.perform(get("/api/item/type/category?speciality_id=" + resultDto.speciality().id()))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(1)));
ItemDto[] resultItemDto = mvcUtil.readResponseValue(ItemDto[].class, resultItem);
assertArrayEquals(new ItemDto[] {special}, resultItemDto);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ void getUserInfoSuccess() {
@SneakyThrows
void getUserInfoFailed() {
mockMvc
.perform(get("/api/info/-5"))
.perform(get("/api/info/-6"))
.andExpectAll(
status().isNotFound(),
jsonPath("$.*", hasSize(3)),
Expand Down
11 changes: 8 additions & 3 deletions src/test/resources/test-database-content.sql
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,9 @@ CREATE EXTENSION IF NOT EXISTS pgcrypto;
INSERT INTO user_account (id, full_name, password_hash, phone, role_id, speciality_id)
VALUES (-1, 'Иванов Иван Иванович', digest('123456', 'sha256'), '+79260567450', -1, NULL),
(-2, 'Глазов Степан Фёдорович', digest('654321', 'sha256'), '+79310367450', -2, -1),
(-3, 'Главный Пётр Петрович', digest('12345', 'sha256'), '+79510367450', -3, NULL);
(-3, 'Главный Пётр Петрович', digest('12345', 'sha256'), '+79510367450', -3, NULL),
(-4, 'Я тестовый пользователь', digest('12345', 'sha256'), '+79510367457', -1, NULL),
(-5, 'Я тоже пользователь', digest('12345', 'sha256'), '+79510367458', -1, NULL);;

INSERT INTO orders (creation_date, delivery_date, sum_price, id, pharmacy_id, user_id)
VALUES ('2024-01-11', '2024-01-16', 100500, -1, -1, -1),
Expand All @@ -59,9 +61,12 @@ VALUES (1, -1, -1, -1),
INSERT INTO cart (id, user_id)
VALUES (-1, -1),
(-2, -2),
(-3, -3);
(-3, -3),
(-4, -4),
(-5, -5);

INSERT INTO cart_to_item (quantity, cart_id, id, item_id)
VALUES (2, -1, -1, -1),
(1, -1, -2, -2),
(1, -2, -3, -2);
(1, -2, -3, -2),
(1, -4, -4, -2);
Loading