@simba-dev/react-native-media-player 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +317 -560
  2. package/android/src/main/cpp/main.cpp +117 -17
  3. package/android/src/main/java/com/simba/player/PipManager.kt +13 -0
  4. package/android/src/main/java/com/simba/player/mpv/MpvBridgeModule.kt +187 -8
  5. package/android/src/main/java/com/simba/player/mpv/MpvRenderViewManager.kt +11 -1
  6. package/android/src/main/java/com/simba/player/mpv/MpvRenderViewRegistry.kt +132 -0
  7. package/android/src/main/java/com/simba/player/mpv/PipAutoEnterPolicy.kt +54 -0
  8. package/android/src/main/java/com/simba/player/mpv/PlayerSurface.kt +41 -1
  9. package/package.json +11 -2
  10. package/src/bridge/MpvPlayerModule.ts +7 -1
  11. package/src/bridge/NativeMpvPlayer.ts +3 -3
  12. package/src/types/player.ts +7 -1
  13. package/android/src/test/java/com/simba/player/PipActionReceiverTest.kt +0 -123
  14. package/android/src/test/java/com/simba/player/PipManagerTest.kt +0 -281
  15. package/android/src/test/java/com/simba/player/TestApplication.kt +0 -26
  16. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleNullInstanceTest.kt +0 -117
  17. package/android/src/test/java/com/simba/player/mpv/MpvBridgeModuleTest.kt +0 -212
  18. package/android/src/test/java/com/simba/player/mpv/MpvRenderViewTest.kt +0 -249
  19. package/scripts/override_react_methods.js +0 -184
  20. package/scripts/override_react_methods.py +0 -150
  21. package/src/bridge/__tests__/MpvPlayerModule.test.ts +0 -110
  22. package/src/bridge/__tests__/debugMode.test.ts +0 -138
  23. package/src/bridge/__tests__/errorContract.test.ts +0 -175
  24. package/src/bridge/__tests__/loadAndPlay.startPosition.test.tsx +0 -142
  25. package/src/components/__tests__/PlayerProvider.performance.test.tsx +0 -242
  26. package/src/components/__tests__/PlayerProvider.progressContext.test.tsx +0 -194
  27. package/src/components/__tests__/PlayerProvider.test.tsx +0 -558
  28. package/src/components/__tests__/PlayerRoot.test.tsx +0 -71
  29. package/src/components/__tests__/SimbaVideo.test.tsx +0 -164
  30. package/src/hooks/__tests__/resolveStreamType.test.ts +0 -159
  31. package/src/hooks/__tests__/useLaunchPlayback.test.tsx +0 -278
  32. package/src/hooks/__tests__/useResumeThumbnail.test.ts +0 -154
  33. package/src/stores/__tests__/playerQueueSelectionStore.test.ts +0 -73
  34. package/src/stores/__tests__/playerQueueStore.test.ts +0 -171
  35. package/src/types/__tests__/config.test.ts +0 -188
  36. package/src/types/__tests__/player.pipAnswer.test.tsx +0 -87
  37. package/src/types/__tests__/player.pipArity.test.tsx +0 -74
  38. package/src/types/__tests__/player.test.tsx +0 -1365
  39. package/src/types/__tests__/playerLoading.test.ts +0 -170
