package org.robolectric.util;

import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.TestRunners;

import java.io.File;
import java.io.FileOutputStream;

import static org.fest.assertions.api.Assertions.assertThat;

@RunWith(TestRunners.WithDefaults.class)
public class SQLiteLibraryLoaderTest {

  @Before
  public void deleteExtractedLibrary() {
    SQLiteLibraryLoader.getNativeLibraryPath().delete();
    SQLiteLibraryLoader.mustReload();
  }

  @Test
  public void shouldExtractNativeLibrary() {
    File extractedPath = SQLiteLibraryLoader.getNativeLibraryPath();
    assertThat(extractedPath).doesNotExist();
    SQLiteLibraryLoader.load();
    assertThat(extractedPath).exists();
  }

  @Test
  public void shouldNotRewriteExistingLibraryIfThereAreNoChanges() throws Exception{
    SQLiteLibraryLoader.load();
    File extractedPath = SQLiteLibraryLoader.getNativeLibraryPath();
    assertThat(extractedPath).exists();
    long time = extractedPath.lastModified();

    Thread.sleep(2);
    SQLiteLibraryLoader.mustReload();
    SQLiteLibraryLoader.load();
    extractedPath = SQLiteLibraryLoader.getNativeLibraryPath();
    assertThat(extractedPath.lastModified()).isEqualTo(time);
  }

  @Test
  public void shouldRewriteExistingLibraryIfThereAreChanges() throws Exception {
    IOUtils.copy(IOUtils.toInputStream("changed"), new FileOutputStream(SQLiteLibraryLoader.getNativeLibraryPath()));
    long firstSize = SQLiteLibraryLoader.getNativeLibraryPath().length();

    SQLiteLibraryLoader.load();
    File extractedPath = SQLiteLibraryLoader.getNativeLibraryPath();
    assertThat(extractedPath).exists();
    assertThat(extractedPath.length()).isGreaterThan(firstSize);
  }

}

@@ -1012,24 +1012,58 @@
 ();%0A
+%0A
     
-long time = 
+final long resetTime = 1234L;%0A    assertThat(
 extr
@@ -1064,33 +1064,36 @@
 t(extractedPath.
-l
+setL
 astModified();%0A%0A
@@ -1092,33 +1092,223 @@
 ied(
-);%0A%0A    Thread.sleep(2
+resetTime)).describedAs(%22Cannot reset modification date%22).isTrue();%0A    // actual time may be truncated to seconds%0A    long time = extractedPath.lastModified();%0A    assertThat(time).isLessThanOrEqualTo(resetTime
 );%0A
+%0A
     

remove sleep from test