1+ package me .oldboy .integration .controllers .api_mock_aouth_scenario ;
2+ 3+ import com .fasterxml .jackson .core .type .TypeReference ;
4+ import com .fasterxml .jackson .databind .ObjectMapper ;
5+ import com .fasterxml .jackson .datatype .jsr310 .JavaTimeModule ;
6+ import lombok .SneakyThrows ;
7+ import me .oldboy .config .security_details .ClientDetailsService ;
8+ import me .oldboy .config .test_data_source .TestContainerInit ;
9+ import me .oldboy .dto .loan_dto .LoanCreateDto ;
10+ import me .oldboy .dto .loan_dto .LoanReadDto ;
11+ import me .oldboy .integration .annotation .IT ;
12+ import me .oldboy .integration .annotation .WithMockOAuth2User ;
13+ import me .oldboy .services .LoanService ;
14+ import org .junit .jupiter .api .BeforeEach ;
15+ import org .junit .jupiter .api .Test ;
16+ import org .springframework .beans .factory .annotation .Autowired ;
17+ import org .springframework .http .MediaType ;
18+ import org .springframework .test .web .servlet .MockMvc ;
19+ import org .springframework .test .web .servlet .MvcResult ;
20+ import org .springframework .test .web .servlet .request .MockMvcRequestBuilders ;
21+ import org .springframework .test .web .servlet .setup .MockMvcBuilders ;
22+ import org .springframework .web .context .WebApplicationContext ;
23+ 24+ import java .time .LocalDate ;
25+ import java .util .List ;
26+ 27+ import static me .oldboy .test_constant .TestConstantFields .EXIST_EMAIL ;
28+ import static org .assertj .core .api .Assertions .assertThat ;
29+ import static org .springframework .security .test .web .servlet .setup .SecurityMockMvcConfigurers .springSecurity ;
30+ import static org .springframework .test .web .servlet .request .MockMvcRequestBuilders .get ;
31+ import static org .springframework .test .web .servlet .result .MockMvcResultMatchers .content ;
32+ import static org .springframework .test .web .servlet .result .MockMvcResultMatchers .status ;
33+ 34+ @ IT
35+ class WmkLoansControllerIT extends TestContainerInit {
36+ 37+ @ Autowired
38+ private WebApplicationContext webApplicationContext ;
39+ @ Autowired
40+ private LoanService loanService ;
41+ @ Autowired
42+ private ClientDetailsService clientDetailsService ;
43+ private MockMvc mockMvc ;
44+ 45+ private Long testId , anotherId ;
46+ private LoanCreateDto testLoanCreateDtoForOwner , testLoanCreateDtoToAnotherClient ;
47+ private List <LoanCreateDto > testList ;
48+ private ObjectMapper objectMapper ;
49+ 50+ @ BeforeEach
51+ void setUp (){
52+ testId = 1L ;
53+ anotherId = 3L ;
54+ 55+ objectMapper = new ObjectMapper ().registerModule (new JavaTimeModule ());
56+ 57+ mockMvc = MockMvcBuilders .webAppContextSetup (webApplicationContext )
58+ .apply (springSecurity ())
59+ .build ();
60+ 61+ testLoanCreateDtoForOwner = LoanCreateDto .builder ()
62+ .clientId (testId )
63+ .startDate (LocalDate .of (2021 , 04 ,05 ))
64+ .loanType ("Plane" )
65+ .totalLoan (350000 )
66+ .amountPaid (65000 )
67+ .outstandingAmount (210000 )
68+ .createDate (LocalDate .of (2021 , 03 ,05 ))
69+ .build ();
70+ testLoanCreateDtoToAnotherClient = LoanCreateDto .builder ()
71+ .clientId (anotherId )
72+ .startDate (LocalDate .of (2022 , 11 ,12 ))
73+ .loanType ("Castle" )
74+ .totalLoan (1350000 )
75+ .amountPaid (115000 )
76+ .outstandingAmount (600000 )
77+ .createDate (LocalDate .of (2022 , 10 ,03 ))
78+ .build ();
79+ 80+ testList = List .of (testLoanCreateDtoForOwner , testLoanCreateDtoToAnotherClient );
81+ }
82+ 83+ @ Test
84+ @ SneakyThrows
85+ @ WithMockOAuth2User (username = EXIST_EMAIL , email = EXIST_EMAIL , authorities = {"ROLE_ADMIN" })
86+ void getLoanDetails_ShouldReturnDtoList_ForClientWithLoans_Test () {
87+ MvcResult result = mockMvc .perform (MockMvcRequestBuilders .get ("/api/myLoans" ))
88+ .andExpect (status ().isOk ())
89+ .andReturn ();
90+ 91+ String strRes = result .getResponse ().getContentAsString ();
92+ List <LoanReadDto > loansListFromBase = new ObjectMapper ()
93+ .registerModule (new JavaTimeModule ())
94+ .readValue (strRes , new TypeReference <List <LoanReadDto >>() {});
95+ 96+ assertThat (loansListFromBase .size ()).isGreaterThan (0 );
97+ }
98+ 99+ @ Test
100+ @ SneakyThrows
101+ @ WithMockOAuth2User (username = "user@test.com" , email = "user@test.com" , authorities = {"ROLE_USER" })
102+ void getLoanDetails_ShouldReturnEmptyBody_IfClientHasNoLoans_Test () {
103+ mockMvc .perform (MockMvcRequestBuilders .get ("/api/myLoans" ))
104+ .andExpect (status ().is2xxSuccessful ())
105+ .andExpect (content ().string ("" ));
106+ }
107+ 108+ @ Test
109+ @ SneakyThrows
110+ void getLoanDetails_ShouldReturnNotAuth_4xx_WithoutAuth_Test () {
111+ mockMvc .perform (MockMvcRequestBuilders .get ("/api/myLoans" ))
112+ .andExpect (status ().is4xxClientError ())
113+ .andExpect (content ().string ("" ));
114+ }
115+ 116+ @ Test
117+ @ SneakyThrows
118+ @ WithMockOAuth2User (username = EXIST_EMAIL , email = EXIST_EMAIL , authorities = {"ROLE_ADMIN" })
119+ void createLoan_ShouldReturnOk_AndRecordIdFromBase_Test () {
120+ /* Подготовим данные для сохранения в БД*/
121+ String strLoanCreateDto = objectMapper .writeValueAsString (testLoanCreateDtoForOwner );
122+ 123+ /* Делаем запрос на сохранение */
124+ MvcResult result = mockMvc .perform (MockMvcRequestBuilders .post ("/api/createLoan" )
125+ .contentType (MediaType .APPLICATION_JSON )
126+ .content (strLoanCreateDto ))
127+ .andExpect (status ().isOk ())
128+ .andReturn ();
129+ 130+ /* "Парсим" ответ */
131+ String strRes = result .getResponse ().getContentAsString ();
132+ Long afterCreateLoanId = objectMapper .readValue (strRes , Long .class );
133+ 134+ /* Сравниваем ожидание с результатом - ID последней записи будет больше последнего известного из БД - 8 */
135+ assertThat (afterCreateLoanId ).isGreaterThan (8 );
136+ }
137+ 138+ /* Id аутентифицированного клиента и Id того на кого оформлен кредит не совпадает - сохранить нельзя */
139+ 140+ @ Test
141+ @ SneakyThrows
142+ @ WithMockOAuth2User (username = EXIST_EMAIL , email = EXIST_EMAIL , authorities = {"ROLE_ADMIN" })
143+ void createLoan_ShouldReturnBadRequest_TryToSaveNotYoursLoan_Test () {
144+ /* Подготовим данные для сохранения в БД*/
145+ String strLoanCreateDto = objectMapper .writeValueAsString (testLoanCreateDtoToAnotherClient );
146+ 147+ /* Делаем запрос на сохранение */
148+ mockMvc .perform (MockMvcRequestBuilders .post ("/api/createLoan" )
149+ .contentType (MediaType .APPLICATION_JSON )
150+ .content (strLoanCreateDto ))
151+ .andExpect (status ().isBadRequest ())
152+ .andExpect (content ().string ("" ));
153+ }
154+ 155+ @ Test
156+ @ SneakyThrows
157+ @ WithMockOAuth2User (username = EXIST_EMAIL , email = EXIST_EMAIL , authorities = {"ROLE_ADMIN" })
158+ void saveAllMyRequestLoan_ShouldReturnOk_AndSaveOnlyAuthOwnerLoans_Test () {
159+ /* Получим количество записей в БД */
160+ List <LoanReadDto > loansList = loanService .findAll ();
161+ Integer listSizeBefore = loansList .size ();
162+ 163+ /* Подготовим данные для сохранения в БД */
164+ String strList = objectMapper .writeValueAsString (testList );
165+ 166+ /* Делаем запрос на сохранение */
167+ mockMvc .perform (MockMvcRequestBuilders .post ("/api/save-all-loans" )
168+ .contentType (MediaType .APPLICATION_JSON )
169+ .content (strList ))
170+ .andExpect (status ().isOk ())
171+ .andExpect (content ().string ("Saved all loans!" ));
172+ 173+ /* Проверяем количество записей в БД после сохранения списка кредитов - больше на одну */
174+ Integer listSizeAfter = loanService .findAll ().size ();
175+ assertThat (listSizeAfter ).isEqualTo (listSizeBefore + 1 );
176+ }
177+ 178+ @ Test
179+ @ SneakyThrows
180+ @ WithMockOAuth2User (username = "user3@test.com" , email = "user3@test.com" , authorities = {"ROLE_USER" })
181+ void saveAllMyRequestLoan_ShouldReturnOk_ButOperationFailed_Test () {
182+ /* Получим количество записей в БД */
183+ List <LoanReadDto > loansList = loanService .findAll ();
184+ Integer listSizeBefore = loansList .size ();
185+ 186+ /* Подготовим данные для сохранения в БД */
187+ String strList = objectMapper .writeValueAsString (testList );
188+ 189+ /* Делаем запрос на сохранение */
190+ mockMvc .perform (MockMvcRequestBuilders .post ("/api/save-all-loans" )
191+ .contentType (MediaType .APPLICATION_JSON )
192+ .content (strList ))
193+ .andExpect (status ().isOk ())
194+ .andExpect (content ().string ("Operation is failed!" ));
195+ 196+ /* Проверяем количество записей в БД после сохранения списка кредитов - неизменен */
197+ Integer listSizeAfter = loanService .findAll ().size ();
198+ assertThat (listSizeAfter ).isEqualTo (listSizeBefore );
199+ }
200+ 201+ @ Test
202+ @ SneakyThrows
203+ @ WithMockOAuth2User (username = EXIST_EMAIL , email = EXIST_EMAIL , authorities = {"ROLE_ADMIN" })
204+ void getAllLoanByType_ShouldReturnOkForRoleAdmin_AndListOfLoansByType_Test () {
205+ String loanType = "Home" ;
206+ 207+ MvcResult result = mockMvc .perform (get ("/api/get-all-loans-by-type/" + loanType ))
208+ .andExpect (status ().isOk ())
209+ .andReturn ();
210+ 211+ String strRes = result .getResponse ().getContentAsString ();
212+ 213+ List <LoanReadDto > respList = objectMapper .readValue (strRes , new TypeReference <List <LoanReadDto >>() {});
214+ 215+ assertThat (respList .size ()).isGreaterThan (1 );
216+ }
217+ 218+ @ Test
219+ @ SneakyThrows
220+ @ WithMockOAuth2User (username = "user3@test.com" , email = "user3@test.com" , authorities = {"ROLE_USER" })
221+ void getAllLoanByType_ShouldReturnForbidden_NotAdminAuth_Test () {
222+ String loanType = "Home" ;
223+ 224+ mockMvc .perform (get ("/api/get-all-loans-by-type/" + loanType ))
225+ .andExpect (status ().isBadRequest ())
226+ .andExpect (content ().string ("{\" exceptionMsg\" :\" Access Denied\" }" ));
227+ }
228+ }
0 commit comments