Search in sources :

Example 21 with DatafileConfig

use of com.optimizely.ab.android.shared.DatafileConfig in project android-sdk by optimizely.

the class DatafileClientTest method testLastModified.

/**
 * testLastModified - This is a test to see if given two projects, the last modified for datafile download is project specific.
 * Two URLs url1 and url2 are both datafile urls, url1 is requested from the data client twice, while url2 is only asked for once.
 * The first time the last modified is 0 and the second time, if it is non-zero, then it is the current last modified and a 304 is returned.
 *
 * @throws IOException
 */
@Test
public void testLastModified() throws IOException {
    final URL url1 = new URL(new DatafileConfig("1", null).getUrl());
    final URL url2 = new URL(new DatafileConfig("2", null).getUrl());
    HttpURLConnection urlConnection2 = mock(HttpURLConnection.class);
    when(urlConnection.getURL()).thenReturn(url1);
    when(urlConnection2.getURL()).thenReturn(url2);
    when(urlConnection.getLastModified()).thenReturn(0L);
    when(urlConnection2.getLastModified()).thenReturn(0L);
    when(client.openConnection(url1)).thenReturn(urlConnection);
    Answer<Integer> answer = new Answer<Integer>() {

        public Integer answer(InvocationOnMock invocation) throws Throwable {
            HttpURLConnection connection = (HttpURLConnection) invocation.getMock();
            URL url = connection.getURL();
            if (url == url1) {
                if (connection.getLastModified() == 0L) {
                    when(connection.getLastModified()).thenReturn(300L);
                    return 200;
                } else {
                    assertEquals(connection.getLastModified(), 300L);
                    return 304;
                }
            } else if (url == url2) {
                if (connection.getLastModified() == 0L) {
                    when(connection.getLastModified()).thenReturn(200L);
                    return 200;
                } else {
                    assertEquals(connection.getLastModified(), 200L);
                    return 304;
                }
            }
            // String string = (String) arguments[0];
            return 0;
        }
    };
    when(urlConnection.getResponseCode()).thenAnswer(answer);
    when(urlConnection2.getResponseCode()).thenAnswer(answer);
    when(client.openConnection(url2)).thenReturn(urlConnection2);
    when(client.readStream(urlConnection)).thenReturn("{}");
    when(client.readStream(urlConnection2)).thenReturn("{}");
    // first call returns the project file {}
    datafileClient.request(url1.toString());
    ArgumentCaptor<Client.Request> captor1 = ArgumentCaptor.forClass(Client.Request.class);
    ArgumentCaptor<Integer> captor2 = ArgumentCaptor.forClass(Integer.class);
    ArgumentCaptor<Integer> captor3 = ArgumentCaptor.forClass(Integer.class);
    verify(client).execute(captor1.capture(), captor2.capture(), captor3.capture());
    assertEquals(Integer.valueOf(DatafileClient.REQUEST_BACKOFF_TIMEOUT), captor2.getValue());
    assertEquals(Integer.valueOf(DatafileClient.REQUEST_RETRIES_POWER), captor3.getValue());
    Object response = captor1.getValue().execute();
    assertTrue(String.class.isInstance(response));
    assertEquals("{}", response);
    verify(logger).info("Requesting data file from {}", url1);
    verify(client).saveLastModified(urlConnection);
    verify(client).readStream(urlConnection);
    verify(urlConnection).disconnect();
    // second call returns 304 so the response is a empty string.
    datafileClient.request(url1.toString());
    captor1 = ArgumentCaptor.forClass(Client.Request.class);
    captor2 = ArgumentCaptor.forClass(Integer.class);
    captor3 = ArgumentCaptor.forClass(Integer.class);
    verify(client, times(2)).execute(captor1.capture(), captor2.capture(), captor3.capture());
    assertEquals(Integer.valueOf(DatafileClient.REQUEST_BACKOFF_TIMEOUT), captor2.getValue());
    assertEquals(Integer.valueOf(DatafileClient.REQUEST_RETRIES_POWER), captor3.getValue());
    response = captor1.getValue().execute();
    assertTrue(String.class.isInstance(response));
    assertEquals("", response);
    verify(logger).info("Data file has not been modified on the cdn");
    verify(urlConnection, times(2)).disconnect();
    datafileClient.request(url2.toString());
    captor1 = ArgumentCaptor.forClass(Client.Request.class);
    captor2 = ArgumentCaptor.forClass(Integer.class);
    captor3 = ArgumentCaptor.forClass(Integer.class);
    verify(client, times(3)).execute(captor1.capture(), captor2.capture(), captor3.capture());
    assertEquals(Integer.valueOf(DatafileClient.REQUEST_BACKOFF_TIMEOUT), captor2.getValue());
    assertEquals(Integer.valueOf(DatafileClient.REQUEST_RETRIES_POWER), captor3.getValue());
    response = captor1.getValue().execute();
    assertTrue(String.class.isInstance(response));
    assertEquals("{}", response);
    verify(logger, times(2)).info("Requesting data file from {}", url1);
    verify(client).saveLastModified(urlConnection2);
    verify(client).readStream(urlConnection2);
    verify(urlConnection2).disconnect();
}
Also used : DatafileConfig(com.optimizely.ab.android.shared.DatafileConfig) URL(java.net.URL) Answer(org.mockito.stubbing.Answer) HttpURLConnection(java.net.HttpURLConnection) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Client(com.optimizely.ab.android.shared.Client) Test(org.junit.Test)

Example 22 with DatafileConfig

use of com.optimizely.ab.android.shared.DatafileConfig in project android-sdk by optimizely.

