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

Feature run test under different package #1834

Open
wants to merge 19 commits into
base: development
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
[submodule "EyeSeeTea-sdk"]
path = EyeSeeTea-sdk
url = https://github.com/EyeSeeTea/sdk.git
[submodule "DBFlow"]
path = DBFlow
url = https://github.com/EyeSeeTea/DBFlow.git
[submodule "bugshaker-android"]
path = bugshaker-android
url = https://github.com/EyeSeeTea/bugshaker-android.git
1 change: 1 addition & 0 deletions DBFlow
Submodule DBFlow added at 6f11f4
11 changes: 2 additions & 9 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -75,21 +75,13 @@ android {
}
buildTypes {

testBuildType "staging"

release {
buildConfigField "boolean", "databaseInMemory", "false"
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
buildConfigField "boolean", "databaseInMemory", "false"
debuggable true
}
staging {
initWith(buildTypes.debug)
buildConfigField "boolean", "databaseInMemory", "true"
}
}

//TODO This config is related to a known issue: http://stackoverflow.com/questions/20827885/android-studio-0-4-duplicate-files-copied-in-apk-meta-inf-license-txt
Expand Down Expand Up @@ -380,7 +372,8 @@ dependencies {
compile "com.squareup:javapoet:${libs.javapoetVersion}"

//DBFlow
apt "com.github.Raizlabs.DBFlow:dbflow-processor:${libs.dbFlowVersion}"
apt project(":dbflow-processor")

compile "com.github.Raizlabs.DBFlow:dbflow:${libs.dbFlowVersion}"
compile "com.github.Raizlabs.DBFlow:dbflow-core:${libs.dbFlowVersion}"
compile "com.github.Raizlabs.DBFlow:dbflow-sqlcipher:${libs.dbFlowVersion}"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.eyeseetea.malariacare;


import com.raizlabs.android.dbflow.config.DatabaseHolder;
import com.raizlabs.android.dbflow.config.EyeSeeTeaInMemoryGeneratedDatabaseHolder;

public class DatabaseHolderProviderStrategy implements
EyeSeeTeaApplication.IDatabaseHolderProviderStrategy {
@Override
public Class<? extends DatabaseHolder> provide() {
return EyeSeeTeaInMemoryGeneratedDatabaseHolder.class;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package org.eyeseetea.malariacare;

import android.support.test.InstrumentationRegistry;

import com.raizlabs.android.dbflow.config.FlowConfig;
import com.raizlabs.android.dbflow.config.FlowManager;

import org.eyeseetea.malariacare.data.database.AppDatabase;
import org.junit.rules.ExternalResource;

/*This test Rules creates a new clean instance of the DBFlow database per each @Test method
that you have, if you change anything in database(insert,delete and update),
it will be clean up when the next @Test methods runs.
For instance, if you have the following:

@Test
public void test1(){
QuestionDB question1 = new QuestionDB();
question1.save(); //After this line id_question
// It's going to be equals to 1
}

@Test
public void test2(){
QuestionDB question2 = new QuestionDB();
question2.save(); //After this line id_question
// it's still equals to 1
// The InMemoryDBFlowDataBase cleans up for you.
}
*/
public class InMemoryDBFlowDataBase extends ExternalResource {

public InMemoryDBFlowDataBase(){
before();
}

@Override
protected void before() {
FlowManager.destroy();
initDBFlowDB();
}

private void initDBFlowDB() {
DatabaseHolderProviderStrategy databaseStrategy = new DatabaseHolderProviderStrategy();
FlowConfig flowConfig = new FlowConfig
.Builder(InstrumentationRegistry.getContext())
.addDatabaseHolder(databaseStrategy.provide())
.build();
FlowManager.init(flowConfig);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import static android.content.Context.ACTIVITY_SERVICE;
import static android.support.test.InstrumentationRegistry.getInstrumentation;

import static android.support.test.InstrumentationRegistry.getContext;
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

Expand All @@ -13,6 +15,7 @@
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.test.InstrumentationRegistry;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

Expand All @@ -33,7 +36,7 @@

import java.util.List;

public class BaseActivityShould {
public class BaseActivityShould extends CommonActivityTestCode{

private Credentials previousOrganisationCredentials;
private Credentials previousCredentials;
Expand All @@ -42,7 +45,6 @@ public class BaseActivityShould {
private UserAccount previousUserAccount;

private final Object syncObject = new Object();

@Test
public void onLoginIntentShowLoginActivity() throws InterruptedException {
synchronized (syncObject) {
Expand All @@ -66,12 +68,15 @@ private void isLoginActivityShowing() {

ComponentName componentInfo = taskInfo.get(0).topActivity;
String activityName = componentInfo.getClassName();
assertThat(activityName, is(LoginActivity.class.getName()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
assertThat(activityName, is(LoginActivity.class.getName()));
} else {
assertThat(activityName, is(LoginActivity.class.getName()));
}
}

@Before
public void cleanUp() {
grantPermission();
savePreviousPreferences();
saveTestCredentialsAndProgram();
Intent intent = new Intent(PreferencesState.getInstance().getContext(),
Expand All @@ -91,25 +96,6 @@ public void cleanUp() {
@After
public void tearDown() {
restorePreferences();

}

public void grantPermission(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getInstrumentation().getUiAutomation().executeShellCommand(
"pm grant " + PreferencesState.getInstance().getContext().getPackageName()
+ " android.permission.READ_PHONE_STATE");
synchronized (syncObject) {
try {
syncObject.wait(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
getInstrumentation().getUiAutomation().executeShellCommand(
"pm grant " + PreferencesState.getInstance().getContext().getPackageName()
+ " android.permission.ACCESS_FINE_LOCATION");
}
}


Expand Down Expand Up @@ -139,15 +125,18 @@ private void savePreviousPreferences() {
}

private void saveTestCredentialsAndProgram() {
Context context = PreferencesState.getInstance().getContext();
//used to avoid override the real app preferences
Context context = InstrumentationRegistry.getContext();
//real app context, it is necessary to use getString() method
Context realAppContext = InstrumentationRegistry.getTargetContext();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(
context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(context.getString(R.string.web_service_url),
context.getString(R.string.ws_base_url));
editor.putString(realAppContext.getString(R.string.web_service_url),
realAppContext.getString(R.string.ws_base_url));
editor.commit();

Credentials credentials = new Credentials(context.getString(R.string.ws_base_url),
Credentials credentials = new Credentials(realAppContext.getString(R.string.ws_base_url),
"test", "test");
CredentialsLocalDataSource credentialsLocalDataSource = new CredentialsLocalDataSource();
credentialsLocalDataSource.saveLastValidCredentials(credentials);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package org.eyeseetea.malariacare;

import android.os.Build;

import org.junit.Before;

import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static android.support.test.InstrumentationRegistry.getTargetContext;

class CommonActivityTestCode {

@Before
public void grantPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
getInstrumentation().getUiAutomation().executeShellCommand(
"pm grant " + getTargetContext().getPackageName()
+ " android.permission.READ_PHONE_STATE");
getInstrumentation().getUiAutomation().executeShellCommand(
"pm grant " + getTargetContext().getPackageName()
+ " android.permission.ACCESS_FINE_LOCATION");
getInstrumentation().getUiAutomation().executeShellCommand(
"pm grant " + getTargetContext().getPackageName()
+ " android.permission.INTERNET");
getInstrumentation().getUiAutomation().executeShellCommand(
"pm grant " + getTargetContext().getPackageName()
+ " android.permission.ACCESS_NETWORK_STATE");
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,9 @@

import static junit.framework.Assert.assertEquals;

import static org.eyeseetea.malariacare.configurationimporter
.ConstantsMetadataConfigurationImporterTest.COUNTRIES_VERSION;
import static org.eyeseetea.malariacare.configurationimporter
.ConstantsMetadataConfigurationImporterTest.COUNTRIES_VERSION_V2;
import static org.eyeseetea.malariacare.configurationimporter
.ConstantsMetadataConfigurationImporterTest.TZ_CONFIG_ANDROID_2_0_JSON;
import static org.eyeseetea.malariacare.configurationimporter.ConstantsMetadataConfigurationImporterTest.COUNTRIES_VERSION;
import static org.eyeseetea.malariacare.configurationimporter.ConstantsMetadataConfigurationImporterTest.COUNTRIES_VERSION_V2;
import static org.eyeseetea.malariacare.configurationimporter.ConstantsMetadataConfigurationImporterTest.TZ_CONFIG_ANDROID_2_0_JSON;
import static org.junit.Assert.assertTrue;


Expand All @@ -23,18 +20,16 @@
import org.eyeseetea.malariacare.data.database.model.QuestionOptionDB;
import org.eyeseetea.malariacare.data.database.utils.PreferencesState;
import org.eyeseetea.malariacare.data.database.utils.Session;
import org.eyeseetea.malariacare.data.database.utils.populatedb.PopulateDB;
import org.eyeseetea.malariacare.data.server.CustomMockServer;
import org.eyeseetea.malariacare.data.sync.factory.ConverterFactory;
import org.eyeseetea.malariacare.data.sync.importer.metadata.configuration
.MetadataConfigurationApiClient;
import org.eyeseetea.malariacare.data.sync.importer.metadata.configuration
.MetadataConfigurationDBImporter;
import org.eyeseetea.malariacare.data.sync.importer.metadata.configuration.MetadataConfigurationApiClient;
import org.eyeseetea.malariacare.data.sync.importer.metadata.configuration.MetadataConfigurationDBImporter;
import org.eyeseetea.malariacare.domain.entity.Credentials;
import org.eyeseetea.malariacare.domain.entity.Program;
import org.eyeseetea.malariacare.network.retrofit.BasicAuthInterceptor;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

import java.io.IOException;
Expand All @@ -47,9 +42,11 @@ public class MetadataConfigurationDBImporterShould {

private final Program program = new Program("T_TZ", "low6qUS2wc9");

@Rule
public InMemoryDBFlowDataBase mInMemoryDBFlowDataBase = new InMemoryDBFlowDataBase();
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an example of using the JUnit rule that I mentioned in the PR.


@Before
public void setUp() throws Exception {
PopulateDB.wipeDataBase();
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now, I can delete this line, because the rule is keeping the state of the DB separated, between @Test

CredentialsReader credentialsReader = CredentialsReader.getInstance();
Context context = PreferencesState.getInstance().getContext();
Session.setCredentials(
Expand Down Expand Up @@ -129,7 +126,7 @@ private void whenConfigFilesAreParsed() throws Exception {
MetadataConfigurationDBImporter importer = new MetadataConfigurationDBImporter(
apiClient, ConverterFactory.getQuestionConverter()
);

importer.hasToUpdateMetadata(program);
importer.importMetadata(program);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
.MetadataConfigurationDataSourceFactory;
import org.eyeseetea.malariacare.domain.entity.Program;
import org.junit.Before;
import org.junit.Test;

public class RealMetadataConfigurationDBImporterShould {

Expand All @@ -29,7 +30,7 @@ public void setUp() throws Exception {

MetadataConfigurationDataSourceFactory metadataConfigurationDataSourceFactory =
new MetadataConfigurationDataSourceFactory(
InstrumentationRegistry.getTargetContext());
InstrumentationRegistry.getContext());
IMetadataConfigurationDataSource apiClient =
metadataConfigurationDataSourceFactory.getMetadataConfigurationDataSource();
importer = new MetadataConfigurationDBImporter(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package org.eyeseetea.malariacare;

import static android.content.Context.ACTIVITY_SERVICE;

import static android.support.test.InstrumentationRegistry.getContext;
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Build;
import android.support.test.InstrumentationRegistry;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import org.eyeseetea.malariacare.data.database.utils.PreferencesState;
import org.eyeseetea.malariacare.services.PushService;
import org.eyeseetea.malariacare.services.strategies.PushServiceStrategy;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

public class SettingsActivityShould extends CommonActivityTestCode{

private final Object syncObject = new Object();
@Test
public void onLoginIntentShowLoginActivity() throws InterruptedException {
synchronized (syncObject) {
syncObject.wait(2000);
}
sendIntentShowLogin();
synchronized (syncObject) {
syncObject.wait(1000);
}
isLoginActivityShowing();
}

private void isLoginActivityShowing() {
ActivityManager am =
(ActivityManager) PreferencesState.getInstance().getContext().getSystemService(
ACTIVITY_SERVICE);
// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);

Log.d("topActivity", BuildConfig.FLAVOR+ " " + BuildConfig.APPLICATION_ID +"CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());

ComponentName componentInfo = taskInfo.get(0).topActivity;
String activityName = componentInfo.getClassName();
assertThat(activityName, is(LoginActivity.class.getName()));
}

@Before
public void cleanUp() {
Intent intent = new Intent(PreferencesState.getInstance().getContext(),
SettingsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
EyeSeeTeaApplication.getInstance().startActivity(intent);
}


private void sendIntentShowLogin() {
Intent surveysIntent = new Intent(PushService.class.getName());
surveysIntent.putExtra(PushServiceStrategy.SERVICE_METHOD,
PushServiceStrategy.PUSH_MESSAGE);
surveysIntent.putExtra(PushServiceStrategy.SHOW_LOGIN, true);
LocalBroadcastManager.getInstance(
InstrumentationRegistry.getContext()).sendBroadcast(surveysIntent);
}


}
Loading