Skip to content

Commit

Permalink
oppia-969: Fetch profile info before showing profile form and added t…
Browse files Browse the repository at this point in the history
…ests
  • Loading branch information
jjoseba committed Apr 20, 2023
1 parent 499620c commit b441e9c
Show file tree
Hide file tree
Showing 10 changed files with 260 additions and 172 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"api_key": "fakeapikey",
"first_name": "Tester",
"last_name": "Testington",
"email": "fakeemail@domain.com",
"cohorts": [4, 5, 6]
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public class EditProfileActivityTest extends MockedApiEndpointTest {
private static final String VALID_LAST_NAME = "Last Name";
private static final String VALID_ORGANIZATION = "A organization";
private static final String VALID_JOB_TITLE = "A job title";
public static final String VALID_PROFILE_RESPONSE = "responses/response_200_profile.json";

@Mock
protected User user;
Expand All @@ -71,6 +72,7 @@ public void setUp() throws Exception {
testDBHelper = new TestDBHelper(InstrumentationRegistry.getInstrumentation().getTargetContext());
testDBHelper.setUp();

startServer(200, VALID_PROFILE_RESPONSE, 0);
}

@After
Expand Down Expand Up @@ -140,7 +142,7 @@ public void checkErrorLabelOnInvalidEmailFormat() throws Exception {
// https://oppia.atlassian.net/browse/OPPIA-1130
public void checkShowsSubmitErrorMessageWhenServerError400Response() throws Exception {

startServer(400, ERROR_MESSAGE_BODY, 0);
enqueueResponse(400, ERROR_MESSAGE_BODY, 0);

try (ActivityScenario<EditProfileActivity> scenario = ActivityScenario.launch(EditProfileActivity.class)) {

Expand All @@ -159,7 +161,7 @@ public void checkShowsSubmitErrorMessageWhenServerError400Response() throws Exce
@Test
public void checkDataSavedWhenServerSuccessResponse() throws Exception {

startServer(200, null, 0);
enqueueResponse(200, null, 0);

try (ActivityScenario<EditProfileActivity> scenario = ActivityScenario.launch(EditProfileActivity.class)) {

Expand Down Expand Up @@ -189,7 +191,7 @@ public void checkDataSavedWhenServerSuccessResponse() throws Exception {
// https://oppia.atlassian.net/browse/OPPIA-1130
public void checkShowsSubmitErrorMessageWhenServerError500Response() throws Exception {

startServer(500, ERROR_MESSAGE_BODY, 0);
enqueueResponse(500, ERROR_MESSAGE_BODY, 0);

try (ActivityScenario<EditProfileActivity> scenario = ActivityScenario.launch(EditProfileActivity.class)) {

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package androidTestFiles.activities;

import android.Manifest;
import android.content.Context;
import android.content.SharedPreferences;

Expand All @@ -14,6 +13,7 @@
import org.digitalcampus.oppia.activity.SearchActivity;
import org.digitalcampus.oppia.activity.StartUpActivity;
import org.digitalcampus.oppia.activity.WelcomeActivity;
import org.digitalcampus.oppia.api.ApiEndpoint;
import org.digitalcampus.oppia.model.Badge;
import org.digitalcampus.oppia.model.CompleteCourse;
import org.digitalcampus.oppia.model.CompleteCourseProvider;
Expand All @@ -26,7 +26,6 @@
import org.digitalcampus.oppia.task.ParseCourseXMLTask;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
Expand All @@ -40,7 +39,6 @@
import androidTestFiles.utils.TestUtils;
import androidTestFiles.utils.UITestActionsUtils;
import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.Espresso;
import androidx.test.espresso.NoMatchingViewException;
import androidx.test.espresso.contrib.RecyclerViewActions;
import androidx.test.espresso.matcher.ViewMatchers;
Expand Down Expand Up @@ -69,6 +67,8 @@
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.when;
import static androidTestFiles.activities.EditProfileActivityTest.VALID_PROFILE_RESPONSE;
import static androidTestFiles.features.authentication.login.LoginUITest.VALID_LOGIN_RESPONSE;
import static androidTestFiles.utils.UITestActionsUtils.waitForView;

@RunWith(AndroidJUnit4.class)
Expand All @@ -88,6 +88,8 @@ public class MainActivityUITest extends MockedApiEndpointTest {
ArrayList<Points> pointList;
@Mock
ArrayList<Badge> badgeList;
@Mock
protected ApiEndpoint apiEndpoint;

@Mock
TagRepository tagRepository;
Expand Down Expand Up @@ -677,6 +679,8 @@ public void returnsToMainScreenWhenBackArrowButtonInCourseIndexScreenIsClicked()
@Test
public void showsEditProfileActivityOnMenuItemClick() throws Exception {

startServer(200, VALID_PROFILE_RESPONSE, 0);

if (!BuildConfig.MENU_ALLOW_EDIT_PROFILE) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.when;
import static androidTestFiles.activities.EditProfileActivityTest.VALID_PROFILE_RESPONSE;
import static androidTestFiles.utils.UITestActionsUtils.waitForView;
import static androidTestFiles.utils.matchers.EspressoTestsMatchers.withDrawable;
import static androidTestFiles.utils.matchers.RecyclerViewMatcher.withRecyclerView;
Expand Down Expand Up @@ -67,7 +68,6 @@ public class FlushCacheUITest extends MockedApiEndpointTest {
@Mock
TagRepository tagRepository;

private static final String COHORTS_5_AND_6 = "responses/cohorts/response_200_cohorts_5_6.json";

private void givenThereAreSomeCourses(int numberOfCourses) {

Expand Down Expand Up @@ -166,7 +166,7 @@ public void refreshCachedCoursesInTagSelectScreen() throws Exception {
}

@Test
public void testFlushUserCohorts() throws Exception {
public void testFlushUserData() throws Exception {
final CountDownLatch signal = new CountDownLatch(1);
Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
DbHelper dbHelper = DbHelper.getInstance(context);
Expand All @@ -179,15 +179,15 @@ public void testFlushUserCohorts() throws Exception {
assertEquals(Arrays.asList(1, 2), user.getCohorts());

// 2. Flush cache and retrieve mocked response with cohorts 5 and 6
startServer(200, COHORTS_5_AND_6, 0);
startServer(200, VALID_PROFILE_RESPONSE, 0);
FetchUserTask task = new FetchUserTask();
task.setListener(() -> signal.countDown());
task.updateLoggedUserProfile(context, apiEndpoint, user);
signal.await();

// 3. Assert User1 now belongs to cohorts 5 and 6
user = dbHelper.getUser(UserData.TEST_USER_1);
assertEquals(Arrays.asList(5, 6), user.getCohorts());
assertEquals(Arrays.asList(4, 5, 6), user.getCohorts());

} catch (UserNotFoundException e) {
e.printStackTrace();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.when;

import static androidTestFiles.activities.EditProfileActivityTest.VALID_PROFILE_RESPONSE;

import android.content.Context;
import android.util.Log;

Expand Down Expand Up @@ -40,6 +43,7 @@
import java.util.concurrent.ExecutionException;

import androidTestFiles.database.sampledata.UserData;
import androidTestFiles.utils.FileUtils;
import it.cosenonjaviste.daggermock.DaggerMockRule;

@RunWith(AndroidJUnit4.class)
Expand All @@ -51,7 +55,6 @@ public class UpdateUserProfileWorkerTest {
.getTargetContext()
.getApplicationContext())).set(
component -> {

App app =
(App) InstrumentationRegistry.getInstrumentation()
.getTargetContext()
Expand All @@ -67,7 +70,6 @@ public class UpdateUserProfileWorkerTest {
public void setUp() throws Exception {

context = InstrumentationRegistry.getInstrumentation().getTargetContext();

Configuration config = new Configuration.Builder()
// Set log level to Log.DEBUG to
// make it easier to see why tests failed
Expand All @@ -83,71 +85,75 @@ public void setUp() throws Exception {
}

@Test
public void testCohortsCheckerWorkerFinishSuccessfully() throws ExecutionException, InterruptedException {
public void testUpdateUserProfileWorkerFinishSuccessfully() throws ExecutionException, InterruptedException {
when(user.getUsername()).thenReturn(UserData.TEST_USER_1);

ListenableWorker testUserCohortsCheckerWorker = TestListenableWorkerBuilder.from(context, UpdateUserProfileWorker.class).build();
ListenableWorker.Result result = testUserCohortsCheckerWorker.startWork().get();
ListenableWorker testUpdateUserProfileWorker = TestListenableWorkerBuilder.from(context, UpdateUserProfileWorker.class).build();
ListenableWorker.Result result = testUpdateUserProfileWorker.startWork().get();
assertThat(result, is(ListenableWorker.Result.success()));
}

@Test
public void doesReturnFailureIfNoUserIsLoggedIn() throws Exception {
when(user.getUsername()).thenReturn(null);

ListenableWorker testUserCohortsCheckerWorker = TestListenableWorkerBuilder.from(context, UpdateUserProfileWorker.class).build();
ListenableWorker.Result result = testUserCohortsCheckerWorker.startWork().get();
ListenableWorker testUpdateUserProfileWorker = TestListenableWorkerBuilder.from(context, UpdateUserProfileWorker.class).build();
ListenableWorker.Result result = testUpdateUserProfileWorker.startWork().get();
Data expectedData = new Data.Builder().putString(UpdateUserProfileWorkerManager.RESULT_MESSAGE, context.getString(R.string.user_not_logged_in)).build();
assertThat(result, is(ListenableWorker.Result.failure(expectedData)));
}

@Test
public void updateUserCohortsIfResultIsSuccessful() throws Exception {
public void updateUserProfileIfResultIsSuccessful() throws Exception {
UserData.loadData(context);
// Initial cohorts of UserData.TEST_USER_1 = [1,2]
when(user.getUsername()).thenReturn(UserData.TEST_USER_1);
doCallRealMethod().when(user).setCohorts(any());
doCallRealMethod().when(user).updateFromJSON(any(), any());
doCallRealMethod().when(user).setCohortsFromJSONArray(any());
doCallRealMethod().when(user).getCohorts();

List<Integer> updatedCohorts = Arrays.asList(2,3,4);
UpdateUserProfileWorkerManager userCohortsChecksWorkerManager = spy(new UpdateUserProfileWorkerManager(context));
String profileResponse = FileUtils.getStringFromFile(
InstrumentationRegistry.getInstrumentation().getContext(), VALID_PROFILE_RESPONSE);
List<Integer> updatedCohorts = Arrays.asList(4,5,6);
UpdateUserProfileWorkerManager updateUserProfileWorkerManager = spy(new UpdateUserProfileWorkerManager(context));
doAnswer(invocationOnMock -> {
// Mock API result for returning a success response and the list of updated cohorts
BasicResult result = new BasicResult();
result.setSuccess(true);
result.setResultMessage(updatedCohorts.toString());
userCohortsChecksWorkerManager.apiRequestComplete(result);
result.setResultMessage(profileResponse);
updateUserProfileWorkerManager.apiRequestComplete(result);
return null;
}).when(userCohortsChecksWorkerManager).fetchUserProfile();
userCohortsChecksWorkerManager.setOnFinishListener(result -> assertThat(result, is(ListenableWorker.Result.success())));
userCohortsChecksWorkerManager.startChecks();
}).when(updateUserProfileWorkerManager).fetchUserProfile();
updateUserProfileWorkerManager.setOnFinishListener(result -> assertThat(result, is(ListenableWorker.Result.success())));
updateUserProfileWorkerManager.startChecks();

List<Integer> cohorts = DbHelper.getInstance(context).getUser(UserData.TEST_USER_1).getCohorts();
assertThat(cohorts, is(updatedCohorts));
}

@Test
public void dontUpdateUserCohortsIfUserIsNotLoggedIn() throws Exception {
public void dontUpdateUserProfileIfUserIsNotLoggedIn() throws Exception {
UserData.loadData(context);
when(user.getUsername()).thenReturn(null); // No user logged in
doCallRealMethod().when(user).setCohorts(any());
doCallRealMethod().when(user).getCohorts();

List<Integer> initialCohorts = Arrays.asList(1,2); // Cohorts of UserData.TEST_USER_1
List<Integer> updatedCohorts = Arrays.asList(2,3,4);
UpdateUserProfileWorkerManager userCohortsChecksWorkerManager = spy(new UpdateUserProfileWorkerManager(context));
UpdateUserProfileWorkerManager updateUserProfileWorkerManager = spy(new UpdateUserProfileWorkerManager(context));
doAnswer(invocationOnMock -> {
// Mock API result for returning a success response and the list of updated cohorts
BasicResult result = new BasicResult();
result.setSuccess(true);
result.setResultMessage(updatedCohorts.toString());
userCohortsChecksWorkerManager.apiRequestComplete(result);
updateUserProfileWorkerManager.apiRequestComplete(result);
return null;
}).when(userCohortsChecksWorkerManager).fetchUserProfile();
}).when(updateUserProfileWorkerManager).fetchUserProfile();

Data expectedData = new Data.Builder().putString(UpdateUserProfileWorkerManager.RESULT_MESSAGE, context.getString(R.string.user_not_logged_in)).build();
userCohortsChecksWorkerManager.setOnFinishListener(result -> assertThat(result, is(ListenableWorker.Result.failure(expectedData))));
userCohortsChecksWorkerManager.startChecks();
updateUserProfileWorkerManager.setOnFinishListener(result -> assertThat(result, is(ListenableWorker.Result.failure(expectedData))));
updateUserProfileWorkerManager.startChecks();

List<Integer> cohorts = DbHelper.getInstance(context).getUser(UserData.TEST_USER_1).getCohorts();
assertThat(cohorts, is(initialCohorts));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package androidTestFiles.utils.parent;

import android.content.Context;
import android.text.TextUtils;

import androidx.test.platform.app.InstrumentationRegistry;

Expand All @@ -20,7 +19,6 @@

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;

public abstract class MockedApiEndpointTest extends DaggerInjectMockUITest {
Expand All @@ -45,24 +43,7 @@ protected void startServer(int responseCode, String responseAsset, int timeoutDe

try {
mockServer = new MockWebServer();
MockResponse response = new MockResponse();
response.setResponseCode(responseCode);

if (!TextUtilsJava.isEmpty(responseAsset)) {

String responseBody = FileUtils.getStringFromFile(
InstrumentationRegistry.getInstrumentation().getContext(), /*BaseTest.PATH_TESTS + File.separator + */responseAsset);

response.setBody(responseBody);

} else {
response.setBody(EMPTY_JSON);
}

if (timeoutDelay > 0) {
response.setBodyDelay(timeoutDelay, TimeUnit.MILLISECONDS);
}

MockResponse response = createResponse(responseCode, responseAsset, timeoutDelay);
if (orderWhenManyRequests > 1) {
for (int i = 1; i < orderWhenManyRequests; i++) {
MockResponse responseUnused = new MockResponse();
Expand All @@ -79,7 +60,35 @@ protected void startServer(int responseCode, String responseAsset, int timeoutDe

when(apiEndpoint.getFullURL((Context) any(), anyString())).thenReturn(mockServer.url("").toString());

}

protected MockResponse createResponse(int responseCode, String responseAsset, int timeoutDelay) throws IOException {
MockResponse response = new MockResponse();
response.setResponseCode(responseCode);

if (!TextUtilsJava.isEmpty(responseAsset)) {
String responseBody = FileUtils.getStringFromFile(
InstrumentationRegistry.getInstrumentation().getContext(), /*BaseTest.PATH_TESTS + File.separator + */responseAsset);
response.setBody(responseBody);

} else {
response.setBody(EMPTY_JSON);
}

if (timeoutDelay > 0) {
response.setBodyDelay(timeoutDelay, TimeUnit.MILLISECONDS);
}
return response;
}

protected void enqueueResponse(int responseCode, String responseAsset, int timeoutDelay){
try {
MockResponse response = createResponse(responseCode, responseAsset, timeoutDelay);
mockServer.enqueue(response);

} catch (IOException e) {
e.printStackTrace();
}
}

public App getApp() {
Expand Down
Loading

0 comments on commit b441e9c

Please sign in to comment.