fix: defer automatic rotation after manual changes

Preserve the full interval with an in-place next-run override and add request-level and real WorkManager regression coverage.
This commit is contained in:
Anthony La authored and GitHub committed 2026-09-12 12:06:19 -07:00
1 parent 22cc66687e
commit e18f3eceb9
4 files changed
+257 -7

No files matched your search

@@ -0,0 +1,131 @@
package com.anthonyla.paperize.service.worker
import android.annotation.SuppressLint
import android.content.Context
import android.os.SystemClock
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.work.WorkInfo
import androidx.work.WorkManager
import androidx.work.impl.WorkManagerImpl
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.domain.model.ScheduleSettings
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeout
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@SuppressLint("RestrictedApi")
@RunWith(AndroidJUnit4::class)
class WallpaperSchedulerInstrumentedTest {
private val context = ApplicationProvider.getApplicationContext<Context>()
private val workManager = WorkManager.getInstance(context) as WorkManagerImpl
private val scheduler = WallpaperScheduler(context)
private val targets = mapOf(
ScreenType.HOME to Constants.WORK_NAME_HOME,
ScreenType.LOCK to Constants.WORK_NAME_LOCK,
ScreenType.BOTH to Constants.WORK_NAME_BOTH,
ScreenType.LIVE to Constants.WORK_NAME_LIVE
)
@Before
@After
fun clearTestSchedules() {
targets.values.forEach { name ->
workManager.cancelUniqueWork(name).result.get(10, TimeUnit.SECONDS)
}
}
@Test
fun manualResetJobsRemainInTheirFirstPeriodUntilTheFullDelay() = runBlocking {
val delayMillis = TimeUnit.MINUTES.toMillis(15)
val jobs = targets.map { (screen, name) ->
val before = System.currentTimeMillis()
scheduler.scheduleWallpaperChange(screen, 15, resetInterval = true)
val info = awaitEnqueued(name)
assertTrue(info.nextScheduleTimeMillis >= before + delayMillis)
info.id to before
}
// Checking only the next countdown can miss an immediate first run: after that run,
// periodic work also shows a full interval. Inspect the persisted first-period state.
SystemClock.sleep(2_000)
jobs.forEach { (id, before) ->
val spec = requireNotNull(workManager.workDatabase.workSpecDao().getWorkSpec(id.toString()))
assertEquals(delayMillis, spec.intervalDuration)
assertEquals(0, spec.periodCount)
assertEquals(WorkInfo.State.ENQUEUED, spec.state)
assertTrue(spec.calculateNextRunTime() >= before + delayMillis)
assertTrue(spec.calculateNextRunTime() <= System.currentTimeMillis() + delayMillis)
}
}
@Test
fun settingsUpdatePreservesThePendingManualResetDelay() = runBlocking {
scheduler.scheduleWallpaperChange(ScreenType.HOME, 60, resetInterval = true)
val reset = awaitEnqueued(Constants.WORK_NAME_HOME)
scheduler.scheduleWallpaperChange(ScreenType.HOME, 60)
val updated = awaitEnqueued(Constants.WORK_NAME_HOME, minimumGeneration = reset.generation + 1)
assertEquals(reset.id, updated.id)
assertEquals(reset.nextScheduleTimeMillis, updated.nextScheduleTimeMillis)
val spec = requireNotNull(workManager.workDatabase.workSpecDao().getWorkSpec(updated.id.toString()))
assertEquals(0, spec.periodCount)
}
@Test
fun repeatedHomeResetLeavesTheIndependentLockCountdownUntouched() = runBlocking {
scheduler.scheduleWallpaperChange(ScreenType.HOME, 60, resetInterval = true)
scheduler.scheduleWallpaperChange(ScreenType.LOCK, 90, resetInterval = true)
val home = awaitEnqueued(Constants.WORK_NAME_HOME)
val lock = awaitEnqueued(Constants.WORK_NAME_LOCK)
val before = System.currentTimeMillis()
scheduler.resetAfterManualChange(
ScreenType.HOME,
ScheduleSettings(
enableChanger = true,
separateSchedules = true,
homeEnabled = true,
lockEnabled = true,
homeAlbumId = "home",
lockAlbumId = "lock",
homeIntervalMinutes = 60,
lockIntervalMinutes = 90
),
WallpaperMode.STATIC
)
val newHome = awaitEnqueued(Constants.WORK_NAME_HOME, minimumGeneration = home.generation + 1)
val sameLock = awaitEnqueued(Constants.WORK_NAME_LOCK)
assertEquals(home.id, newHome.id)
assertTrue(newHome.nextScheduleTimeMillis >= before + TimeUnit.MINUTES.toMillis(60))
assertEquals(lock.id, sameLock.id)
assertEquals(lock.nextScheduleTimeMillis, sameLock.nextScheduleTimeMillis)
}
private suspend fun awaitEnqueued(
name: String,
minimumGeneration: Int = 0
): WorkInfo =
withTimeout(10_000) {
workManager.getWorkInfosForUniqueWorkFlow(name).first { infos ->
infos.any {
it.state == WorkInfo.State.ENQUEUED &&
it.generation >= minimumGeneration
}
}.single {
it.state == WorkInfo.State.ENQUEUED &&
it.generation >= minimumGeneration
}
}
}
@@ -82,17 +82,22 @@ class WallpaperScheduler @Inject constructor(
.setConstraints(constraints)
.setInputData(inputData)
.addTag(getWorkTag(screenType))
.apply {
// New periodic work otherwise runs immediately. Unlike an initial delay, this
// one-run deadline also survives unrelated UPDATE requests from settings edits.
if (resetInterval) {
setNextScheduleTimeOverride(
System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(adjustedInterval)
)
}
}
.build()
// UPDATE preserves the existing period for settings edits. A successful manual change uses
// CANCEL_AND_REENQUEUE so the next automatic change waits for one complete interval.
// Preserve the existing work and explicitly move only the next run after a manual change.
// Replacing periodic work starts a new first period, which can otherwise run immediately.
workManager.enqueueUniquePeriodicWork(
workName,
if (resetInterval) {
ExistingPeriodicWorkPolicy.CANCEL_AND_REENQUEUE
} else {
ExistingPeriodicWorkPolicy.UPDATE
},
ExistingPeriodicWorkPolicy.UPDATE,
workRequest
)
@@ -0,0 +1,112 @@
@file:Suppress("RestrictedApi")
package com.anthonyla.paperize.service.worker
import android.content.Context
import android.util.Log
import androidx.work.ExistingPeriodicWorkPolicy
import androidx.work.Operation
import androidx.work.PeriodicWorkRequest
import androidx.work.WorkManager
import com.anthonyla.paperize.core.ScreenType
import com.anthonyla.paperize.core.WallpaperMode
import com.anthonyla.paperize.core.constants.Constants
import com.anthonyla.paperize.domain.model.ScheduleSettings
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import java.util.concurrent.TimeUnit
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
class WallpaperSchedulerTest {
private val context = mockk<Context>()
private val workManager = mockk<WorkManager>()
private val operation = mockk<Operation>()
private val enqueued = mutableListOf<Triple<String, ExistingPeriodicWorkPolicy, PeriodicWorkRequest>>()
private lateinit var scheduler: WallpaperScheduler
@Before
fun setUp() {
mockkObject(WorkManager.Companion)
mockkStatic(Log::class)
every { WorkManager.getInstance(context) } returns workManager
every { Log.d(any(), any()) } returns 0
every { workManager.enqueueUniquePeriodicWork(any(), any(), any()) } answers {
enqueued += Triple(firstArg(), secondArg(), thirdArg())
operation
}
scheduler = WallpaperScheduler(context)
}
@After
fun tearDown() = unmockkAll()
@Test
fun `manual resets defer the next run for a full interval for every target`() {
val intervalMillis = TimeUnit.MINUTES.toMillis(60)
ScreenType.entries.forEach { screen ->
val enqueueTime = System.currentTimeMillis()
scheduler.scheduleWallpaperChange(screen, 60, resetInterval = true)
val (_, policy, request) = enqueued.last()
assertEquals(ExistingPeriodicWorkPolicy.UPDATE, policy)
assertEquals(screen.name, request.workSpec.input.getString(Constants.EXTRA_SCREEN_TYPE))
request.workSpec.lastEnqueueTime = enqueueTime
val nextRun = request.workSpec.calculateNextRunTime()
assertTrue(nextRun >= enqueueTime + intervalMillis)
assertTrue(nextRun <= System.currentTimeMillis() + intervalMillis)
}
}
@Test
fun `ordinary scheduling retains update policy and immediate first activation`() {
scheduler.scheduleWallpaperChange(ScreenType.HOME, 60)
val (_, policy, request) = enqueued.single()
assertEquals(ExistingPeriodicWorkPolicy.UPDATE, policy)
assertEquals(0L, request.workSpec.initialDelay)
assertEquals(Long.MAX_VALUE, request.workSpec.nextScheduleTimeOverride)
}
@Test
fun `manual reset delay uses the same minimum as the periodic interval`() {
val before = System.currentTimeMillis()
scheduler.scheduleWallpaperChange(ScreenType.HOME, 1, resetInterval = true)
val request = enqueued.single().third
val minimumMillis = TimeUnit.MINUTES.toMillis(15)
assertEquals(minimumMillis, request.workSpec.intervalDuration)
assertTrue(request.workSpec.calculateNextRunTime() >= before + minimumMillis)
assertTrue(request.workSpec.calculateNextRunTime() <= System.currentTimeMillis() + minimumMillis)
}
@Test
fun `manual home reset delays only its active independent schedule`() {
val before = System.currentTimeMillis()
scheduler.resetAfterManualChange(
ScreenType.HOME,
ScheduleSettings(
enableChanger = true,
separateSchedules = true,
homeEnabled = true,
lockEnabled = true,
homeAlbumId = "home",
lockAlbumId = "lock",
homeIntervalMinutes = 60,
lockIntervalMinutes = 90
),
WallpaperMode.STATIC
)
val (name, policy, request) = enqueued.single()
assertEquals(Constants.WORK_NAME_HOME, name)
assertEquals(ExistingPeriodicWorkPolicy.UPDATE, policy)
assertTrue(request.workSpec.calculateNextRunTime() >= before + TimeUnit.MINUTES.toMillis(60))
}
}