the class DatafileServiceTest method testValidStart.

@Test
public void testValidStart() throws TimeoutException {
    Context context = InstrumentationRegistry.getInstrumentation().getTargetContext();
    Intent intent = new Intent(context, DatafileService.class);
    IBinder binder = null;
    int it = 0;
    while ((binder = mServiceRule.bindService(intent)) == null && it < MAX_ITERATION) {
        it++;
    }
    intent.putExtra(DatafileService.EXTRA_DATAFILE_CONFIG, new DatafileConfig("1", null).toJSONString());
    DatafileService datafileService = ((DatafileService.LocalBinder) binder).getService();
    Logger logger = mock(Logger.class);
    datafileService.logger = logger;
    int val = datafileService.onStartCommand(intent, 0, 0);
    assertEquals(val, START_FLAG_REDELIVERY);
}
Also used : Context(android.content.Context) IBinder(android.os.IBinder) Intent(android.content.Intent) DatafileConfig(com.optimizely.ab.android.shared.DatafileConfig) Logger(org.slf4j.Logger) Test(org.junit.Test)

Example 23 with DatafileConfig

use of com.optimizely.ab.android.shared.DatafileConfig in project android-sdk by optimizely.

the class DatafileServiceTest method testGetDatafileUrl.

@Test
public void testGetDatafileUrl() {
    // HARD-CODING link here to make sure we don't unintentionally mess up the datafile version
    // and url by accidentally changing those constants.
    // us to update this test.
    String datafileUrl = new DatafileConfig("1", null).getUrl();
    assertEquals("https://cdn.optimizely.com/json/1.json", datafileUrl);
}
Also used : DatafileConfig(com.optimizely.ab.android.shared.DatafileConfig) Test(org.junit.Test)

Example 24 with DatafileConfig

use of com.optimizely.ab.android.shared.DatafileConfig in project android-sdk by optimizely.

the class DatafileServiceTest method testIntentExtraData.

@Test
@Ignore
public void testIntentExtraData() {
    Context context = mock(Context.class);
    when(context.getPackageName()).thenReturn("com.optly");
    ServiceScheduler serviceScheduler = mock(ServiceScheduler.class);
    ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    ServiceScheduler.PendingIntentFactory pendingIntentFactory = new ServiceScheduler.PendingIntentFactory(context);
    Intent intent = new Intent(context, DatafileService.class);
    intent.putExtra(DatafileService.EXTRA_DATAFILE_CONFIG, new DatafileConfig("1", null).toJSONString());
    serviceScheduler.schedule(intent, TimeUnit.HOURS.toMillis(1L));
    try {
        executor.awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        fail("Timed out");
    }
    verify(serviceScheduler).schedule(captor.capture(), eq(TimeUnit.HOURS.toMillis(1L)));
    Intent intent2 = captor.getValue();
    assertTrue(intent2.getComponent().getShortClassName().contains("DatafileService"));
}
Also used : Context(android.content.Context) AlarmManager(android.app.AlarmManager) Intent(android.content.Intent) DatafileConfig(com.optimizely.ab.android.shared.DatafileConfig) ServiceScheduler(com.optimizely.ab.android.shared.ServiceScheduler) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 25 with DatafileConfig

use of com.optimizely.ab.android.shared.DatafileConfig in project android-sdk by optimizely.

the class DatafileWorkerTest method testDatafileFetch.

@Test
public void testDatafileFetch() {
    DatafileWorker worker = mockDatafileWorker(sdkKey);
    worker.datafileLoader = mock(DatafileLoader.class);
    ListenableWorker.Result result = worker.doWork();
    DatafileConfig datafileConfig = new DatafileConfig(null, sdkKey);
    String datafileUrl = datafileConfig.getUrl();
    DatafileCache datafileCache = new DatafileCache(datafileConfig.getKey(), new Cache(context, logger), logger);
    verify(worker.datafileLoader).getDatafile(eq(datafileUrl), eq(datafileCache), eq(null));
    // success
    assertThat(result, is(ListenableWorker.Result.success()));
}
Also used : ListenableWorker(androidx.work.ListenableWorker) DatafileConfig(com.optimizely.ab.android.shared.DatafileConfig) Matchers.anyString(org.mockito.Matchers.anyString) Cache(com.optimizely.ab.android.shared.Cache) Test(org.junit.Test)

Aggregations

DatafileConfig (com.optimizely.ab.android.shared.DatafileConfig)38 Test (org.junit.Test)34 Context (android.content.Context)15 URL (java.net.URL)8 Client (com.optimizely.ab.android.shared.Client)7 Cache (com.optimizely.ab.android.shared.Cache)5 SdkSuppress (androidx.test.filters.SdkSuppress)4 DatafileLoadedListener (com.optimizely.ab.android.datafile_handler.DatafileLoadedListener)4 Intent (android.content.Intent)2 Data (androidx.work.Data)2 DefaultDatafileHandler (com.optimizely.ab.android.datafile_handler.DefaultDatafileHandler)2 DefaultUserProfileService (com.optimizely.ab.android.user_profile.DefaultUserProfileService)2 UserProfileService (com.optimizely.ab.bucketing.UserProfileService)2 ArrayList (java.util.ArrayList)2 JSONException (org.json.JSONException)2 InvocationOnMock (org.mockito.invocation.InvocationOnMock)2 Logger (org.slf4j.Logger)2 AlarmManager (android.app.AlarmManager)1 IBinder (android.os.IBinder)1 NonNull (androidx.annotation.NonNull)1