aboutsummaryrefslogtreecommitdiff
path: root/robolectric/src/test/java/org/robolectric/shadows/ShadowContextTest.java
blob: 51f71d358faa2a20aff5e46aef1008b71a09f25f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.P;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.R;
import org.robolectric.Robolectric;
import org.robolectric.annotation.Config;

/**
 * Tests of the {@link ShadowContextImpl} class
 */
@RunWith(AndroidJUnit4.class)
public class ShadowContextTest {
  private final Context context = ApplicationProvider.getApplicationContext();

  @Test
  public void createConfigurationContext() {
    Configuration configuration = new Configuration(context.getResources().getConfiguration());
    configuration.mcc = 234;

    Context configurationContext = context.createConfigurationContext(configuration);

    assertThat(configurationContext).isNotNull();
  }

  @Test
  @Config(minSdk = VERSION_CODES.O)
  public void startForegroundService() {
    Intent intent = new Intent().setPackage("dummy.package");
    context.startForegroundService(intent);
    assertThat(ShadowApplication.getInstance().getNextStartedService()).isEqualTo(intent);
  }

  @Test
  public void shouldGetApplicationDataDirectory() {
    File dataDir = context.getDir("data", Context.MODE_PRIVATE);
    assertThat(dataDir.exists()).isTrue();
  }

  @Test
  public void shouldCreateIfDoesNotExistAndGetApplicationDataDirectory() throws Exception {
    File dataDir = new File(context.getPackageManager()
        .getPackageInfo("org.robolectric", 0).applicationInfo.dataDir, "data");

    assertThat(dataDir.exists()).isFalse();

    dataDir = context.getDir("data", Context.MODE_PRIVATE);
    assertThat(dataDir.exists()).isTrue();
  }

  @Test
  public void shouldStubThemeStuff() {
    assertThat(context.obtainStyledAttributes(new int[0])).isNotNull();
    assertThat(context.obtainStyledAttributes(0, new int[0])).isNotNull();
    assertThat(context.obtainStyledAttributes(null, new int[0])).isNotNull();
    assertThat(context.obtainStyledAttributes(null, new int[0], 0, 0)).isNotNull();
  }

  @Test
  public void getCacheDir_shouldCreateDirectory() {
    assertThat(context.getCacheDir().exists()).isTrue();
  }

  @Test
  public void getExternalCacheDir_shouldCreateDirectory() {
    assertThat(context.getExternalCacheDir().exists()).isTrue();
  }

  @Test
  public void shouldWriteToCacheDir() throws Exception {
    assertThat(context.getCacheDir()).isNotNull();
    File cacheTest = new File(context.getCacheDir(), "__test__");

    assertThat(cacheTest.getAbsolutePath())
      .startsWith(System.getProperty("java.io.tmpdir"));
    assertThat(cacheTest.getAbsolutePath())
        .endsWith(File.separator + "__test__");

    try (FileOutputStream fos = new FileOutputStream(cacheTest)) {
      fos.write("test".getBytes(UTF_8));
    }
    assertThat(cacheTest.exists()).isTrue();
  }

  @Test
  public void shouldWriteToExternalCacheDir() throws Exception {
    assertThat(context.getExternalCacheDir()).isNotNull();
    File cacheTest = new File(context.getExternalCacheDir(), "__test__");

    assertThat(cacheTest.getAbsolutePath())
      .startsWith(System.getProperty("java.io.tmpdir"));
    assertThat(cacheTest.getAbsolutePath())
      .endsWith(File.separator + "__test__");

    try (FileOutputStream fos = new FileOutputStream(cacheTest)) {
      fos.write("test".getBytes(UTF_8));
    }

    assertThat(cacheTest.exists()).isTrue();
  }

  @Test
  public void getExternalCacheDirs_nonEmpty() {
    assertThat(context.getExternalCacheDirs()).isNotEmpty();
  }

  @Test
  public void getExternalCacheDirs_createsDirectories() {
    File[] externalCacheDirs = context.getExternalCacheDirs();
    for (File d : externalCacheDirs) {
      assertThat(d.exists()).isTrue();
    }
  }

  @Test
  public void getFilesDir_shouldCreateDirectory() {
    assertThat(context.getFilesDir().exists()).isTrue();
  }

  @Test
  public void fileList() {
    assertThat(context.fileList()).isEqualTo(context.getFilesDir().list());
  }

  @Test
  public void getExternalFilesDir_shouldCreateDirectory() {
    assertThat(context.getExternalFilesDir(null).exists()).isTrue();
  }

  @Test
  public void getExternalFilesDir_shouldCreateNamedDirectory() {
    File f = context.getExternalFilesDir("__test__");
    assertThat(f.exists()).isTrue();
    assertThat(f.getAbsolutePath()).endsWith("__test__");
  }

  @Test
  public void getDatabasePath_shouldAllowAbsolutePaths() {
      String testDbName;

      if (System.getProperty("os.name").startsWith("Windows")) {
        testDbName = "C:\\absolute\\full\\path\\to\\db\\abc.db";
      } else {
        testDbName = "/absolute/full/path/to/db/abc.db";
      }
      File dbFile = context.getDatabasePath(testDbName);
      assertThat(dbFile).isEqualTo(new File(testDbName));
  }

  @Test
  public void openFileInput_shouldReturnAFileInputStream() throws Exception {
    String fileContents = "blah";

    File file = new File(context.getFilesDir(), "__test__");
    try (Writer fileWriter = Files.newBufferedWriter(file.toPath(), UTF_8)) {
      fileWriter.write(fileContents);
    }

    try (FileInputStream fileInputStream = context.openFileInput("__test__")) {
      byte[] bytes = new byte[fileContents.length()];
      fileInputStream.read(bytes);
      assertThat(bytes).isEqualTo(fileContents.getBytes(UTF_8));
    }
  }

