|
| 1 | +package org.baeldung; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertEquals; |
| 4 | +import static org.junit.Assert.assertTrue; |
| 5 | +import io.restassured.RestAssured; |
| 6 | +import io.restassured.response.Response; |
| 7 | + |
| 8 | +import java.util.Set; |
| 9 | + |
| 10 | +import org.junit.Before; |
| 11 | +import org.junit.Test; |
| 12 | +import org.junit.runner.RunWith; |
| 13 | +import org.springframework.boot.test.context.SpringBootTest; |
| 14 | +import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; |
| 15 | +import org.springframework.http.HttpStatus; |
| 16 | +import org.springframework.test.context.junit4.SpringRunner; |
| 17 | + |
| 18 | +import redis.clients.jedis.Jedis; |
| 19 | + |
| 20 | +@RunWith(SpringRunner.class) |
| 21 | +@SpringBootTest(classes = { SpringCloudRestClientApplication.class, SessionConfig.class }, webEnvironment = WebEnvironment.DEFINED_PORT) |
| 22 | +public class SessionLiveTest { |
| 23 | + |
| 24 | + private Jedis jedis; |
| 25 | + private static final String API_URI = "http://localhost:8084/books"; |
| 26 | + |
| 27 | + @Before |
| 28 | + public void setUp() { |
| 29 | + jedis = new Jedis("localhost", 6379); |
| 30 | + jedis.flushAll(); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + public void whenStart_thenNoSessionsExist() { |
| 35 | + final Set<String> result = jedis.keys("*"); |
| 36 | + assertEquals(0, result.size()); |
| 37 | + } |
| 38 | + |
| 39 | + @Test |
| 40 | + public void givenUnauthorizeUser_whenAccessResources_then_unAuthorized() { |
| 41 | + final Response response = RestAssured.get(API_URI); |
| 42 | + assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatusCode()); |
| 43 | + } |
| 44 | + |
| 45 | + @Test |
| 46 | + public void givenAuthorizedUser_whenDeleteSession_thenUnauthorized() { |
| 47 | + // authorize User |
| 48 | + Response response = RestAssured.given() |
| 49 | + .auth() |
| 50 | + .preemptive() |
| 51 | + .basic("user", "userPass") |
| 52 | + .get(API_URI); |
| 53 | + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); |
| 54 | + final String sessionCookie = response.getCookie("SESSION"); |
| 55 | + |
| 56 | + // check redis |
| 57 | + final Set<String> redisResult = jedis.keys("*"); |
| 58 | + assertTrue(redisResult.size() > 0); |
| 59 | + |
| 60 | + // login with cookie |
| 61 | + response = RestAssured.given() |
| 62 | + .cookie("SESSION", sessionCookie) |
| 63 | + .get(API_URI); |
| 64 | + assertEquals(HttpStatus.OK.value(), response.getStatusCode()); |
| 65 | + |
| 66 | + // empty redis |
| 67 | + jedis.flushAll(); |
| 68 | + |
| 69 | + // login with cookie again |
| 70 | + response = RestAssured.given() |
| 71 | + .cookie("SESSION", sessionCookie) |
| 72 | + .get(API_URI); |
| 73 | + assertEquals(HttpStatus.UNAUTHORIZED.value(), response.getStatusCode()); |
| 74 | + } |
| 75 | +} |
0 commit comments