summaryrefslogtreecommitdiff
path: root/app/src/test/java/se/leap/bitmaskclient/testutils/MockHelper.java
blob: c2362c7b93d2594bfbd97652cba20f3666d594db (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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package se.leap.bitmaskclient.testutils;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Parcelable;
import android.os.ResultReceiver;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import org.json.JSONException;
import org.json.JSONObject;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.io.IOException;
import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.OkHttpClient;
import se.leap.bitmaskclient.ConfigHelper;
import se.leap.bitmaskclient.Constants;
import se.leap.bitmaskclient.OkHttpClientGenerator;
import se.leap.bitmaskclient.Provider;
import se.leap.bitmaskclient.R;
import se.leap.bitmaskclient.testutils.BackendMockResponses.BackendMockProvider;
import se.leap.bitmaskclient.testutils.matchers.BundleMatcher;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static se.leap.bitmaskclient.Constants.PROVIDER_PRIVATE_KEY;
import static se.leap.bitmaskclient.Constants.PROVIDER_VPN_CERTIFICATE;

/**
 * Created by cyberta on 29.01.18.
 */

public class MockHelper {
    @NonNull
    public static Bundle mockBundle() {
        final Map<String, Boolean> fakeBooleanBundle = new HashMap<>();
        final Map<String, String> fakeStringBundle = new HashMap<>();
        final Map<String, Integer> fakeIntBundle = new HashMap<>();
        final Map<String, Parcelable> fakeParcelableBundle = new HashMap<>();

        Bundle bundle = mock(Bundle.class);

        //mock String values in Bundle
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                String value = ((String) arguments[1]);
                fakeStringBundle.put(key, value);
                return null;
            }
        }).when(bundle).putString(anyString(), anyString());
        when(bundle.getString(anyString())).thenAnswer(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                return fakeStringBundle.get(key);
            }
        });

        //mock Boolean values in Bundle
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                Boolean value = ((boolean) arguments[1]);
                fakeBooleanBundle.put(key, value);
                return null;
            }
        }).when(bundle).putBoolean(anyString(), anyBoolean());
        when(bundle.getBoolean(anyString())).thenAnswer(new Answer<Boolean>() {
            @Override
            public Boolean answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                return fakeBooleanBundle.get(key);
            }
        });

        //mock Integer values in Bundle
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                Integer value = ((int) arguments[1]);
                fakeIntBundle.put(key, value);
                return null;
            }
        }).when(bundle).putInt(anyString(), anyInt());
        when(bundle.getInt(anyString())).thenAnswer(new Answer<Integer>() {
            @Override
            public Integer answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                return fakeIntBundle.get(key);
            }
        });

        //mock Parcelable values in Bundle
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                Parcelable value = ((Parcelable) arguments[1]);
                fakeParcelableBundle.put(key, value);
                return null;
            }
        }).when(bundle).putParcelable(anyString(), any(Parcelable.class));
        when(bundle.getParcelable(anyString())).thenAnswer(new Answer<Parcelable>() {
            @Override
            public Parcelable answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                return fakeParcelableBundle.get(key);
            }
        });

        //mock get
        when(bundle.get(anyString())).thenAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                if (fakeBooleanBundle.containsKey(key)) {
                    return fakeBooleanBundle.get(key);
                } else if (fakeIntBundle.containsKey(key)) {
                    return fakeIntBundle.get(key);
                } else if (fakeStringBundle.containsKey(key)) {
                    return fakeStringBundle.get(key);
                } else {
                    return fakeParcelableBundle.get(key);
                }
            }
        });

        //mock getKeySet
       when(bundle.keySet()).thenAnswer(new Answer<Set<String>>() {
           @Override
           public Set<String> answer(InvocationOnMock invocation) throws Throwable {
               //this whole approach as a drawback:
               //you should not add the same keys for values of different types
               HashSet<String> keys = new HashSet<String>();
               keys.addAll(fakeBooleanBundle.keySet());
               keys.addAll(fakeIntBundle.keySet());
               keys.addAll(fakeStringBundle.keySet());
               keys.addAll(fakeParcelableBundle.keySet());
               return keys;
           }
        });

        //mock containsKey
        when(bundle.containsKey(anyString())).thenAnswer(new Answer<Boolean>() {
            @Override
            public Boolean answer(InvocationOnMock invocation) throws Throwable {
                String key = (String) invocation.getArguments()[0];
                return fakeBooleanBundle.containsKey(key) ||
                        fakeStringBundle.containsKey(key) ||
                        fakeIntBundle.containsKey(key) ||
                        fakeParcelableBundle.containsKey(key);
            }
        });

        return bundle;
    }

    public static Intent mockIntent() {
        Intent intent = mock(Intent.class);
        final String[] action = new String[1];
        final Map<String, Object> fakeExtras = new HashMap<>();
        final List<String> categories = new ArrayList<>();


        //mock Action in intent
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                action[0] = ((String) arguments[0]);
                return null;
            }
        }).when(intent).setAction(anyString());
        when(intent.getAction()).thenAnswer(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                return action[0];
            }
        });

        //mock Bundle in intent extras
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                Bundle value = ((Bundle) arguments[1]);
                fakeExtras.put(key, value);
                return null;
            }
        }).when(intent).putExtra(anyString(), any(Bundle.class));
        when(intent.getBundleExtra(anyString())).thenAnswer(new Answer<Bundle>() {
            @Override
            public Bundle answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                return (Bundle) fakeExtras.get(key);
            }
        });

        //mock Parcelable in intent extras
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                Parcelable value = ((Parcelable) arguments[1]);
                fakeExtras.put(key, value);
                return null;
            }
        }).when(intent).putExtra(anyString(), any(Parcelable.class));
        when(intent.getParcelableExtra(anyString())).thenAnswer(new Answer<Parcelable>() {
            @Override
            public Parcelable answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                String key = ((String) arguments[0]);
                return (Parcelable) fakeExtras.get(key);
            }
        });
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                categories.add(((String) arguments[0]));
                return null;
            }
        }).when(intent).addCategory(anyString());

        when(intent.getCategories()).thenAnswer(new Answer<Set<String>>() {
            @Override
            public Set<String> answer(InvocationOnMock invocation) throws Throwable {
                return new HashSet<>(categories);
            }
        });

        return intent;
    }

    public static void mockTextUtils() {
        mockStatic(TextUtils.class);

        when(TextUtils.equals(any(CharSequence.class), any(CharSequence.class))).thenAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                CharSequence a = (CharSequence) invocation.getArguments()[0];
                CharSequence b = (CharSequence) invocation.getArguments()[1];
                if (a == b) return true;
                int length;
                if (a != null && b != null && (length = a.length()) == b.length()) {
                    if (a instanceof String && b instanceof String) {
                        return a.equals(b);
                    } else {
                        for (int i = 0; i < length; i++) {
                            if (a.charAt(i) != b.charAt(i)) return false;
                        }
                        return true;
                    }
                }
                return false;
            }
        });

        when(TextUtils.isEmpty(any(CharSequence.class))).thenAnswer(new Answer<Boolean>() {
            @Override
            public Boolean answer(InvocationOnMock invocation) throws Throwable {
                CharSequence param = (CharSequence) invocation.getArguments()[0];
                return param == null || param.length() == 0;
            }
        });
    }

    public static ResultReceiver mockResultReceiver(final int expectedResultCode, final Bundle expectedBundle) {
        ResultReceiver resultReceiver = mock(ResultReceiver.class);

        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] arguments = invocation.getArguments();
                int resultCode = (int) arguments[0];
                Bundle bundle = (Bundle) arguments[1];
                Set<String> keys = expectedBundle.keySet();
                Iterator<String> iterator = keys.iterator();
                HashMap<String, Integer> expectedIntegers = new HashMap<>();
                HashMap<String, String> expectedStrings = new HashMap<>();
                HashMap<String, Boolean> expectedBooleans = new HashMap<>();
                HashMap<String, Parcelable> expectedParcelables = new HashMap<>();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    Object value = expectedBundle.get(key);

                    if (value instanceof Boolean) {
                        expectedBooleans.put(key, (Boolean) value);
                    } else if (value instanceof Integer) {
                        expectedIntegers.put(key, (Integer) value);
                    } else if (value instanceof String) {
                        expectedStrings.put(key, (String) value);
                    } else if (value instanceof Parcelable) {
                        expectedParcelables.put(key, (Parcelable) value);
                    }
                }
                assertThat("expected bundle: ", bundle, new BundleMatcher(expectedIntegers, expectedStrings, expectedBooleans, expectedParcelables));
                assertEquals("expected resultCode: ", expectedResultCode, resultCode);
                return null;
            }
        }).when(resultReceiver).send(anyInt(), any(Bundle.class));
        return resultReceiver;
    }

    public static void mockConfigHelper(String mockedFingerprint, final Provider providerFromPrefs) throws CertificateEncodingException, NoSuchAlgorithmException {
        // FIXME use MockSharedPreferences instead of provider
        mockStatic(ConfigHelper.class);
        when(ConfigHelper.getFromPersistedProvider(anyString(), anyString(), any(SharedPreferences.class))).thenAnswer(new Answer<String>() {
            @Override
            public String answer(InvocationOnMock invocation) throws Throwable {
                String key = (String) invocation.getArguments()[0];
                switch (key) {
                    case PROVIDER_PRIVATE_KEY:
                        return providerFromPrefs.getPrivateKey();
                    case PROVIDER_VPN_CERTIFICATE:
                        return providerFromPrefs.getVpnCertificate();
                    case Provider.KEY:
                        return providerFromPrefs.getDefinition().toString();
                    case Provider.CA_CERT_FINGERPRINT:
                        return providerFromPrefs.getCaCertFingerprint();
                }
                return null;
            }
        });
        when(ConfigHelper.getFingerprintFromCertificate(any(X509Certificate.class), anyString())).thenReturn(mockedFingerprint);
        when(ConfigHelper.checkErroneousDownload(anyString())).thenCallRealMethod();
        when(ConfigHelper.parseX509CertificateFromString(anyString())).thenCallRealMethod();
    }
    public static void mockFingerprintForCertificate(String mockedFingerprint) throws CertificateEncodingException, NoSuchAlgorithmException {
        mockStatic(ConfigHelper.class);
        when(ConfigHelper.getFingerprintFromCertificate(any(X509Certificate.class), anyString())).thenReturn(mockedFingerprint);
        when(ConfigHelper.checkErroneousDownload(anyString())).thenCallRealMethod();
        when(ConfigHelper.parseX509CertificateFromString(anyString())).thenCallRealMethod();
    }

    public static void mockProviderApiConnector(final BackendMockProvider.TestBackendErrorCase errorCase) throws IOException {
        BackendMockProvider.provideBackendResponsesFor(errorCase);
    }

    public static OkHttpClientGenerator mockClientGenerator() {
        OkHttpClientGenerator mockClientGenerator = mock(OkHttpClientGenerator.class);
        OkHttpClient mockedOkHttpClient = mock(OkHttpClient.class);
        when(mockClientGenerator.initCommercialCAHttpClient(any(JSONObject.class))).thenReturn(mockedOkHttpClient);
        when(mockClientGenerator.initSelfSignedCAHttpClient(anyString(), any(JSONObject.class))).thenReturn(mockedOkHttpClient);
        return mockClientGenerator;
    }

    public static Resources mockResources(InputStream inputStream) throws IOException, JSONException {
        Resources mockedResources = mock(Resources.class, RETURNS_DEEP_STUBS);
        JSONObject errorMessages = new JSONObject(TestSetupHelper.getInputAsString(inputStream));


        when(mockedResources.getString(R.string.warning_corrupted_provider_details)).
                thenReturn(errorMessages.getString("warning_corrupted_provider_details"));
        when(mockedResources.getString(R.string.server_unreachable_message)).
                thenReturn(errorMessages.getString("server_unreachable_message"));
        when(mockedResources.getString(R.string.error_security_pinnedcertificate)).
                thenReturn(errorMessages.getString("error.security.pinnedcertificate"));
        when(mockedResources.getString(R.string.malformed_url)).
                thenReturn(errorMessages.getString("malformed_url"));
        when(mockedResources.getString(R.string.certificate_error)).
                thenReturn(errorMessages.getString("certificate_error"));
        when(mockedResources.getString(R.string.error_srp_math_error_user_message)).
                thenReturn(errorMessages.getString("error_srp_math_error_user_message"));
        when(mockedResources.getString(R.string.error_bad_user_password_user_message)).
                thenReturn(errorMessages.getString("error_bad_user_password_user_message"));
        when(mockedResources.getString(R.string.error_not_valid_password_user_message)).
                thenReturn(errorMessages.getString("error_not_valid_password_user_message"));
        when(mockedResources.getString(R.string.error_client_http_user_message)).
                thenReturn(errorMessages.getString("error_client_http_user_message"));
        when(mockedResources.getString(R.string.error_io_exception_user_message)).
                thenReturn(errorMessages.getString("error_io_exception_user_message"));
        when(mockedResources.getString(R.string.error_json_exception_user_message)).
                thenReturn(errorMessages.getString("error_json_exception_user_message"));
        when(mockedResources.getString(R.string.error_no_such_algorithm_exception_user_message)).
                thenReturn(errorMessages.getString("error_no_such_algorithm_exception_user_message"));
        when(mockedResources.getString(R.string.warning_corrupted_provider_details)).
                thenReturn(errorMessages.getString("warning_corrupted_provider_details"));
        when(mockedResources.getString(R.string.warning_corrupted_provider_cert)).
                thenReturn(errorMessages.getString("warning_corrupted_provider_cert"));
        when(mockedResources.getString(R.string.warning_expired_provider_cert)).
                thenReturn(errorMessages.getString("warning_expired_provider_cert"));
        return mockedResources;
    }
}