|
| 1 | +package org.openimis.imisclaims; |
| 2 | + |
| 3 | +import static org.junit.Assert.assertFalse; |
| 4 | +import static org.junit.Assert.assertSame; |
| 5 | +import static org.junit.Assert.assertTrue; |
| 6 | +import static org.mockito.Mockito.doReturn; |
| 7 | +import static org.mockito.Mockito.never; |
| 8 | +import static org.mockito.Mockito.spy; |
| 9 | +import static org.mockito.Mockito.verify; |
| 10 | +import static org.mockito.Mockito.when; |
| 11 | + |
| 12 | +import android.content.SharedPreferences; |
| 13 | + |
| 14 | +import org.junit.Before; |
| 15 | +import org.junit.Test; |
| 16 | +import org.junit.runner.RunWith; |
| 17 | +import org.mockito.Mock; |
| 18 | +import org.mockito.junit.MockitoJUnitRunner; |
| 19 | +import org.openimis.imisclaims.network.util.PersistentCookieJar; |
| 20 | + |
| 21 | +@RunWith(MockitoJUnitRunner.class) |
| 22 | +public class GlobalSessionTest { |
| 23 | + |
| 24 | + @Mock |
| 25 | + private Token token; |
| 26 | + @Mock |
| 27 | + private SharedPreferences preferences; |
| 28 | + @Mock |
| 29 | + private PersistentCookieJar cookieJar; |
| 30 | + |
| 31 | + private Global global; |
| 32 | + |
| 33 | + @Before |
| 34 | + public void setUp() { |
| 35 | + global = spy(new Global()); |
| 36 | + doReturn(token).when(global).getJWTToken(); |
| 37 | + doReturn(preferences).when(global).getDefaultSharedPreferences(); |
| 38 | + global.setCookieJar(cookieJar); |
| 39 | + } |
| 40 | + |
| 41 | + @Test |
| 42 | + public void isLoggedIn_trueOnlyWhenJwtValidAndSessionNotExpired_otherwiseClearsState() { |
| 43 | + when(token.isTokenValidJWT()).thenReturn(true); |
| 44 | + when(preferences.getLong("session_expiry", 0)).thenReturn(System.currentTimeMillis() + 5_000); |
| 45 | + assertTrue(global.isLoggedIn()); |
| 46 | + verify(token, never()).clearToken(); |
| 47 | + |
| 48 | + when(token.isTokenValidJWT()).thenReturn(false); |
| 49 | + when(preferences.getLong("session_expiry", 0)).thenReturn(System.currentTimeMillis() + 5_000); |
| 50 | + assertFalse(global.isLoggedIn()); |
| 51 | + verify(token).clearToken(); |
| 52 | + verify(cookieJar).clear(); |
| 53 | + |
| 54 | + when(token.isTokenValidJWT()).thenReturn(true); |
| 55 | + when(preferences.getLong("session_expiry", 0)).thenReturn(System.currentTimeMillis() - 5_000); |
| 56 | + assertFalse(global.isLoggedIn()); |
| 57 | + } |
| 58 | + |
| 59 | + @Test |
| 60 | + public void cookieJar_reference_setAndGet_roundTrip() { |
| 61 | + PersistentCookieJar anotherJar = org.mockito.Mockito.mock(PersistentCookieJar.class); |
| 62 | + global.setCookieJar(anotherJar); |
| 63 | + assertSame(anotherJar, global.getCookieJar()); |
| 64 | + } |
| 65 | +} |
0 commit comments