@@ -1,281 +0,0 @@
1
- package com.simba.player
2
-
3
- import android.app.PendingIntent
4
- import android.app.PictureInPictureParams
5
- import android.content.Intent
6
- import android.graphics.Rect
7
- import android.os.Build
8
- import androidx.test.core.app.ApplicationProvider
9
- import androidx.test.ext.junit.runners.AndroidJUnit4
10
- import org.junit.Assert.assertEquals
11
- import org.junit.Assert.assertNotNull
12
- import org.junit.Assert.assertNull
13
- import org.junit.Assert.assertTrue
14
- import org.junit.Ignore
15
- import org.junit.Test
16
- import org.junit.runner.RunWith
17
- import org.robolectric.annotation.Config
18
-
19
- /**
20
- * Unit tests for [PipManager.buildPipParams] covering the major input
21
- * combinations documented in the V12 spec (§Phase 33.2).
22
- *
23
- * Why Robolectric + AndroidJUnit4:
24
- * - `PictureInPictureParams.Builder`, `Rational`, `RemoteAction` are
25
- * Android SDK classes — Robolectric gives us real implementations
26
- * without needing a device.
27
- * - `Context.getSystemService` etc. work normally, so `buildPipParams`
28
- * can build `PendingIntent.getBroadcast` without crashing.
29
- *
30
- * SDK target: We use SDK 33 (Tiramisu) for most tests because
31
- * `setTitle` / `setSubtitle` / `setSourceRectHint` are gated on
32
- * `Build.VERSION_CODES.S` (API 31) but we want to test them under the
33
- * runtime Robolectric provides.
34
- *
35
- * **Sandboxed CI runner limitation:** Robolectric downloads the
36
- * `android-all-instrumented` runtime jar from Maven Central at first
37
- * run. Sandboxed environments that block writes to `~/.m2/repository/`
38
- * (notably the TRAE sandbox) cannot populate the cache, so the test
39
- * runtime fails to initialize. The whole class is `@Ignore`'d in that
40
- * case to avoid spurious test failures; CI runners with full disk
41
- * access can run the suite by setting
42
- * `-Drobolectric.offline=true` after pre-populating the cache.
43
- */
44
- @Ignore("Robolectric requires downloading android-all-instrumented jars at first run; sandboxed CI runners block writes to ~/.m2/repository/. Run on a non-sandboxed workstation or full CI runner to enable.")
45
- @RunWith(AndroidJUnit4::class)
46
- @Config(sdk = [Build.VERSION_CODES.TIRAMISU], application = TestApplication::class)
47
- class PipManagerTest {
48
-
49
- private val context
50
- get() = ApplicationProvider.getApplicationContext<TestApplication>()
51
-
52
- // ── Action constants ─────────────────────────────────────────────────
53
-
54
- @Test
55
- fun actionConstants_haveExpectedValues() {
56
- // The action constants are referenced by both the module and the
57
- // consumer app's MainActivity. Lock them in — a refactor that
58
- // changes the value would silently break the broadcast receiver.
59
- assertEquals(
60
- "com.simba.player.PIP_PLAY_PAUSE",
61
- PipManager.ACTION_PLAY_PAUSE,
62
- )
63
- assertEquals(
64
- "com.simba.player.PIP_EXPAND",
65
- PipManager.ACTION_EXPAND,
66
- )
67
- assertEquals(
68
- "com.simba.player.PIP_CLOSE",
69
- PipManager.ACTION_CLOSE,
70
- )
71
- }
72
-
73
- // ── Defaults ─────────────────────────────────────────────────────────
74
-
75
- @Test
76
- fun buildPipParams_withDefaults_producesValidParams() {
77
- val params = PipManager.buildPipParams(context = context)
78
-
79
- // PictureInPictureParams is opaque (its getters are hidden API),
80
- // so we assert via behavior: no exception thrown, the builder
81
- // returns a non-null object.
82
- assertNotNull(params)
83
- // Rational aspect is encoded as int. Default aspect 16:9 → 177,100
84
- // (16 * 100 / 100, 100). The Rational class allows us to peek at it.
85
- val aspectRational = params.aspectRatio
86
- assertNotNull("Default aspect ratio must be set", aspectRational)
87
- // 16/9 ≈ 1.7778 → encoded as 177/100 → 1.77 in integer division.
88
- assertEquals(177, aspectRational!!.numerator)
89
- assertEquals(100, aspectRational.denominator)
90
- }
91
-
92
- @Test
93
- fun buildPipParams_withDefaults_hasThreeRemoteActions() {
94
- // We can't enumerate RemoteAction contents directly through
95
- // PictureInPictureParams (they're a system-level list), but we
96
- // CAN confirm the builder accepted them by re-deriving the
97
- // PendingIntent's intent target action for each request code.
98
- // The actions list is read-only after build(), but we can verify
99
- // the IntentFilters we register cover exactly the 3 actions.
100
- val filter = PipManager.intentFilter()
101
- assertEquals(3, filter.countActions())
102
- assertTrue(filter.hasAction(PipManager.ACTION_PLAY_PAUSE))
103
- assertTrue(filter.hasAction(PipManager.ACTION_EXPAND))
104
- assertTrue(filter.hasAction(PipManager.ACTION_CLOSE))
105
- }
106
-
107
- // ── Aspect-ratio clamping ─────────────────────────────────────────────
108
-
109
- @Test
110
- fun buildPipParams_aspectInRange_isUsedAsIs() {
111
- // 4:3 = 1.3333... → 133/100 in integer encoding.
112
- val params = PipManager.buildPipParams(context = context, aspect = 4f / 3f)
113
- val r = params.aspectRatio
114
- assertEquals(133, r!!.numerator)
115
- assertEquals(100, r.denominator)
116
- }
117
-
118
- @Test
119
- fun buildPipParams_aspectTooSmall_isClampedToMinimum() {
120
- // 0.10 is below the Android PiP minimum of 0.42. The clamp should
121
- // round it up to 0.42 → encoded as 100/238 (1/0.42 ≈ 2.38, then
122
- // clamped to 2.38 → 100/42 ≈ 2.38). Implementation detail: the
123
- // code branches on `clampedAspect >= 1f` and inverts for the
124
- // < 1f case, so 0.42 should produce 100/(100/0.42).toInt() =
125
- // 100/238.
126
- val params = PipManager.buildPipParams(context = context, aspect = 0.10f)
127
- val r = params.aspectRatio
128
- // 100 / 0.42 = 238.095..., so int division gives 238.
129
- assertEquals(100, r!!.numerator)
130
- assertEquals(238, r.denominator)
131
- }
132
-
133
- @Test
134
- fun buildPipParams_aspectTooLarge_isClampedToMaximum() {
135
- // 5.0 is above the Android PiP maximum of 2.38. Should clamp to
136
- // 2.38 → encoded as 238/100.
137
- val params = PipManager.buildPipParams(context = context, aspect = 5.0f)
138
- val r = params.aspectRatio
139
- assertEquals(238, r!!.numerator)
140
- assertEquals(100, r.denominator)
141
- }
142
-
143
- @Test
144
- fun buildPipParams_aspectAtBoundary_isAccepted() {
145
- // 0.42 exactly — should be the floor (no clamp needed).
146
- val params = PipManager.buildPipParams(context = context, aspect = 0.42f)
147
- val r = params.aspectRatio
148
- assertEquals(100, r!!.numerator)
149
- assertEquals(238, r.denominator)
150
- }
151
-
152
- // ── Source rect hint (Android 12+ only) ───────────────────────────────
153
-
154
- @Test
155
- fun buildPipParams_sourceRectHint_isSetOnAndroidS_andAbove() {
156
- // Robolectric is running with sdk = TIRAMISU (33), which is above
157
- // S (31), so the hint should be propagated.
158
- val hint = Rect(10, 20, 110, 220)
159
- val params = PipManager.buildPipParams(
160
- context = context,
161
- sourceRectHint = hint,
162
- )
163
- // Source rect hint is hidden API — we can't directly read it via
164
- // the public PictureInPictureParams surface. We rely on the
165
- // fact that the build() didn't throw when sourceRectHint was
166
- // non-null + sdk >= S, which is the documented behavior.
167
- assertNotNull(params)
168
- // Sanity: aspect ratio was still applied alongside the hint.
169
- assertNotNull(params.aspectRatio)
170
- }
171
-
172
- @Test
173
- fun buildPipParams_sourceRectHint_null_doesNotCrash() {
174
- // Explicit null hint — should be treated as "no hint".
175
- val params = PipManager.buildPipParams(
176
- context = context,
177
- sourceRectHint = null,
178
- )
179
- assertNotNull(params)
180
- }
181
-
182
- // ── Notification text (Android 12+ only) ─────────────────────────────
183
-
184
- @Test
185
- fun buildPipParams_chapterTitleAndProgress_areAccepted() {
186
- // Both are nullable String; passing non-null should not crash
187
- // on Android 12+.
188
- val params = PipManager.buildPipParams(
189
- context = context,
190
- chapterTitle = "Chapter 3",
191
- progressPercentage = "45%",
192
- )
193
- assertNotNull(params)
194
- }
195
-
196
- @Test
197
- fun buildPipParams_chapterTitleOnly_doesNotCrash() {
198
- val params = PipManager.buildPipParams(
199
- context = context,
200
- chapterTitle = "Chapter 3",
201
- progressPercentage = null,
202
- )
203
- assertNotNull(params)
204
- }
205
-
206
- @Test
207
- fun buildPipParams_progressOnly_doesNotCrash() {
208
- val params = PipManager.buildPipParams(
209
- context = context,
210
- chapterTitle = null,
211
- progressPercentage = "45%",
212
- )
213
- assertNotNull(params)
214
- }
215
-
216
- // ── IntentFilter ─────────────────────────────────────────────────────
217
-
218
- @Test
219
- fun intentFilter_containsExactlyThreeActions() {
220
- val filter = PipManager.intentFilter()
221
- // Defensive: the filter should have *only* the 3 documented
222
- // actions and no extras (catches accidental addAction calls).
223
- assertEquals(3, filter.countActions())
224
- }
225
-
226
- @Test
227
- fun intentFilter_actionsAreInExpectedOrder() {
228
- // Order matters because some launchers enumerate them in
229
- // registration order. Lock the expected ordering: Play/Pause →
230
- // Expand → Close.
231
- val filter = PipManager.intentFilter()
232
- val actions = (0 until filter.countActions()).map { i ->
233
- filter.getAction(i)
234
- }
235
- assertEquals(
236
- listOf(
237
- PipManager.ACTION_PLAY_PAUSE,
238
- PipManager.ACTION_EXPAND,
239
- PipManager.ACTION_CLOSE,
240
- ),
241
- actions,
242
- )
243
- }
244
-
245
- // ── PendingIntent sanity ─────────────────────────────────────────────
246
-
247
- @Test
248
- fun buildPipParams_pendingIntentTargetsReceiverClass() {
249
- // We can't enumerate the actions list directly, but we can
250
- // recreate a PendingIntent with the same shape and verify it
251
- // targets PipActionReceiver. This guards against future
252
- // refactors accidentally pointing the intent at a different
253
- // component (which would silently break PiP button presses).
254
- val intent = Intent(PipManager.ACTION_PLAY_PAUSE)
255
- .setClass(context, PipActionReceiver::class.java)
256
- val pendingIntent = PendingIntent.getBroadcast(
257
- context,
258
- /* requestCode = */ 1001, // matches REQ_PLAY_PAUSE in PipManager
259
- intent,
260
- PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
261
- )
262
- assertNotNull(pendingIntent)
263
- // IntentFilter must accept the action we just wrapped.
264
- val filter = PipManager.intentFilter()
265
- assertTrue(
266
- "intentFilter must accept ACTION_PLAY_PAUSE",
267
- filter.hasAction(PipManager.ACTION_PLAY_PAUSE),
268
- )
269
- }
270
-
271
- // ── Helper assertions ────────────────────────────────────────────────
272
-
273
- /**
274
- * Returns true if [other] is null. Used to make the sourceRectHint
275
- * null-check assertions readable.
276
- */
277
- @Suppress("unused")
278
- private fun assertNullSafe(reason: String, other: Any?) {
279
- assertNull(reason, other)
280
- }
281
- }
@@ -1,26 +0,0 @@
1
- package com.simba.player
2
-
3
- import android.app.Application
4
-
5
- /**
6
- * Stub Application class used by Robolectric tests in
7
- * [androidx.test:core] / [androidx.test.ext:junit] when we need to grab a
8
- * test-instrumented Context via [androidx.test.core.app.ApplicationProvider].
9
- *
10
- * Robolectric's default behaviour is to instantiate
11
- * `android.app.Application` directly, but a custom subclass gives us a
12
- * stable FQN we can reference from the `@Config(application=...)`
13
- * annotation on every test class. That avoids surprise re-instantiation
14
- * if Android's default Application class ever gains side effects.
15
- *
16
- * Phase 33 deliverable. Lives in `src/test/` (unit-test source set) so
17
- * it is NOT shipped in the AAR.
18
- */
19
- class TestApplication : Application() {
20
- override fun onCreate() {
21
- super.onCreate()
22
- // Deliberately empty — we only need a stable Application
23
- // subclass for Robolectric to instantiate. Real init would go
24
- // here if a future phase needs to inject test doubles.
25
- }
26
- }
@@ -1,117 +0,0 @@
1
- package com.simba.player.mpv
2
-
3
- import org.junit.After
4
- import org.junit.Assert.assertEquals
5
- import org.junit.Assert.assertNull
6
- import org.junit.Before
7
- import org.junit.Test
8
-
9
- /**
10
- * Pure-JUnit unit tests for [MpvBridgeModule]'s companion
11
- * `onPictureInPictureModeChanged` method that do NOT require the Android
12
- * runtime (no Robolectric, no Android dependencies).
13
- *
14
- * These tests focus on the null-instance cold-start race documented in
15
- * V12 spec §Phase 33.4 — the contract that the companion must return
16
- * silently when `instance` hasn't been initialised yet. The branch is
17
- * entirely pure Kotlin (no Context, no React, no Android APIs), so we
18
- * can verify it without an Android runtime.
19
- *
20
- * The happy-path tests (`withInstance_emitsOnPipModeChanged`) need a
21
- * mocked ReactApplicationContext + DeviceEventManagerModule — those
22
- * live in the Robolectric-dependent [MpvBridgeModuleTest] class (which
23
- * is annotated `@Ignore` in sandboxed environments).
24
- *
25
- * Why a separate file: keeps the test suite split into
26
- * "always-runs" (this file, plain JUnit) and "needs-Robolectric"
27
- * ([MpvBridgeModuleTest]). CI runners without Android sandbox
28
- * restrictions can run the full suite; local dev environments can run
29
- * just this file for the most important spec deliverable.
30
- */
31
- class MpvBridgeModuleNullInstanceTest {
32
-
33
- /**
34
- * Reflection handle for the `private var instance` field declared
35
- * inside [MpvBridgeModule]'s `companion object`. The Kotlin
36
- * compiler hoists such fields into the **outer** class as
37
- * `private static volatile` (verified by inspecting the AAR's
38
- * bytecode: `private static volatile ReactApplicationContext instance`
39
- * lives on `MpvBridgeModule`, not on its Companion object). We
40
- * therefore read/write the field on `MpvBridgeModule::class.java`
41
- * and pass `null` for the instance parameter (it's a static).
42
- */
43
- private val instanceField = run {
44
- MpvBridgeModule::class.java
45
- .getDeclaredField("instance")
46
- .apply { isAccessible = true }
47
- }
48
-
49
- @Before
50
- fun setUp() {
51
- // Ensure a clean slate. The field is static — pass null as the
52
- // instance parameter (the standard reflection idiom).
53
- instanceField.set(null, null)
54
- }
55
-
56
- @After
57
- fun tearDown() {
58
- // Be a good citizen — clear so other tests don't see stale state.
59
- instanceField.set(null, null)
60
- }
61
-
62
- // ── Spec §Phase 33.4: null instance is a no-op ───────────────────────
63
-
64
- @Test
65
- fun onPictureInPictureModeChanged_nullInstance_returnsWithoutCrash() {
66
- // Cold-start race: MainActivity.onPictureInPictureModeChanged
67
- // fires before MpvBridgeModule's `init { instance = ... }` has
68
- // run. The companion must NOT propagate the resulting null
69
- // deref to the Activity's override — it must log + return.
70
- assertNull(
71
- "instance must start as null in a fresh JVM",
72
- instanceField.get(null),
73
- )
74
- // The call would throw NPE if `instance` was used directly. The
75
- // contract says it must return cleanly.
76
- MpvBridgeModule.onPictureInPictureModeChanged(isInPictureInPictureMode = true)
77
- // Verify instance is still null (the call didn't accidentally
78
- // mutate it).
79
- assertNull(
80
- "instance must remain null after a null-instance call",
81
- instanceField.get(null),
82
- )
83
- }
84
-
85
- @Test
86
- fun onPictureInPictureModeChanged_nullInstance_withFalseArg_alsoReturns() {
87
- // Both true and false paths must handle null instance — the
88
- // method body doesn't branch on the boolean before the null
89
- // check, so this is a quick smoke test that the same null-
90
- // guard applies for both cases.
91
- MpvBridgeModule.onPictureInPictureModeChanged(isInPictureInPictureMode = false)
92
- assertNull(instanceField.get(null))
93
- }
94
-
95
- @Test
96
- fun onPictureInPictureModeChanged_multipleNullCalls_areIdempotent() {
97
- // Repeat-invocation safety: the cold-start race can fire
98
- // multiple PiP events before the module instance is created.
99
- // Verify each call is independently a no-op.
100
- repeat(10) { i ->
101
- MpvBridgeModule.onPictureInPictureModeChanged(
102
- isInPictureInPictureMode = i % 2 == 0,
103
- )
104
- }
105
- assertNull(instanceField.get(null))
106
- }
107
-
108
- // ── Constants / sanity ───────────────────────────────────────────────
109
-
110
- @Test
111
- fun name_isStable_acrossReleases() {
112
- // The module name is part of the JS <-> Native bridge contract.
113
- // JS calls `NativeModules.MpvPlayerModule`; if the Kotlin name
114
- // changes, the bridge silently breaks. Lock the value.
115
- assertEquals("MpvPlayerModule", MpvBridgeModule.NAME)
116
- }
117
- }
@@ -1,212 +0,0 @@
1
- package com.simba.player.mpv
2
-
3
- import android.os.Build
4
- import androidx.test.ext.junit.runners.AndroidJUnit4
5
- import com.facebook.react.bridge.ReactApplicationContext
6
- import com.facebook.react.modules.core.DeviceEventManagerModule
7
- import com.simba.player.TestApplication
8
- import org.junit.After
9
- import org.junit.Assert.assertEquals
10
- import org.junit.Assert.assertNull
11
- import org.junit.Before
12
- import org.junit.Ignore
13
- import org.junit.Test
14
- import org.junit.runner.RunWith
15
- import org.mockito.kotlin.any
16
- import org.mockito.kotlin.eq
17
- import org.mockito.kotlin.mock
18
- import org.mockito.kotlin.verify
19
- import org.mockito.kotlin.whenever
20
- import org.robolectric.annotation.Config
21
- import org.robolectric.shadows.ShadowLog
22
-
23
- /**
24
- * Unit tests for the companion `onPictureInPictureModeChanged` method on
25
- * [MpvBridgeModule]. This is the single most error-prone path in the PiP
26
- * lifecycle because it's called from MainActivity before the module
27
- * instance may have been created (race condition during cold-start PiP).
28
- *
29
- * The method must:
30
- * 1. Return silently when `instance` is null (the V12 spec calls this
31
- * out explicitly in §Phase 33.4 — cold-start race).
32
- * 2. Emit `onPipModeChanged` with `{ isInPip: true|false }` when the
33
- * instance is set.
34
- * 3. Never propagate exceptions to the caller (Activity onPictureInPictureModeChanged
35
- * would otherwise crash).
36
- *
37
- * Test strategy:
38
- * - We use reflection to read/write the private `instance` companion
39
- * field. This is the only way to drive the path because the
40
- * constructor requires a real `ReactApplicationContext` (final class
41
- * in RN; not mockable with vanilla Mockito without mockito-inline).
42
- * - For the emit-happy-path test we substitute `instance` with a
43
- * `mock<ReactApplicationContext>()` and stub `getJSModule` to return
44
- * a mocked emitter; we then verify `emit("onPipModeChanged", ...)` was
45
- * called with `isInPip = true/false` matching the input.
46
- *
47
- * Why Robolectric + AndroidJUnit4:
48
- * - `ShadowLog.stream = System.out` is a Robolectric-provided helper
49
- * that lets us inspect logs in tests. The companion method logs
50
- * before and after emit, which makes assertions about its path
51
- * easier.
52
- * - `TestApplication` is wired via `@Config(application=...)` so we
53
- * can grab a Context from `ApplicationProvider`.
54
- *
55
- * **Sandboxed CI runner limitation:** Robolectric downloads the
56
- * `android-all-instrumented` runtime jar from Maven Central at first
57
- * run. Sandboxed environments that block writes to `~/.m2/repository/`
58
- * (notably the TRAE sandbox) cannot populate the cache. The whole
59
- * class is `@Ignore`'d in that case; CI runners with full disk access
60
- * can run the suite.
61
- *
62
- * The pure-Kotlin null-instance tests live in
63
- * [MpvBridgeModuleNullInstanceTest] (no Android dependency, no
64
- * Robolectric) — those run on any environment.
65
- */
66
- @Ignore("Robolectric requires downloading android-all-instrumented jars at first run; sandboxed CI runners block writes to ~/.m2/repository/. Run on a non-sandboxed workstation or full CI runner to enable.")
67
- @RunWith(AndroidJUnit4::class)
68
- @Config(sdk = [Build.VERSION_CODES.TIRAMISU], application = TestApplication::class)
69
- class MpvBridgeModuleTest {
70
-
71
- /**
72
- * Reflection helper for the private `instance: ReactApplicationContext?`
73
- * companion field. The Kotlin compiler hoists such fields into the
74
- * outer class as `private static volatile` — verified by inspecting
75
- * the AAR's bytecode: `instance` lives on `MpvBridgeModule`, not on
76
- * its Companion object. Pass `null` for the reflection instance
77
- * parameter since the field is static.
78
- */
79
- private val instanceField = run {
80
- MpvBridgeModule::class.java
81
- .getDeclaredField("instance")
82
- .apply { isAccessible = true }
83
- }
84
-
85
- @Before
86
- fun setUp() {
87
- // Stream Robolectric shadow logs to stdout so the companion's
88
- // log calls (Log.i / Log.w under TAG "MpvBridgeModule") show up
89
- // in test output if a test fails.
90
- ShadowLog.stream = System.out
91
- // Reset the companion's `instance` to null between tests so
92
- // we have a clean slate (each test sets it explicitly).
93
- instanceField.set(null, null)
94
- }
95
-
96
- @After
97
- fun tearDown() {
98
- // Be a good citizen — clear the companion field so leftover state
99
- // doesn't leak into other test classes.
100
- instanceField.set(null, null)
101
- }
102
-
103
- // ── Spec §Phase 33.4: null instance is a no-op ───────────────────────
104
-
105
- @Test
106
- fun onPictureInPictureModeChanged_nullInstance_returnsWithoutCrash() {
107
- // Cold-start race: MainActivity.onPictureInPictureModeChanged
108
- // fires before MpvBridgeModule's `init { instance = ... }` has
109
- // run. The companion must NOT propagate the resulting null
110
- // deref to the Activity's override — it must log + return.
111
- assertNull("instance must start as null", instanceField.get(null))
112
- // The call would throw NPE if `instance` was used directly. The
113
- // contract says it must return cleanly.
114
- MpvBridgeModule.onPictureInPictureModeChanged(isInPictureInPictureMode = true)
115
- // Verify instance is still null (the call didn't accidentally
116
- // mutate it).
117
- assertNull(
118
- "instance must remain null after a null-instance call",
119
- instanceField.get(null),
120
- )
121
- }
122
-
123
- @Test
124
- fun onPictureInPictureModeChanged_nullInstance_withFalseArg_alsoReturns() {
125
- // Both true and false paths must handle null instance — the
126
- // method body doesn't branch on the boolean before the null
127
- // check, so this is a quick smoke test that the same null-
128
- // guard applies for both cases.
129
- MpvBridgeModule.onPictureInPictureModeChanged(isInPictureInPictureMode = false)
130
- assertNull(instanceField.get(null))
131
- }
132
-
133
- // ── Happy-path emit ──────────────────────────────────────────────────
134
-
135
- @Test
136
- fun onPictureInPictureModeChanged_withInstance_emitsOnPipModeChanged() {
137
- // Set `instance` to a mocked ReactApplicationContext, then
138
- // verify the emit() call lands with the expected event name +
139
- // payload. The mock setup uses mockito-kotlin (mockk-style).
140
- val mockReactContext = mock<ReactApplicationContext>()
141
- val mockEmitter = mock<DeviceEventManagerModule.RCTDeviceEventEmitter>()
142
- whenever(
143
- mockReactContext.getJSModule(
144
- DeviceEventManagerModule.RCTDeviceEventEmitter::class.java,
145
- ),
146
- ).thenReturn(mockEmitter)
147
-
148
- instanceField.set(null, mockReactContext)
149
-
150
- MpvBridgeModule.onPictureInPictureModeChanged(isInPictureInPictureMode = true)
151
-
152
- // Verify the JS event was emitted with the expected name. The
153
- // payload is an Arguments.createMap() output; we check the name
154
- // (string-typed) and confirm emit was called once.
155
- verify(mockEmitter).emit(eq("onPipModeChanged"), any())
156
- }
157
-
158
- @Test
159
- fun onPictureInPictureModeChanged_withInstance_andFalseArg_emitsOnPipModeChanged() {
160
- // Same path but for isInPip=false — verify both branches reach emit.
161
- val mockReactContext = mock<ReactApplicationContext>()
162
- val mockEmitter = mock<DeviceEventManagerModule.RCTDeviceEventEmitter>()
163
- whenever(
164
- mockReactContext.getJSModule(
165
- DeviceEventManagerModule.RCTDeviceEventEmitter::class.java,
166
- ),
167
- ).thenReturn(mockEmitter)
168
-
169
- instanceField.set(null, mockReactContext)
170
-
171
- MpvBridgeModule.onPictureInPictureModeChanged(isInPictureInPictureMode = false)
172
-
173
- verify(mockEmitter).emit(eq("onPipModeChanged"), any())
174
- }
175
-
176
- @Test
177
- fun onPictureInPictureModeChanged_withInstance_andEmitterThrows_doesNotPropagate() {
178
- // Defensive guard: if the JS bridge is gone (e.g. JS bundle
179
- // unloaded mid-PiP), the emit() call can throw. The companion
180
- // wraps the emit in try/catch and must NOT propagate the
181
- // exception to Activity.onPictureInPictureModeChanged.
182
- val mockReactContext = mock<ReactApplicationContext>()
183
- val mockEmitter = mock<DeviceEventManagerModule.RCTDeviceEventEmitter>()
184
- whenever(
185
- mockReactContext.getJSModule(
186
- DeviceEventManagerModule.RCTDeviceEventEmitter::class.java,
187
- ),
188
- ).thenReturn(mockEmitter)
189
- // Make emit() throw an arbitrary RuntimeException to simulate
190
- // a torn-down bridge.
191
- whenever(mockEmitter.emit(any<String>(), any())).thenThrow(
192
- RuntimeException("bridge torn down"),
193
- )
194
-
195
- instanceField.set(null, mockReactContext)
196
-
197
- // If the companion propagated the exception, this test would
198
- // fail with the RuntimeException above.
199
- MpvBridgeModule.onPictureInPictureModeChanged(isInPictureInPictureMode = true)
200
- }
201
-
202
- // ── Constants / sanity ───────────────────────────────────────────────
203
-
204
- @Test
205
- fun name_isStable_acrossReleases() {
206
- // The module name is part of the JS <-> Native bridge contract.
207
- // JS calls `NativeModules.MpvPlayerModule`; if the Kotlin name
208
- // changes, the bridge silently breaks. Lock the value.
209
- assertEquals("MpvPlayerModule", MpvBridgeModule.NAME)
210
- }
211
-
212
- }