package com.braintreepayments.demo.test.utilities;

import android.Manifest.permission;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.widget.Spinner;

import static android.support.test.InstrumentationRegistry.getTargetContext;
import static com.lukekorth.deviceautomator.AutomatorAction.click;
import static com.lukekorth.deviceautomator.AutomatorAssertion.text;
import static com.lukekorth.deviceautomator.DeviceAutomator.onDevice;
import static com.lukekorth.deviceautomator.UiObjectMatcher.withClass;
import static com.lukekorth.deviceautomator.UiObjectMatcher.withText;
import static org.hamcrest.CoreMatchers.equalTo;

public class TestHelper {

    public void setup() {
        PreferenceManager.getDefaultSharedPreferences(getTargetContext())
                .edit()
                .clear()
                .commit();
        onDevice().onHomeScreen().launchApp("com.braintreepayments.demo");
        enableStoragePermission();
        ensureEnvironmentIs("Sandbox");
    }

    private static void ensureEnvironmentIs(String environment) {
        try {
            onDevice(withText(environment)).check(text(equalTo(environment)));
        } catch (RuntimeException e) {
            onDevice(withClass(Spinner.class)).perform(click());
            onDevice(withText(environment)).perform(click());
            onDevice(withText(environment)).check(text(equalTo(environment)));
        }
    }

    private static void enableStoragePermission() {
        if (ContextCompat.checkSelfPermission(getTargetContext(), permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            try {
                onDevice(withText("Allow")).perform(click());
            } catch (RuntimeException ignored) {}
        }
    }
}

@@ -81,16 +81,48 @@
 ission;%0A
+import android.content.Context;%0A
 import a
@@ -804,24 +804,104 @@
 d setup() %7B%0A
+        clearPreference(%22BraintreeApi%22);%0A        clearPreference(%22PayPalOTC%22);%0A%0A
         Pref
@@ -962,16 +962,16 @@
 text())%0A
-
         
@@ -1034,24 +1034,25 @@
  .commit();%0A
+%0A
         onDe
@@ -1149,16 +1149,16 @@
 sion();%0A
-
         
@@ -1188,32 +1188,251 @@
 ndbox%22);%0A    %7D%0A%0A
+    private void clearPreference(String preference) %7B%0A        getTargetContext().getSharedPreferences(preference, Context.MODE_PRIVATE)%0A                .edit()%0A                .clear()%0A                .commit();%0A    %7D%0A%0A
     private stat

Clear all preferences before demo app tests