-
Notifications
You must be signed in to change notification settings - Fork 370
Fix StrictMode DiskReadViolations during SDK initialization #871
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jaredmixpanel
wants to merge
3
commits into
master
Choose a base branch
from
fix-strictmode-violations
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
173 changes: 173 additions & 0 deletions
173
src/androidTest/java/com/mixpanel/android/mpmetrics/StrictModeTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
| @@ -0,0 +1,173 @@ | ||||||
| package com.mixpanel.android.mpmetrics; | ||||||
|
|
||||||
| import static org.junit.Assert.assertNotNull; | ||||||
| import static org.junit.Assert.fail; | ||||||
|
|
||||||
| import android.content.Context; | ||||||
| import android.os.Build; | ||||||
| import android.os.Handler; | ||||||
| import android.os.Looper; | ||||||
| import android.os.StrictMode; | ||||||
| import androidx.test.ext.junit.runners.AndroidJUnit4; | ||||||
| import androidx.test.filters.LargeTest; | ||||||
| import androidx.test.platform.app.InstrumentationRegistry; | ||||||
| import java.io.ByteArrayOutputStream; | ||||||
| import java.io.PrintStream; | ||||||
| import java.util.concurrent.CountDownLatch; | ||||||
| import java.util.concurrent.TimeUnit; | ||||||
| import org.junit.Before; | ||||||
| import org.junit.Test; | ||||||
| import org.junit.runner.RunWith; | ||||||
|
|
||||||
| /** | ||||||
| * Test that MixpanelAPI initialization doesn't violate StrictMode policies | ||||||
| */ | ||||||
| @RunWith(AndroidJUnit4.class) | ||||||
| @LargeTest | ||||||
| public class StrictModeTest { | ||||||
|
|
||||||
| private Context mContext; | ||||||
| private static final String TEST_TOKEN = "test_token_strict_mode"; | ||||||
|
|
||||||
| @Before | ||||||
| public void setUp() { | ||||||
| mContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); | ||||||
| // Clear SharedPreferences for clean test | ||||||
| mContext.getSharedPreferences("com.mixpanel.android.mpmetrics.MixpanelAPI.SharedPreferencesLoader", Context.MODE_PRIVATE) | ||||||
| .edit() | ||||||
| .clear() | ||||||
| .apply(); | ||||||
| } | ||||||
|
|
||||||
| @Test | ||||||
| public void testNoDiskReadViolationsOnMainThread() throws InterruptedException { | ||||||
| // This test verifies that initializing MixpanelAPI on the main thread | ||||||
| // doesn't cause StrictMode DiskReadViolations | ||||||
|
|
||||||
| // Capture the original error stream | ||||||
| final PrintStream originalErr = System.err; | ||||||
| final ByteArrayOutputStream errCapture = new ByteArrayOutputStream(); | ||||||
| final PrintStream captureStream = new PrintStream(errCapture); | ||||||
|
|
||||||
| // Enable StrictMode to detect disk reads on main thread | ||||||
| StrictMode.ThreadPolicy originalPolicy = StrictMode.getThreadPolicy(); | ||||||
|
|
||||||
| final CountDownLatch latch = new CountDownLatch(1); | ||||||
| final boolean[] violationDetected = {false}; | ||||||
|
|
||||||
| try { | ||||||
| // Redirect System.err to capture StrictMode violations | ||||||
| System.setErr(captureStream); | ||||||
|
|
||||||
| // Set up StrictMode to detect disk reads | ||||||
| StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() | ||||||
| .detectDiskReads() | ||||||
| .penaltyLog() // Log violations to System.err | ||||||
| .build()); | ||||||
|
|
||||||
| // Run initialization on main thread | ||||||
| new Handler(Looper.getMainLooper()).post(new Runnable() { | ||||||
| @Override | ||||||
| public void run() { | ||||||
| try { | ||||||
| // Initialize MixpanelAPI on main thread (this is what the user does) | ||||||
| MixpanelAPI mixpanel = MixpanelAPI.getInstance(mContext, TEST_TOKEN, true); | ||||||
| assertNotNull(mixpanel); | ||||||
|
|
||||||
| // Track an event to ensure more initialization happens | ||||||
| mixpanel.track("Test Event"); | ||||||
|
|
||||||
| // Small delay to let async operations start | ||||||
| new Handler().postDelayed(new Runnable() { | ||||||
| @Override | ||||||
| public void run() { | ||||||
| // Check captured output for violations | ||||||
| String capturedOutput = errCapture.toString(); | ||||||
|
|
||||||
| // Check if any of the known violation points are in the output | ||||||
| if (capturedOutput.contains("DiskReadViolation") && | ||||||
| capturedOutput.contains("com.mixpanel.android")) { | ||||||
|
|
||||||
| boolean hasKnownViolation = | ||||||
| capturedOutput.contains("PersistentIdentity.getTimeEvents") || | ||||||
| capturedOutput.contains("MPDbAdapter$MPDatabaseHelper.<init>") || | ||||||
| capturedOutput.contains("MPDbAdapter.<init>") || | ||||||
| capturedOutput.contains("MixpanelAPI.<init>"); | ||||||
|
|
||||||
| violationDetected[0] = hasKnownViolation; | ||||||
| } | ||||||
|
|
||||||
| latch.countDown(); | ||||||
| } | ||||||
| }, 500); | ||||||
| } catch (Exception e) { | ||||||
| e.printStackTrace(); | ||||||
| latch.countDown(); | ||||||
| } | ||||||
| } | ||||||
| }); | ||||||
|
|
||||||
| // Wait for test to complete | ||||||
| assertTrue("Test should complete within timeout", | ||||||
| latch.await(10, TimeUnit.SECONDS)); | ||||||
|
|
||||||
| if (violationDetected[0]) { | ||||||
| fail("StrictMode DiskReadViolation detected in Mixpanel SDK initialization. " + | ||||||
| "Check the following locations:\n" + | ||||||
| "- PersistentIdentity.getTimeEvents()\n" + | ||||||
| "- MPDbAdapter$MPDatabaseHelper.<init>()\n" + | ||||||
| "- MixpanelAPI.<init>()"); | ||||||
| } | ||||||
|
|
||||||
| } finally { | ||||||
| // Restore original StrictMode policy and error stream | ||||||
| StrictMode.setThreadPolicy(originalPolicy); | ||||||
| System.setErr(originalErr); | ||||||
| } | ||||||
| } | ||||||
|
|
||||||
| @Test | ||||||
| public void testInitializationCompletes() throws InterruptedException { | ||||||
| // Simple test to ensure the SDK can initialize without errors | ||||||
| final CountDownLatch latch = new CountDownLatch(1); | ||||||
| final MixpanelAPI[] mixpanelRef = new MixpanelAPI[1]; | ||||||
| final Exception[] exceptionRef = new Exception[1]; | ||||||
|
|
||||||
| new Handler(Looper.getMainLooper()).post(new Runnable() { | ||||||
| @Override | ||||||
| public void run() { | ||||||
| try { | ||||||
| // Initialize MixpanelAPI | ||||||
| mixpanelRef[0] = MixpanelAPI.getInstance(mContext, TEST_TOKEN, true); | ||||||
|
|
||||||
| // Track an event | ||||||
| mixpanelRef[0].track("Test Event"); | ||||||
|
|
||||||
| // Access persistent identity (which would trigger getTimeEvents) | ||||||
| String distinctId = mixpanelRef[0].getDistinctId(); | ||||||
| assertNotNull("Distinct ID should not be null", distinctId); | ||||||
|
|
||||||
| } catch (Exception e) { | ||||||
| exceptionRef[0] = e; | ||||||
| } finally { | ||||||
| latch.countDown(); | ||||||
| } | ||||||
| } | ||||||
| }); | ||||||
|
|
||||||
| assertTrue("Initialization should complete", | ||||||
| latch.await(5, TimeUnit.SECONDS)); | ||||||
|
||||||
| latch.await(5, TimeUnit.SECONDS)); | |
| latch.await(5, TimeUnit.SECONDS)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
assertTruemethod is defined at the bottom of the test class but shadows the staticAssert.assertTruemethod. This creates confusion and could lead to incorrect test behavior. Use the importedAssert.assertTruedirectly or rename the custom method to avoid shadowing.