  @Test(expected = IllegalArgumentException.class)
  public void openFileInput_shouldNotAcceptPathsWithSeparatorCharacters() throws Exception {
    try (FileInputStream fileInputStream =
        context.openFileInput("data" + File.separator + "test")) {}
  }

  @Test
  public void openFileOutput_shouldReturnAFileOutputStream() throws Exception {
    File file = new File("__test__");
    String fileContents = "blah";
    try (FileOutputStream fileOutputStream =
        context.openFileOutput("__test__", Context.MODE_PRIVATE)) {
      fileOutputStream.write(fileContents.getBytes(UTF_8));
    }
    try (FileInputStream fileInputStream = new FileInputStream(new File(context.getFilesDir(), file.getName()))) {
      byte[] readBuffer = new byte[fileContents.length()];
      fileInputStream.read(readBuffer);
      assertThat(new String(readBuffer, UTF_8)).isEqualTo(fileContents);
    }
  }

  @Test(expected = IllegalArgumentException.class)
  public void openFileOutput_shouldNotAcceptPathsWithSeparatorCharacters() throws Exception {
    try (FileOutputStream fos =
        context.openFileOutput(
            File.separator + "data" + File.separator + "test" + File.separator + "hi", 0)) {}
  }

  @Test
  public void openFileOutput_shouldAppendData() throws Exception {
    File file = new File("__test__");
    String initialFileContents = "foo";
    String appendedFileContents = "bar";
    String finalFileContents = initialFileContents + appendedFileContents;
    try (FileOutputStream fileOutputStream =
        context.openFileOutput("__test__", Context.MODE_APPEND)) {
      fileOutputStream.write(initialFileContents.getBytes(UTF_8));
    }
    try (FileOutputStream fileOutputStream =
        context.openFileOutput("__test__", Context.MODE_APPEND)) {
      fileOutputStream.write(appendedFileContents.getBytes(UTF_8));
    }
    try (FileInputStream fileInputStream = new FileInputStream(new File(context.getFilesDir(), file.getName()))) {
      byte[] readBuffer = new byte[finalFileContents.length()];
      fileInputStream.read(readBuffer);
      assertThat(new String(readBuffer, UTF_8)).isEqualTo(finalFileContents);
    }
  }

  @Test
  public void openFileOutput_shouldOverwriteData() throws Exception {
    File file = new File("__test__");
    String initialFileContents = "foo";
    String newFileContents = "bar";
    try (FileOutputStream fileOutputStream = context.openFileOutput("__test__", 0)) {
      fileOutputStream.write(initialFileContents.getBytes(UTF_8));
    }
    try (FileOutputStream fileOutputStream = context.openFileOutput("__test__", 0)) {
      fileOutputStream.write(newFileContents.getBytes(UTF_8));
    }
    try (FileInputStream fileInputStream = new FileInputStream(new File(context.getFilesDir(), file.getName()))) {
      byte[] readBuffer = new byte[newFileContents.length()];
      fileInputStream.read(readBuffer);
      assertThat(new String(readBuffer, UTF_8)).isEqualTo(newFileContents);
    }
  }

  @Test
  public void deleteFile_shouldReturnTrue() throws IOException {
    File filesDir = context.getFilesDir();
    File file = new File(filesDir, "test.txt");
    boolean successfully = file.createNewFile();
    assertThat(successfully).isTrue();
    successfully = context.deleteFile(file.getName());
    assertThat(successfully).isTrue();
  }

  @Test
  public void deleteFile_shouldReturnFalse() {
    File filesDir = context.getFilesDir();
    File file = new File(filesDir, "test.txt");
    boolean successfully = context.deleteFile(file.getName());
    assertThat(successfully).isFalse();
  }

  @Test
  public void obtainStyledAttributes_shouldExtractAttributesFromAttributeSet() {
    AttributeSet roboAttributeSet = Robolectric.buildAttributeSet()
        .addAttribute(R.attr.itemType, "ungulate")
        .addAttribute(R.attr.scrollBars, "horizontal|vertical")
        .addAttribute(R.attr.quitKeyCombo, "^q")
        .addAttribute(R.attr.aspectRatio, "1.5")
        .addAttribute(R.attr.aspectRatioEnabled, "true")
        .build();

    TypedArray a = context.obtainStyledAttributes(roboAttributeSet, R.styleable.CustomView);
    assertThat(a.getInt(R.styleable.CustomView_itemType, -1234)).isEqualTo(1 /* ungulate */);
    assertThat(a.getInt(R.styleable.CustomView_scrollBars, -1234)).isEqualTo(0x300);
    assertThat(a.getString(R.styleable.CustomView_quitKeyCombo)).isEqualTo("^q");
    assertThat(a.getText(R.styleable.CustomView_quitKeyCombo).toString()).isEqualTo("^q");
    assertThat(a.getFloat(R.styleable.CustomView_aspectRatio, 1f)).isEqualTo(1.5f);
    assertThat(a.getBoolean(R.styleable.CustomView_aspectRatioEnabled, false)).isTrue();

    TypedArray typedArray = context.obtainStyledAttributes(roboAttributeSet, new int[]{R.attr.quitKeyCombo, R.attr.itemType});
    assertThat(typedArray.getString(0)).isEqualTo("^q");
    assertThat(typedArray.getInt(1, -1234)).isEqualTo(1 /* ungulate */);
  }

  @Test
  @Config(minSdk = P)
  public void getWifiRttService() {
    assertThat(context.getSystemService(Context.WIFI_RTT_RANGING_SERVICE)).isNotNull();
  }
}