Skip to content
This repository has been archived by the owner on Apr 24, 2023. It is now read-only.

Commit

Permalink
Removes getting context inside of fields
Browse files Browse the repository at this point in the history
This is because, otherwise classes which use specific fields (ValiFieldPassword) are not testable, there is just method getString() which returns "string-*" for tests.
  • Loading branch information
Tomáš Mlynarič committed Jan 9, 2018
1 parent 6bedc86 commit abb3492
Show file tree
Hide file tree
Showing 16 changed files with 88 additions and 43 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

#### 1. Add gradle dependency
```groovy
compile 'com.mlykotom:valifi:1.1.7'
compile 'com.mlykotom:valifi:1.2.0'
```
#### 2. Setup project with data binding
``` groovy
Expand Down
2 changes: 1 addition & 1 deletion example-android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,6 @@ dependencies {
if(isLocalBuild) {
implementation project(':valifi')
} else {
implementation 'com.mlykotom:valifi:1.1.7'
implementation 'com.mlykotom:valifi:1.2.0'
}
}
3 changes: 2 additions & 1 deletion example-viewmodel/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ android {
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.0.2'
implementation 'com.android.support:design:27.0.2'
implementation 'eu.inloop:androidviewmodel:1.3.3'

debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.4'
Expand All @@ -37,6 +38,6 @@ dependencies {
if(isLocalBuild) {
implementation project(':valifi')
} else {
implementation 'com.mlykotom:valifi:1.1.7'
implementation 'com.mlykotom:valifi:1.2.0'
}
}
14 changes: 7 additions & 7 deletions valifi/build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
final VERSION_MAJOR = 1 // max two digits
final VERSION_MINOR = 1 // max two digits
final VERSION_PATCH = 7 // max two digits
final VERSION_MINOR = 2 // max two digits
final VERSION_PATCH = 0 // max two digits
final VERSION_BUILD = 0 // max three digits

apply plugin: 'com.android.library'
Expand Down Expand Up @@ -69,9 +69,9 @@ android {
}

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.android.support:design:27.0.2'
testCompile 'junit:junit:4.12'
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:design:27.0.2'
testImplementation 'junit:junit:4.12'
}

if(isLocalBuild) {
Expand All @@ -88,15 +88,15 @@ if(isLocalBuild) {
def compilePath = project.ext.publishedGroupId + ":" + project.ext.bintrayName + ":"

// Task for updating readme file for new version of library
task updateReadmeFile << {
task updateReadmeFile {
def readme = file('../README.md')

def updatedReadmeText = readme.text.replaceFirst("compile '" + compilePath + "[^']+'", "compile '" + compilePath + version + "'")
readme.write(updatedReadmeText)
}

// task for updating example gradle scripts so that it matches the latest version of library
task updateExamplesLibraryVersion << {
task updateExamplesLibraryVersion {
['example-android', 'example-viewmodel'].each {
def gradleScript = file("../${it}/build.gradle")
def updatedGradleText = gradleScript.text.replaceAll("compile '" + compilePath + "[^']+'", "compile '" + compilePath + version + "'")
Expand Down
26 changes: 20 additions & 6 deletions valifi/src/main/java/com/mlykotom/valifi/ValiFi.java
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,11 @@ public class ValiFi {
private final Context mAppContext;


private ValiFi(Context appContext, @NonNull ValiFiConfig config) {
/**
* @param appContext nullable for tests
* @param config configuration of valifi (patterns, errors)
*/
private ValiFi(@Nullable Context appContext, @NonNull ValiFiConfig config) {
mAppContext = appContext;
mParameters = config;
}
Expand Down Expand Up @@ -118,6 +122,15 @@ static long getAsyncValidationDelay() {
}


static ValiFi getInstance() {
if(ourInstance == null) {
throw new ValiFiException("ValiFi must be installed in Application.onCreate()!");
}

return ourInstance;
}


static Context getContext() {
if(getInstance().mAppContext == null) {
throw new ValiFiException("ValiFi was installed without Context!");
Expand All @@ -126,12 +139,13 @@ static Context getContext() {
}


static ValiFi getInstance() {
if(ourInstance == null) {
throw new ValiFiException("ValiFi must be installed in Application.onCreate()!");
static String getString(@StringRes int stringRes, Object... formatArgs) {
@Nullable Context context = getInstance().mAppContext;
if(context == null) {
// tests may be initialized without context, so will use placeholder string
return "string-" + stringRes;
}

return ourInstance;
return context.getString(stringRes, formatArgs);
}


Expand Down
18 changes: 12 additions & 6 deletions valifi/src/main/java/com/mlykotom/valifi/ValiFieldBase.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.mlykotom.valifi;

import android.content.Context;
import android.databinding.BaseObservable;
import android.databinding.Bindable;
import android.databinding.BindingAdapter;
Expand Down Expand Up @@ -410,7 +409,7 @@ public String getError() {
* @see #addVerifyFieldValidator(String, ValiFieldBase)
*/
public ValiFieldBase<ValueType> addVerifyFieldValidator(@StringRes int errorResource, final ValiFieldBase<ValueType> targetField) {
String errorMessage = getAppContext().getString(errorResource);
String errorMessage = getString(errorResource);
return addVerifyFieldValidator(errorMessage, targetField);
}

Expand Down Expand Up @@ -459,7 +458,7 @@ public ValiFieldBase<ValueType> addCustomValidator(PropertyValidator<ValueType>
* @see #addCustomValidator(String, PropertyValidator)
*/
public ValiFieldBase<ValueType> addCustomValidator(@StringRes int errorResource, PropertyValidator<ValueType> validator) {
String errorMessage = getAppContext().getString(errorResource);
String errorMessage = getString(errorResource);
return addCustomValidator(errorMessage, validator);
}

Expand Down Expand Up @@ -513,7 +512,7 @@ public ValiFieldBase<ValueType> addCustomAsyncValidator(AsyncPropertyValidator<V
* @see #addCustomAsyncValidator(String, AsyncPropertyValidator)
*/
public ValiFieldBase<ValueType> addCustomAsyncValidator(@StringRes int errorResource, AsyncPropertyValidator<ValueType> validator) {
String errorMessage = getAppContext().getString(errorResource);
String errorMessage = getString(errorResource);
return addCustomAsyncValidator(errorMessage, validator);
}

Expand Down Expand Up @@ -585,8 +584,15 @@ protected Pattern getPattern(@ValiFi.Builder.ValiFiPattern int field) {
}


protected Context getAppContext() {
return ValiFi.getContext();
/**
* Serves for getting strings in fields
*
* @param stringRes R.string.*
* @param formatArgs the same as in context.getString()
* @return formatted String | in case of tests, returns "string-*"
*/
protected String getString(@StringRes int stringRes, Object... formatArgs) {
return ValiFi.getString(stringRes, formatArgs);
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public ValiFieldCard() {

public ValiFieldCard(@Nullable Long defaultValue) {
super(defaultValue);
addSpecifiedValidator(getAppContext().getString(getErrorRes(ValiFi.Builder.ERROR_RES_CREDIT_CARD)));
addSpecifiedValidator(getString(getErrorRes(ValiFi.Builder.ERROR_RES_CREDIT_CARD)));
}


Expand All @@ -33,7 +33,7 @@ public ValiFieldCard(@StringRes int errorResource) {

public ValiFieldCard(@Nullable Long defaultValue, @StringRes int errorResource) {
super(defaultValue);
addNotEmptyValidator(getAppContext().getString(errorResource));
addNotEmptyValidator(getString(errorResource));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public ValiFieldDate addOlderThanYearsValidator(int amount) {


public ValiFieldDate addOlderThanValidator(@StringRes int errorResource, int calendarField, int amount) {
String errorMessage = getAppContext().getString(errorResource, amount);
String errorMessage = getString(errorResource, amount);
return addOlderThanValidator(errorMessage, calendarField, amount);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public ValiFieldEmail() {

public ValiFieldEmail(@Nullable String defaultValue) {
super(defaultValue);
addEmailValidator(getAppContext().getString(getErrorRes(ValiFi.Builder.ERROR_RES_EMAIL)));
addEmailValidator(getString(getErrorRes(ValiFi.Builder.ERROR_RES_EMAIL)));
}


Expand All @@ -26,7 +26,7 @@ public ValiFieldEmail(@StringRes int errorResource) {

public ValiFieldEmail(@Nullable String defaultValue, @StringRes int errorResource) {
super(defaultValue);
addEmailValidator(getAppContext().getString(errorResource));
addEmailValidator(getString(errorResource));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public ValiFieldPassword() {

public ValiFieldPassword(@Nullable String defaultValue) {
super(defaultValue);
addPasswordValidator(getAppContext().getString(getErrorRes(ValiFi.Builder.ERROR_RES_PASSWORD)));
addPasswordValidator(getString(getErrorRes(ValiFi.Builder.ERROR_RES_PASSWORD)));
}


Expand All @@ -25,7 +25,7 @@ public ValiFieldPassword(@StringRes int errorResource) {

public ValiFieldPassword(@Nullable String defaultValue, @StringRes int errorResource) {
super(defaultValue);
addPasswordValidator(getAppContext().getString(errorResource));
addPasswordValidator(getString(errorResource));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public ValiFieldPhone() {

public ValiFieldPhone(@Nullable String defaultValue) {
super(defaultValue);
addPhoneValidator(getAppContext().getString(getErrorRes(ValiFi.Builder.ERROR_RES_PHONE)));
addPhoneValidator(getString(getErrorRes(ValiFi.Builder.ERROR_RES_PHONE)));
}


Expand All @@ -25,7 +25,7 @@ public ValiFieldPhone(@StringRes int errorResource) {

public ValiFieldPhone(@Nullable String defaultValue, @StringRes int errorResource) {
super(defaultValue);
addPhoneValidator(getAppContext().getString(errorResource));
addPhoneValidator(getString(errorResource));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public ValiFieldText setEmptyAllowed(boolean isEmptyAllowed) {
* @see #addPatternValidator(String, Pattern)
*/
public ValiFieldText addPatternValidator(@StringRes int errorResource, final Pattern pattern) {
String errorMessage = getAppContext().getString(errorResource);
String errorMessage = getString(errorResource);
return addPatternValidator(errorMessage, pattern);
}

Expand Down Expand Up @@ -118,7 +118,7 @@ public ValiFieldText addNotEmptyValidator() {


public ValiFieldText addNotEmptyValidator(@StringRes int errorResource) {
String errorMessage = getAppContext().getString(errorResource);
String errorMessage = getString(errorResource);
return addNotEmptyValidator(errorMessage);
}

Expand Down Expand Up @@ -147,7 +147,7 @@ public ValiFieldText addMinLengthValidator(int minLength) {


public ValiFieldText addMinLengthValidator(@StringRes int errorResource, int minLength) {
String errorMessage = getAppContext().getString(errorResource, minLength);
String errorMessage = getString(errorResource, minLength);
return addMinLengthValidator(errorMessage, minLength);
}

Expand All @@ -171,7 +171,7 @@ public ValiFieldText addExactLengthValidator(int exactLength) {


public ValiFieldText addExactLengthValidator(@StringRes int errorResource, int exactLength) {
String errorMessage = getAppContext().getString(errorResource, exactLength);
String errorMessage = getString(errorResource, exactLength);
return addExactLengthValidator(errorMessage, exactLength);
}

Expand All @@ -190,7 +190,7 @@ public ValiFieldText addMaxLengthValidator(int maxLength) {


public ValiFieldText addMaxLengthValidator(@StringRes int errorResource, int maxLength) {
String errorMessage = getAppContext().getString(errorResource, maxLength);
String errorMessage = getString(errorResource, maxLength);
return addMaxLengthValidator(errorMessage, maxLength);
}

Expand All @@ -209,7 +209,7 @@ public ValiFieldText addRangeLengthValidator(int minLength, int maxLength) {


public ValiFieldText addRangeLengthValidator(@StringRes int errorResource, int minLength, int maxLength) {
String errorMessage = getAppContext().getString(errorResource, minLength, maxLength);
String errorMessage = getString(errorResource, minLength, maxLength);
return addRangeLengthValidator(errorMessage, minLength, maxLength);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public ValiFieldUsername() {

public ValiFieldUsername(@Nullable String defaultValue) {
super(defaultValue);
addUsernameValidator(getAppContext().getString(getErrorRes(ValiFi.Builder.ERROR_RES_USERNAME)));
addUsernameValidator(getString(getErrorRes(ValiFi.Builder.ERROR_RES_USERNAME)));
}


Expand All @@ -25,7 +25,7 @@ public ValiFieldUsername(@StringRes int errorResource) {

public ValiFieldUsername(@Nullable String defaultValue, @StringRes int errorResource) {
super(defaultValue);
addUsernameValidator(getAppContext().getString(errorResource));
addUsernameValidator(getString(errorResource));
}


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ public ValiFieldNumber<NumberType> addNumberValidator(@Nullable NumberValidator<


public ValiFieldNumber<NumberType> addNumberValidator(@StringRes int errorResource, @Nullable NumberValidator<NumberType> validator) {
String errorMessage = getAppContext().getString(errorResource);
String errorMessage = getString(errorResource);
return addNumberValidator(errorMessage, validator);
}

Expand Down
7 changes: 4 additions & 3 deletions valifi/src/test/java/com/mlykotom/valifi/ValiFiTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.junit.Test;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;


Expand All @@ -32,13 +33,13 @@ public void prepareField() {
}


@Test(expected = ValiFiException.class)
@Test
public void checkLibraryInstalled() {
mField.getAppContext();
assertThat(ValiFi.getInstance(), notNullValue());
}


@Test(expected = ValiFiException.class)
@Test
public void checkLibraryInstalledByAddingValidator() {
mField.addCustomValidator(R.string.validation_error_email, new ValiFieldBase.PropertyValidator<String>() {
@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,27 @@
package com.mlykotom.valifi.fields;

import com.mlykotom.valifi.ValiFiTest;

import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;


public class ValiFieldPasswordTest {
ValiFieldPassword field;


@Before
public void setup() {
ValiFiTest.installWithoutContext();
field = new ValiFieldPassword();
}


@Test
public void initializationSucces() {
assertThat(field.isValid(), not(true));
}
}

0 comments on commit abb3492

Please sign in to comment.