diff --git a/app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/learneranalytics/BUILD.bazel b/app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/learneranalytics/BUILD.bazel index f98a384b911..da61bfc0e69 100644 --- a/app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/learneranalytics/BUILD.bazel +++ b/app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/learneranalytics/BUILD.bazel @@ -51,6 +51,7 @@ app_test( "//app/src/main/java/org/oppia/android/app/translation/testing:test_module", "//testing", "//testing/src/main/java/org/oppia/android/testing/junit:initialize_default_locale_rule", + "//testing/src/main/java/org/oppia/android/testing/logging:event_log_subject", "//testing/src/main/java/org/oppia/android/testing/logging:sync_status_test_module", "//testing/src/main/java/org/oppia/android/testing/platformparameter:test_module", "//testing/src/main/java/org/oppia/android/testing/robolectric:test_module", diff --git a/app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/learneranalytics/ProfileAndDeviceIdFragmentTest.kt b/app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/learneranalytics/ProfileAndDeviceIdFragmentTest.kt index 925535d3433..5e41e379417 100644 --- a/app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/learneranalytics/ProfileAndDeviceIdFragmentTest.kt +++ b/app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/learneranalytics/ProfileAndDeviceIdFragmentTest.kt @@ -9,6 +9,7 @@ import android.view.View import androidx.annotation.IdRes import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.RecyclerView +import androidx.test.core.app.ActivityScenario import androidx.test.core.app.ApplicationProvider import androidx.test.espresso.Espresso.onView import androidx.test.espresso.ViewInteraction @@ -23,7 +24,6 @@ import androidx.test.espresso.matcher.ViewMatchers.isEnabled import androidx.test.espresso.matcher.ViewMatchers.isRoot import androidx.test.espresso.matcher.ViewMatchers.withId import androidx.test.espresso.matcher.ViewMatchers.withText -import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.ext.truth.content.IntentSubject.assertThat import androidx.work.Configuration @@ -56,6 +56,7 @@ import org.oppia.android.app.application.ApplicationStartupListenerModule import org.oppia.android.app.application.testing.TestingBuildFlavorModule import org.oppia.android.app.devoptions.DeveloperOptionsModule import org.oppia.android.app.devoptions.DeveloperOptionsStarterModule +import org.oppia.android.app.model.OppiaEventLogs import org.oppia.android.app.model.ProfileId import org.oppia.android.app.player.state.itemviewmodel.SplitScreenInteractionModule import org.oppia.android.app.recyclerview.RecyclerViewMatcher.Companion.atPositionOnView @@ -104,6 +105,9 @@ import org.oppia.android.testing.OppiaTestRule import org.oppia.android.testing.TestLogReportingModule import org.oppia.android.testing.firebase.TestAuthenticationModule import org.oppia.android.testing.junit.InitializeDefaultLocaleRule +import org.oppia.android.testing.logging.EventLogSubject +import org.oppia.android.testing.logging.EventLogSubject.Companion.assertThat +import org.oppia.android.testing.logging.EventLogSubject.LearnerDetailsContextSubject import org.oppia.android.testing.logging.SyncStatusTestModule import org.oppia.android.testing.logging.TestSyncStatusManager import org.oppia.android.testing.platformparameter.TestPlatformParameterModule @@ -118,6 +122,7 @@ import org.oppia.android.util.caching.AssetModule import org.oppia.android.util.caching.testing.CachingTestModule import org.oppia.android.util.gcsresource.GcsResourceModule import org.oppia.android.util.locale.LocaleProdModule +import org.oppia.android.util.locale.OppiaLocale import org.oppia.android.util.logging.EventLoggingConfigurationModule import org.oppia.android.util.logging.LoggerModule import org.oppia.android.util.logging.SyncStatusManager.SyncStatus @@ -131,7 +136,10 @@ import org.oppia.android.util.parser.image.GlideImageLoaderModule import org.oppia.android.util.parser.image.ImageParsingModule import org.robolectric.annotation.Config import org.robolectric.annotation.LooperMode +import java.security.MessageDigest +import java.util.Base64 import java.util.concurrent.TimeUnit +import java.util.zip.GZIPInputStream import javax.inject.Inject import javax.inject.Singleton @@ -148,11 +156,6 @@ import javax.inject.Singleton class ProfileAndDeviceIdFragmentTest { @get:Rule val initializeDefaultLocaleRule = InitializeDefaultLocaleRule() @get:Rule val oppiaTestRule = OppiaTestRule() - @get:Rule - var activityRule = - ActivityScenarioRule( - TestActivity.createIntent(ApplicationProvider.getApplicationContext()) - ) @Inject lateinit var profileTestHelper: ProfileTestHelper @Inject lateinit var testCoroutineDispatchers: TestCoroutineDispatchers @@ -164,6 +167,7 @@ class ProfileAndDeviceIdFragmentTest { @Inject lateinit var syncStatusManager: TestSyncStatusManager @Inject lateinit var learnerAnalyticsLogger: LearnerAnalyticsLogger @Inject lateinit var fakeAnalyticsEventLogger: FakeAnalyticsEventLogger + @Inject lateinit var machineLocale: OppiaLocale.MachineLocale private val clipboardManager by lazy { context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager @@ -194,559 +198,587 @@ class ProfileAndDeviceIdFragmentTest { @Test fun testFragment_withOnlyAdminProfile_hasThreeItems() { - initializeActivityAndAddFragment() - - // There should be three items: a header, a profile, and the sync status. - onView(withId(R.id.profile_and_device_id_recycler_view)).check(hasItemCount(count = 4)) + runWithLaunchedActivityAndAddedFragment { + // There should be three items: a header, a profile, and the sync status. + onView(withId(R.id.profile_and_device_id_recycler_view)).check(hasItemCount(count = 4)) + } } @Test fun testFragment_withOnlyAdminProfile_hasDeviceIdHeader() { - initializeActivityAndAddFragment() - - onDeviceIdLabelAt(position = 0).check(matches(isDisplayed())) + runWithLaunchedActivityAndAddedFragment { + onDeviceIdLabelAt(position = 0).check(matches(isDisplayed())) + } } @Test fun testFragment_hasDeviceId() { - initializeActivityAndAddFragment() - - onDeviceIdLabelAt(position = 0).check(matches(withText(containsString("0347439ebe8b")))) + runWithLaunchedActivityAndAddedFragment { + onDeviceIdLabelAt(position = 0).check(matches(withText(containsString("113e04cc09a3")))) + } } @Test fun testFragment_deviceId_hasCopyButton() { - initializeActivityAndAddFragment() - - onDeviceIdCopyButtonAt(position = 0).check(matches(isDisplayed())) + runWithLaunchedActivityAndAddedFragment { + onDeviceIdCopyButtonAt(position = 0).check(matches(isDisplayed())) + } } @Test fun testFragment_deviceId_clickCopyButton_copiesDeviceIdToClipboard() { - initializeActivityAndAddFragment() - - onDeviceIdCopyButtonAt(position = 0).perform(click()) - testCoroutineDispatchers.runCurrent() + runWithLaunchedActivityAndAddedFragment { + onDeviceIdCopyButtonAt(position = 0).perform(click()) + testCoroutineDispatchers.runCurrent() + } val clipData = getCurrentClipData() assertThat(clipData?.description?.label).isEqualTo("Oppia installation ID") assertThat(clipData?.itemCount).isEqualTo(1) - assertThat(clipData?.getItemAt(0)?.text).isEqualTo("0347439ebe8b") + assertThat(clipData?.getItemAt(0)?.text).isEqualTo("113e04cc09a3") } @Test fun testFragment_withOnlyAdminProfile_hasOneProfileListed() { - initializeActivityAndAddFragment() - - onProfileNameAt(position = 1).check(matches(isDisplayed())) + runWithLaunchedActivityAndAddedFragment { + onProfileNameAt(position = 1).check(matches(isDisplayed())) + } } @Test fun testFragment_profileEntry_hasProfileName() { - initializeActivityAndAddFragment() - - onProfileNameAt(position = 1).check(matches(withText("Admin"))) + runWithLaunchedActivityAndAddedFragment { + onProfileNameAt(position = 1).check(matches(withText("Admin"))) + } } @Test fun testFragment_profileEntry_hasLearnerId() { - initializeActivityAndAddFragment() - - onLearnerIdAt(position = 1).check(matches(withText("a9fe66ab"))) + runWithLaunchedActivityAndAddedFragment { + onLearnerIdAt(position = 1).check(matches(withText("8dcbbd21"))) + } } @Test fun testFragment_profileEntry_hasCopyButton() { - initializeActivityAndAddFragment() - - onLearnerIdCopyButtonAt(position = 1).check(matches(isDisplayed())) + runWithLaunchedActivityAndAddedFragment { + onLearnerIdCopyButtonAt(position = 1).check(matches(isDisplayed())) + } } @Test fun testFragment_profileEntry_clickFirstCopyButton_copiesAdminLearnerIdToClipboard() { - initializeActivityAndAddFragment() - - onLearnerIdCopyButtonAt(position = 1).perform(click()) - testCoroutineDispatchers.runCurrent() + runWithLaunchedActivityAndAddedFragment { + onLearnerIdCopyButtonAt(position = 1).perform(click()) + testCoroutineDispatchers.runCurrent() + } val clipData = getCurrentClipData() assertThat(clipData?.description?.label).isEqualTo("Admin's learner ID") assertThat(clipData?.itemCount).isEqualTo(1) - assertThat(clipData?.getItemAt(0)?.text).isEqualTo("a9fe66ab") + assertThat(clipData?.getItemAt(0)?.text).isEqualTo("8dcbbd21") } @Test fun testFragment_multipleProfiles_listsAllProfiles() { profileTestHelper.addMoreProfiles(numProfiles = 5) - initializeActivityAndAddFragment() - - // Header + admin + 5 new profiles + sync status = 8 items. - onView(withId(R.id.profile_and_device_id_recycler_view)).check(hasItemCount(count = 9)) + runWithLaunchedActivityAndAddedFragment { + // Header + admin + 5 new profiles + sync status = 8 items. + onView(withId(R.id.profile_and_device_id_recycler_view)).check(hasItemCount(count = 9)) + } } @Test fun testFragment_multipleProfiles_adminIsFirst() { profileTestHelper.addMoreProfiles(numProfiles = 5) - initializeActivityAndAddFragment() - - onProfileNameAt(position = 1).check(matches(withText("Admin"))) + runWithLaunchedActivityAndAddedFragment { + onProfileNameAt(position = 1).check(matches(withText("Admin"))) + } } @Test fun testFragment_multipleProfiles_secondEntryHasDifferentName() { profileTestHelper.addMoreProfiles(numProfiles = 5) - initializeActivityAndAddFragment() - - // The second entry is not the admin. - onProfileNameAt(position = 2).check(matches(withText("A"))) + runWithLaunchedActivityAndAddedFragment { + // The second entry is not the admin. + onProfileNameAt(position = 2).check(matches(withText("A"))) + } } @Test fun testFragment_multipleProfiles_secondEntryHasDifferentLearnerIdThanFirst() { profileTestHelper.addMoreProfiles(numProfiles = 5) - initializeActivityAndAddFragment() - - // The second profile has a different learner ID. - onLearnerIdAt(position = 1).check(matches(withText("a9fe66ab"))) - onLearnerIdAt(position = 2).check(matches(withText("6e563e2f"))) + runWithLaunchedActivityAndAddedFragment { + // The second profile has a different learner ID. + onLearnerIdAt(position = 1).check(matches(withText("8dcbbd21"))) + onLearnerIdAt(position = 2).check(matches(withText("208663b0"))) + } } @Test fun testFragment_multipleProfiles_copySecondEntry_copiesDifferentLearnerIdThanFirst() { profileTestHelper.addMoreProfiles(numProfiles = 5) - initializeActivityAndAddFragment() - - onLearnerIdCopyButtonAt(position = 2).perform(click()) - testCoroutineDispatchers.runCurrent() + runWithLaunchedActivityAndAddedFragment { + onLearnerIdCopyButtonAt(position = 2).perform(click()) + testCoroutineDispatchers.runCurrent() + } val clipData = getCurrentClipData() assertThat(clipData?.description?.label).isEqualTo("A's learner ID") assertThat(clipData?.itemCount).isEqualTo(1) - assertThat(clipData?.getItemAt(0)?.text).isEqualTo("6e563e2f") + assertThat(clipData?.getItemAt(0)?.text).isEqualTo("208663b0") } @Test fun testFragment_initialState_deviceIdCopyButtonHasCopyLabel() { - initializeActivityAndAddFragment() - - onDeviceIdCopyButtonAt(position = 0).check(matches(withText("Copy"))) + runWithLaunchedActivityAndAddedFragment { + onDeviceIdCopyButtonAt(position = 0).check(matches(withText("Copy"))) + } } @Test fun testFragment_adminProfile_initialState_learnerIdCopyButtonHasCopyLabel() { - initializeActivityAndAddFragment() - - onLearnerIdCopyButtonAt(position = 1).check(matches(withText("Copy"))) + runWithLaunchedActivityAndAddedFragment { + onLearnerIdCopyButtonAt(position = 1).check(matches(withText("Copy"))) + } } @Test fun testFragment_adminProfile_clickDeviceIdCopyButton_deviceIdIsCopiedButNotLearnerId() { - initializeActivityAndAddFragment() - - onDeviceIdCopyButtonAt(position = 0).perform(click()) - testCoroutineDispatchers.runCurrent() + runWithLaunchedActivityAndAddedFragment { + onDeviceIdCopyButtonAt(position = 0).perform(click()) + testCoroutineDispatchers.runCurrent() - onDeviceIdCopyButtonAt(position = 0).check(matches(withText("Copied"))) - onLearnerIdCopyButtonAt(position = 1).check(matches(withText("Copy"))) + onDeviceIdCopyButtonAt(position = 0).check(matches(withText("Copied"))) + onLearnerIdCopyButtonAt(position = 1).check(matches(withText("Copy"))) + } } @Test fun testFragment_adminProfile_clickLearnerIdCopyButton_learnerIdIsCopiedButNotDeviceId() { - initializeActivityAndAddFragment() - - onLearnerIdCopyButtonAt(position = 1).perform(click()) - testCoroutineDispatchers.runCurrent() + runWithLaunchedActivityAndAddedFragment { + onLearnerIdCopyButtonAt(position = 1).perform(click()) + testCoroutineDispatchers.runCurrent() - onDeviceIdCopyButtonAt(position = 0).check(matches(withText("Copy"))) - onLearnerIdCopyButtonAt(position = 1).check(matches(withText("Copied"))) + onDeviceIdCopyButtonAt(position = 0).check(matches(withText("Copy"))) + onLearnerIdCopyButtonAt(position = 1).check(matches(withText("Copied"))) + } } @Test fun testFragment_adminProfile_clickLearnerIdCopyButton_copyInOtherApp_nothingIsCopied() { - initializeActivityAndAddFragment() - onLearnerIdCopyButtonAt(position = 1).perform(click()) - testCoroutineDispatchers.runCurrent() + runWithLaunchedActivityAndAddedFragment { + onLearnerIdCopyButtonAt(position = 1).perform(click()) + testCoroutineDispatchers.runCurrent() - updateClipDataAsThoughFromAnotherApp() + updateClipDataAsThoughFromAnotherApp() - // Changing the clipboard in a different app should reset the labels. - onDeviceIdCopyButtonAt(position = 0).check(matches(withText("Copy"))) - onLearnerIdCopyButtonAt(position = 1).check(matches(withText("Copy"))) + // Changing the clipboard in a different app should reset the labels. + onDeviceIdCopyButtonAt(position = 0).check(matches(withText("Copy"))) + onLearnerIdCopyButtonAt(position = 1).check(matches(withText("Copy"))) + } } @Test fun testFragment_adminProfile_clickLearnerIdCopyButton_rotate_learnerIdStillCopied() { - initializeActivityAndAddFragment() - onLearnerIdCopyButtonAt(position = 1).perform(click()) - testCoroutineDispatchers.runCurrent() + runWithLaunchedActivityAndAddedFragment { + onLearnerIdCopyButtonAt(position = 1).perform(click()) + testCoroutineDispatchers.runCurrent() - onView(isRoot()).perform(orientationLandscape()) - testCoroutineDispatchers.runCurrent() + onView(isRoot()).perform(orientationLandscape()) + testCoroutineDispatchers.runCurrent() - // The button label should be restored after a rotation. - onDeviceIdCopyButtonAt(position = 0).check(matches(withText("Copy"))) - onLearnerIdCopyButtonAt(position = 1).check(matches(withText("Copied"))) + // The button label should be restored after a rotation. + onDeviceIdCopyButtonAt(position = 0).check(matches(withText("Copy"))) + onLearnerIdCopyButtonAt(position = 1).check(matches(withText("Copied"))) + } } @Test fun testFragment_multipleProfiles_rotate_profilesStillPresent() { profileTestHelper.addMoreProfiles(numProfiles = 5) - initializeActivityAndAddFragment() - onView(isRoot()).perform(orientationLandscape()) - testCoroutineDispatchers.runCurrent() + runWithLaunchedActivityAndAddedFragment { + onView(isRoot()).perform(orientationLandscape()) + testCoroutineDispatchers.runCurrent() - onView(withId(R.id.profile_and_device_id_recycler_view)).check(hasItemCount(count = 9)) + onView(withId(R.id.profile_and_device_id_recycler_view)).check(hasItemCount(count = 9)) + } } @Test fun testFragment_firstEntry_noAdminEvents_hasZeroAdminEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - onAwaitingUploadLearnerEventsCountAt(position = 1).check(matches(withText("0"))) - onUploadedLearnerEventsCountAt(position = 1).check(matches(withText("0"))) + runWithLaunchedActivityAndAddedFragment { + onAwaitingUploadLearnerEventsCountAt(position = 1).check(matches(withText("0"))) + onUploadedLearnerEventsCountAt(position = 1).check(matches(withText("0"))) + } } @Test fun testFragment_firstEntry_adminEvents_notUploaded_hasSomeAdminEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - // Log a couple of events. - logTwoAnalyticsEvents(profileId = ADMIN_PROFILE_ID) + // Log a couple of events. + logTwoAnalyticsEvents(profileId = ADMIN_PROFILE_ID) - // Two are awaiting upload, but neither have been uploaded yet. - onAwaitingUploadLearnerEventsCountAt(position = 1).check(matches(withText("2"))) - onUploadedLearnerEventsCountAt(position = 1).check(matches(withText("0"))) + // Two are awaiting upload, but neither have been uploaded yet. + onAwaitingUploadLearnerEventsCountAt(position = 1).check(matches(withText("2"))) + onUploadedLearnerEventsCountAt(position = 1).check(matches(withText("0"))) + } } @Test fun testFragment_firstEntry_adminEvents_uploaded_hasSomeAdminEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - // Log a couple of events, upload them, then log one more event. - logTwoAnalyticsEvents(profileId = ADMIN_PROFILE_ID) - connectOnlyToFlushWorkerQueue() - logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) + // Log a couple of events, upload them, then log one more event. + logTwoAnalyticsEvents(profileId = ADMIN_PROFILE_ID) + connectOnlyToFlushWorkerQueue() + logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) - // Two should be uploaded, and one waiting upload. - onAwaitingUploadLearnerEventsCountAt(position = 1).check(matches(withText("1"))) - onUploadedLearnerEventsCountAt(position = 1).check(matches(withText("2"))) + // Two should be uploaded, and one waiting upload. + onAwaitingUploadLearnerEventsCountAt(position = 1).check(matches(withText("1"))) + onUploadedLearnerEventsCountAt(position = 1).check(matches(withText("2"))) + } } @Test fun testFragment_firstEntry_noGenericEvents_hasZeroGenericEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - onAwaitingUploadUncategorizedEventsCountAt(position = 1).check(matches(withText("0"))) - onUploadedUncategorizedEventsCountAt(position = 1).check(matches(withText("0"))) + runWithLaunchedActivityAndAddedFragment { + onAwaitingUploadUncategorizedEventsCountAt(position = 1).check(matches(withText("0"))) + onUploadedUncategorizedEventsCountAt(position = 1).check(matches(withText("0"))) + } } @Test fun testFragment_firstEntry_genericEvents_notUploaded_hasSomeGenericEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - // Log a couple of events off of the admin profile. - logTwoAnalyticsEvents(profileId = null) + // Log a couple of events off of the admin profile. + logTwoAnalyticsEvents(profileId = null) - onAwaitingUploadUncategorizedEventsCountAt(position = 1).check(matches(withText("2"))) - onUploadedUncategorizedEventsCountAt(position = 1).check(matches(withText("0"))) + onAwaitingUploadUncategorizedEventsCountAt(position = 1).check(matches(withText("2"))) + onUploadedUncategorizedEventsCountAt(position = 1).check(matches(withText("0"))) + } } @Test fun testFragment_firstEntry_genericEvents_uploaded_hasSomeGenericEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - // Log a couple of events, upload them, then log one more event, off of the admin profile. - logTwoAnalyticsEvents(profileId = null) - connectOnlyToFlushWorkerQueue() - logAnalyticsEvent(profileId = null) + // Log a couple of events, upload them, then log one more event, off of the admin profile. + logTwoAnalyticsEvents(profileId = null) + connectOnlyToFlushWorkerQueue() + logAnalyticsEvent(profileId = null) - onAwaitingUploadUncategorizedEventsCountAt(position = 1).check(matches(withText("1"))) - onUploadedUncategorizedEventsCountAt(position = 1).check(matches(withText("2"))) + onAwaitingUploadUncategorizedEventsCountAt(position = 1).check(matches(withText("1"))) + onUploadedUncategorizedEventsCountAt(position = 1).check(matches(withText("2"))) + } } @Test fun testFragment_firstEntry_mixOfAdminAndGenericEvents_someUploaded_reportsAllEvents() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - - // Log & upload a mix of events with and without the admin profile. - logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) - logThreeAnalyticsEvents(profileId = null) - connectOnlyToFlushWorkerQueue() - logAnalyticsEvent(profileId = null) - logTwoAnalyticsEvents(profileId = ADMIN_PROFILE_ID) - - // Event counts should be represented in the correct places. - onAwaitingUploadLearnerEventsCountAt(position = 1).check(matches(withText("2"))) - onUploadedLearnerEventsCountAt(position = 1).check(matches(withText("1"))) - onAwaitingUploadUncategorizedEventsCountAt(position = 1).check(matches(withText("1"))) - onUploadedUncategorizedEventsCountAt(position = 1).check(matches(withText("3"))) + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + + // Log & upload a mix of events with and without the admin profile. + logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) + logThreeAnalyticsEvents(profileId = null) + connectOnlyToFlushWorkerQueue() + logAnalyticsEvent(profileId = null) + logTwoAnalyticsEvents(profileId = ADMIN_PROFILE_ID) + + // Event counts should be represented in the correct places. + onAwaitingUploadLearnerEventsCountAt(position = 1).check(matches(withText("2"))) + onUploadedLearnerEventsCountAt(position = 1).check(matches(withText("1"))) + onAwaitingUploadUncategorizedEventsCountAt(position = 1).check(matches(withText("1"))) + onUploadedUncategorizedEventsCountAt(position = 1).check(matches(withText("3"))) + } } @Test fun testFragment_secondEntry_noLearnerEvents_hasZeroLearnerEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - onAwaitingUploadLearnerEventsCountAt(position = 2).check(matches(withText("0"))) - onUploadedLearnerEventsCountAt(position = 2).check(matches(withText("0"))) + runWithLaunchedActivityAndAddedFragment { + onAwaitingUploadLearnerEventsCountAt(position = 2).check(matches(withText("0"))) + onUploadedLearnerEventsCountAt(position = 2).check(matches(withText("0"))) + } } @Test fun testFragment_secondEntry_learnerEvents_notUploaded_hasSomeLearnerEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - // Log a couple of events. - logTwoAnalyticsEvents(profileId = LEARNER_PROFILE_ID_0) + // Log a couple of events. + logTwoAnalyticsEvents(profileId = LEARNER_PROFILE_ID_0) - // Two are awaiting upload, but neither have been uploaded yet. - onAwaitingUploadLearnerEventsCountAt(position = 2).check(matches(withText("2"))) - onUploadedLearnerEventsCountAt(position = 2).check(matches(withText("0"))) + // Two are awaiting upload, but neither have been uploaded yet. + onAwaitingUploadLearnerEventsCountAt(position = 2).check(matches(withText("2"))) + onUploadedLearnerEventsCountAt(position = 2).check(matches(withText("0"))) + } } @Test fun testFragment_secondEntry_learnerEvents_uploaded_hasSomeLearnerEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - // Log a couple of events, upload them, then log one more event. - logTwoAnalyticsEvents(profileId = LEARNER_PROFILE_ID_0) - connectOnlyToFlushWorkerQueue() - logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) + // Log a couple of events, upload them, then log one more event. + logTwoAnalyticsEvents(profileId = LEARNER_PROFILE_ID_0) + connectOnlyToFlushWorkerQueue() + logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) - // Two should be uploaded, and one waiting upload. - onAwaitingUploadLearnerEventsCountAt(position = 2).check(matches(withText("1"))) - onUploadedLearnerEventsCountAt(position = 2).check(matches(withText("2"))) + // Two should be uploaded, and one waiting upload. + onAwaitingUploadLearnerEventsCountAt(position = 2).check(matches(withText("1"))) + onUploadedLearnerEventsCountAt(position = 2).check(matches(withText("2"))) + } } @Test fun testFragment_secondEntry_learnerEvents_hasZeroAdminOrGenericEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - - // Log a couple of events, upload them, then log one more event, for a learner profile. - logTwoAnalyticsEvents(profileId = LEARNER_PROFILE_ID_0) - connectOnlyToFlushWorkerQueue() - logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) - - // The admin profile's event counts shouldn't change since the only logged events were for a - // specific learner profile. - onAwaitingUploadLearnerEventsCountAt(position = 1).check(matches(withText("0"))) - onUploadedLearnerEventsCountAt(position = 1).check(matches(withText("0"))) - onAwaitingUploadUncategorizedEventsCountAt(position = 1).check(matches(withText("0"))) - onUploadedUncategorizedEventsCountAt(position = 1).check(matches(withText("0"))) + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + + // Log a couple of events, upload them, then log one more event, for a learner profile. + logTwoAnalyticsEvents(profileId = LEARNER_PROFILE_ID_0) + connectOnlyToFlushWorkerQueue() + logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) + + // The admin profile's event counts shouldn't change since the only logged events were for a + // specific learner profile. + onAwaitingUploadLearnerEventsCountAt(position = 1).check(matches(withText("0"))) + onUploadedLearnerEventsCountAt(position = 1).check(matches(withText("0"))) + onAwaitingUploadUncategorizedEventsCountAt(position = 1).check(matches(withText("0"))) + onUploadedUncategorizedEventsCountAt(position = 1).check(matches(withText("0"))) + } } @Test fun testFragment_secondEntry_adminAndGenericEvents_uploaded_hasZeroLearnerEventsReported() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - - // Log a couple of events generically and for the admin profile. - logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) - logAnalyticsEvent(profileId = null) - connectOnlyToFlushWorkerQueue() - logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) - logAnalyticsEvent(profileId = null) - - // No events should be reported for the learner since it didn't have any events uploaded. - onAwaitingUploadLearnerEventsCountAt(position = 2).check(matches(withText("0"))) - onUploadedLearnerEventsCountAt(position = 2).check(matches(withText("0"))) + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + + // Log a couple of events generically and for the admin profile. + logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) + logAnalyticsEvent(profileId = null) + connectOnlyToFlushWorkerQueue() + logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) + logAnalyticsEvent(profileId = null) + + // No events should be reported for the learner since it didn't have any events uploaded. + onAwaitingUploadLearnerEventsCountAt(position = 2).check(matches(withText("0"))) + onUploadedLearnerEventsCountAt(position = 2).check(matches(withText("0"))) + } } @Test fun testFragment_initialState_profileDataHasYetToBeCollected() { - initializeActivityAndAddFragment() - - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("No data has been collected yet to upload")))) + runWithLaunchedActivityAndAddedFragment { + onSyncStatusAt(position = 2) + .check(matches(withText(containsString("No data has been collected yet to upload")))) + } } @Test fun testFragment_initialState_wait_profileDataHasYetToBeCollected() { - initializeActivityAndAddFragment() - - testCoroutineDispatchers.advanceTimeBy(delayTimeMillis = TimeUnit.SECONDS.toMillis(1)) + runWithLaunchedActivityAndAddedFragment { + testCoroutineDispatchers.advanceTimeBy(delayTimeMillis = TimeUnit.SECONDS.toMillis(1)) - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("No data has been collected yet to upload")))) + onSyncStatusAt(position = 2) + .check(matches(withText(containsString("No data has been collected yet to upload")))) + } } @Test fun testFragment_eventLogged_waitingForUpload_indicatorTextMentionsWaiting() { - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - - // Enqueue the event, but don't actually begin uploading it, then reconnect to the network. Note - // that the extra event log is a slight hack to force a refresh of the status indicator (since - // network changes are polled when there are other changes to represent rather than being - // actively "pushed" by the system). - logAnalyticsEvent() - connectNetwork() - logAnalyticsEvent() - - // The status indicator is suggesting that events can be uploaded (and there are some available - // to upload), they just haven't been scheduled yet. - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("Waiting to schedule data uploading worker…")))) + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + + // Enqueue the event, but don't actually begin uploading it, then reconnect to the network. + // Note that the extra event log is a slight hack to force a refresh of the status indicator + // (since network changes are polled when there are other changes to represent rather than + // being actively "pushed" by the system). + logAnalyticsEvent() + connectNetwork() + logAnalyticsEvent() + + // The status indicator is suggesting that events can be uploaded (and there are some + // available to upload), they just haven't been scheduled yet. + onSyncStatusAt(position = 2) + .check(matches(withText(containsString("Waiting to schedule data uploading worker…")))) + } } @Test fun testFragment_eventLogged_waitingForUpload_uploadStarted_profileDataIsCurrentlyUploading() { - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - // Unfortunately, it's tricky to pause the actual upload worker so this is a hacky way to - // produce the same situation to ensure the label is correct. - logAnalyticsEvent() - syncStatusManager.forceSyncStatus(SyncStatus.DATA_UPLOADING) - testCoroutineDispatchers.runCurrent() + // Unfortunately, it's tricky to pause the actual upload worker so this is a hacky way to + // produce the same situation to ensure the label is correct. + logAnalyticsEvent() + syncStatusManager.forceSyncStatus(SyncStatus.DATA_UPLOADING) + testCoroutineDispatchers.runCurrent() - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("Profile data is currently uploading")))) + onSyncStatusAt(position = 2) + .check(matches(withText(containsString("Profile data is currently uploading")))) + } } @Test fun testFragment_noConnectivity_indicatorTextMentionsDataCannotBeUploaded() { - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - - // Enqueue an event but don't reconnect to the network. - logAnalyticsEvent() - - // The status indicator is suggesting that internet connectivity needs to resume in order to - // upload events. - onSyncStatusAt(position = 2) - .check( - matches( - withText( - containsString( - "Please connect to a WiFi or Cellular network in order to upload profile data" + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + + // Enqueue an event but don't reconnect to the network. + logAnalyticsEvent() + + // The status indicator is suggesting that internet connectivity needs to resume in order to + // upload events. + onSyncStatusAt(position = 2) + .check( + matches( + withText( + containsString( + "Please connect to a WiFi or Cellular network in order to upload profile data" + ) ) ) ) - ) + } } @Test fun testFragment_eventLogged_waitForUpload_profileDataIsUploaded() { - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - logAnalyticsEvent() - connectNetwork() - flushEventWorkerQueue() + logAnalyticsEvent() + connectNetwork() + flushEventWorkerQueue() - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("All profile data has been uploaded")))) + onSyncStatusAt(position = 2) + .check(matches(withText(containsString("All profile data has been uploaded")))) + } } @Test fun testFragment_eventLogged_uploadError_profileDataHasError() { - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - logAnalyticsEvent() + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + logAnalyticsEvent() - // An upload error can currently only be simulated by directly influencing the sync manager. - syncStatusManager.forceSyncStatus(SyncStatus.UPLOAD_ERROR) - testCoroutineDispatchers.runCurrent() + // An upload error can currently only be simulated by directly influencing the sync manager. + syncStatusManager.forceSyncStatus(SyncStatus.UPLOAD_ERROR) + testCoroutineDispatchers.runCurrent() - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("Something went wrong when trying to upload events")))) + onSyncStatusAt(position = 2) + .check( + matches(withText(containsString("Something went wrong when trying to upload events"))) + ) + } } @Test fun testFragment_eventLogged_uploadError_anotherLogged_wait_profileDataIsUploading() { - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - logAnalyticsEvent() - syncStatusManager.reportUploadError() - testCoroutineDispatchers.runCurrent() - - logAnalyticsEvent() - connectNetwork() - flushEventWorkerQueue() - - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("All profile data has been uploaded")))) + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + logAnalyticsEvent() + syncStatusManager.reportUploadError() + testCoroutineDispatchers.runCurrent() + + logAnalyticsEvent() + connectNetwork() + flushEventWorkerQueue() + + onSyncStatusAt(position = 2) + .check(matches(withText(containsString("All profile data has been uploaded")))) + } } @Test fun testFragment_rotate_profileDataHasYetToBeCollected() { - initializeActivityAndAddFragment() + runWithLaunchedActivityAndAddedFragment { + onView(isRoot()).perform(orientationLandscape()) + testCoroutineDispatchers.runCurrent() - onView(isRoot()).perform(orientationLandscape()) - testCoroutineDispatchers.runCurrent() - - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("No data has been collected yet to upload")))) + onSyncStatusAt(position = 2) + .check(matches(withText(containsString("No data has been collected yet to upload")))) + } } @Test fun testFragment_eventLogged_waitingForUpload_rotate_profileDataIsCurrentlyUploading() { - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - logAnalyticsEvent() - syncStatusManager.forceSyncStatus(SyncStatus.DATA_UPLOADING) - testCoroutineDispatchers.runCurrent() + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + logAnalyticsEvent() + syncStatusManager.forceSyncStatus(SyncStatus.DATA_UPLOADING) + testCoroutineDispatchers.runCurrent() - onView(isRoot()).perform(orientationLandscape()) - testCoroutineDispatchers.runCurrent() + onView(isRoot()).perform(orientationLandscape()) + testCoroutineDispatchers.runCurrent() - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("Profile data is currently uploading")))) + onSyncStatusAt(position = 2) + .check(matches(withText(containsString("Profile data is currently uploading")))) + } } @Test fun testFragment_eventLogged_waitForUpload_rotate_profileDataIsUploaded() { - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - logAnalyticsEvent() - connectNetwork() - flushEventWorkerQueue() + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + logAnalyticsEvent() + connectNetwork() + flushEventWorkerQueue() - onView(isRoot()).perform(orientationLandscape()) - testCoroutineDispatchers.runCurrent() + onView(isRoot()).perform(orientationLandscape()) + testCoroutineDispatchers.runCurrent() - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("All profile data has been uploaded")))) + onSyncStatusAt(position = 2) + .check(matches(withText(containsString("All profile data has been uploaded")))) + } } @Test fun testFragment_eventsLogged_uploadError_rotate_profileDataHasError() { - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - logAnalyticsEvent() - syncStatusManager.forceSyncStatus(SyncStatus.UPLOAD_ERROR) - testCoroutineDispatchers.runCurrent() - - onView(isRoot()).perform(orientationLandscape()) - testCoroutineDispatchers.runCurrent() - - onSyncStatusAt(position = 2) - .check(matches(withText(containsString("Something went wrong when trying to upload events")))) + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + logAnalyticsEvent() + syncStatusManager.forceSyncStatus(SyncStatus.UPLOAD_ERROR) + testCoroutineDispatchers.runCurrent() + + onView(isRoot()).perform(orientationLandscape()) + testCoroutineDispatchers.runCurrent() + + onSyncStatusAt(position = 2) + .check( + matches(withText(containsString("Something went wrong when trying to upload events"))) + ) + } } @Test @@ -754,127 +786,166 @@ class ProfileAndDeviceIdFragmentTest { // Use fake time so that the generated event logs are consistent across runs. fakeOppiaClock.setFakeTimeMode(FakeOppiaClock.FakeTimeMode.MODE_FIXED_FAKE_TIME) profileTestHelper.addMoreProfiles(numProfiles = 2) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - - // Log & upload some events, then enqueue others. - logThreeAnalyticsEvents(profileId = null) - logTwoAnalyticsEvents(profileId = ADMIN_PROFILE_ID) - logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) - logTwoAnalyticsEvents(profileId = LEARNER_PROFILE_ID_1) - connectOnlyToFlushWorkerQueue() - logAnalyticsEvent(profileId = null) - logThreeAnalyticsEvents(profileId = ADMIN_PROFILE_ID) - logTwoAnalyticsEvents(profileId = LEARNER_PROFILE_ID_0) - logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_1) - connectNetwork() - logAnalyticsEvent(profileId = null) // Log an event to trigger tracking the network change. - - onShareIdsAndEventsButtonAt(position = 5).perform(click()) - testCoroutineDispatchers.runCurrent() - - val expectedShareText = - """ - Oppia app installation ID: 932459768f39 - - Profile name: Admin, learner ID: a9fe66ab - - Uploading learner events: 3 - - Uploaded learner events: 2 - - Uploading uncategorized events: 1 - - Uploaded uncategorized events: 4 - - Profile name: A, learner ID: 6e563e2f - - Uploading learner events: 2 - - Uploaded learner events: 1 - - Profile name: B, learner ID: 5c0710a2 - - Uploading learner events: 1 - - Uploaded learner events: 2 - Current sync status: Waiting to schedule data uploading worker…. - Event log encoding integrity checks: - - First 40 chars of encoded string: H4sIAAAAAAAAAOPSlGBUUj3FqMTFX5JaXBKfk5pY - - Last 40 chars of encoded string: BzGNlJIepORoISdAydHERJ4m4sMLAFFY60EUAwAA - - SHA-1 hash (unwrapped event string): 76f7a26348b4034787982f9505c6b5697efc6567 - - Total event string length (unwrapped): 140 - Encoded event logs: - H4sIAAAAAAAAAOPSlGBUUj3FqMTFX5JaXBKfk5pYlJdaFJ+ZIgQRyMwrLknMyQEKcBkSrVSLwYjBisGJ - gU5ajEnVwsTBSDdNTELEBzGNlJIepORoISdAydHERJ4m4sMLAFFY60EUAwAA - """.trimIndent() - val intents = getIntents() - assertThat(intents).hasSize(1) - assertThat(intents.single()).hasAction(Intent.ACTION_SEND) - assertThat(intents.single()).hasType("text/plain") - assertThat(intents.single()).extras().containsKey(Intent.EXTRA_TEXT) - assertThat(intents.single()).extras().string(Intent.EXTRA_TEXT).isEqualTo(expectedShareText) + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + + // Log & upload some events, then enqueue others. + logThreeAnalyticsEvents(profileId = null) + logTwoAnalyticsEvents(profileId = ADMIN_PROFILE_ID) + logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) + logTwoAnalyticsEvents(profileId = LEARNER_PROFILE_ID_1) + connectOnlyToFlushWorkerQueue() + logAnalyticsEvent(profileId = null) + logThreeAnalyticsEvents(profileId = ADMIN_PROFILE_ID) + logTwoAnalyticsEvents(profileId = LEARNER_PROFILE_ID_0) + logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_1) + connectNetwork() + logAnalyticsEvent(profileId = null) // Log an event to trigger tracking the network change. + + onShareIdsAndEventsButtonAt(position = 5).perform(click()) + testCoroutineDispatchers.runCurrent() + + val expectedShareTextPattern = + """ + Oppia app installation ID: 113e04cc09a3 + - Profile name: Admin, learner ID: 8dcbbd21 + - Uploading learner events: 3 + - Uploaded learner events: 2 + - Uploading uncategorized events: 1 + - Uploaded uncategorized events: 4 + - Profile name: A, learner ID: 208663b0 + - Uploading learner events: 2 + - Uploaded learner events: 1 + - Profile name: B, learner ID: 92d0c6e2 + - Uploading learner events: 1 + - Uploaded learner events: 2 + Current sync status: Waiting to schedule data uploading worker…. + Event log encoding integrity checks: + - First 40 chars of encoded string: ([\p{Alnum}/\\+=]+) + - Last 40 chars of encoded string: ([\p{Alnum}/\\+=]+) + - SHA-1 hash \(unwrapped event string\): (\p{XDigit}+) + - Total event string length \(unwrapped\): (\p{Digit}+) + Encoded event logs:([\p{Alnum}/+=\p{Space}]+) + """.trimIndent().toRegex() + val intents = getIntents() + val extraText = intents.singleOrNull()?.getStringExtra(Intent.EXTRA_TEXT) + assertThat(intents).hasSize(1) + assertThat(intents.single()).hasAction(Intent.ACTION_SEND) + assertThat(intents.single()).hasType("text/plain") + assertThat(intents.single()).extras().containsKey(Intent.EXTRA_TEXT) + assertThat(extraText).matches(expectedShareTextPattern.toPattern()) + val (encodingPrefix, encodingSuffix, shaHash, encodingLength, rawEncodedLogs) = + extraText?.let { expectedShareTextPattern.matchEntire(it) }?.destructured!! + val unwrappedEncodedLogs = rawEncodedLogs.trim().replace(" ", "").replace("\n", "") + // Verify that the correct _values_ are being outputted, even if the specific values might + // differ slightly (depending on the running platform). + assertThat(encodingPrefix).isEqualTo(unwrappedEncodedLogs.take(40)) + assertThat(encodingSuffix).isEqualTo(unwrappedEncodedLogs.takeLast(40)) + assertThat(shaHash).isEqualTo(unwrappedEncodedLogs.computeSha1Hash()) + assertThat(encodingLength.toInt()).isEqualTo(unwrappedEncodedLogs.length) + // Verify the encoded events themselves are correct by decoding them and analyzing the loaded + // proto (since the string can vary somewhat). + val eventLogs = decodeEventLogString(unwrappedEncodedLogs) + assertThat(eventLogs.eventLogsToUploadCount).isEqualTo(7) + assertThat(eventLogs.uploadedEventLogsCount).isEqualTo(9) + assertThat(eventLogs.eventLogsToUploadList[0]).hasCommonPropsWithNoProfileId() + assertThat(eventLogs.eventLogsToUploadList[1]).hasCommonPropsWithProfile(ADMIN_PROFILE_ID) + assertThat(eventLogs.eventLogsToUploadList[2]).hasCommonPropsWithProfile(ADMIN_PROFILE_ID) + assertThat(eventLogs.eventLogsToUploadList[3]).hasCommonPropsWithProfile(ADMIN_PROFILE_ID) + assertThat(eventLogs.eventLogsToUploadList[4]).hasCommonPropsWithProfile(LEARNER_PROFILE_ID_0) + assertThat(eventLogs.eventLogsToUploadList[5]).hasCommonPropsWithProfile(LEARNER_PROFILE_ID_0) + assertThat(eventLogs.eventLogsToUploadList[6]).hasCommonPropsWithProfile(LEARNER_PROFILE_ID_1) + assertThat(eventLogs.uploadedEventLogsList[0]).hasCommonPropsWithNoProfileId() + assertThat(eventLogs.uploadedEventLogsList[1]).hasCommonPropsWithNoProfileId() + assertThat(eventLogs.uploadedEventLogsList[2]).hasCommonPropsWithNoProfileId() + assertThat(eventLogs.uploadedEventLogsList[3]).hasCommonPropsWithProfile(ADMIN_PROFILE_ID) + assertThat(eventLogs.uploadedEventLogsList[4]).hasCommonPropsWithProfile(ADMIN_PROFILE_ID) + assertThat(eventLogs.uploadedEventLogsList[5]).hasCommonPropsWithProfile(LEARNER_PROFILE_ID_0) + assertThat(eventLogs.uploadedEventLogsList[6]).hasCommonPropsWithProfile(LEARNER_PROFILE_ID_1) + assertThat(eventLogs.uploadedEventLogsList[7]).hasCommonPropsWithProfile(LEARNER_PROFILE_ID_1) + assertThat(eventLogs.uploadedEventLogsList[8]).hasCommonPropsWithNoProfileId() + } } @Test fun testFragment_noEventsPending_uploadLogsButtonDisabled() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - // The upload button should be disabled when there are no events to upload. - onUploadLogsButtonAt(position = 4).check(matches(not(isEnabled()))) + // The upload button should be disabled when there are no events to upload. + onUploadLogsButtonAt(position = 4).check(matches(not(isEnabled()))) + } } @Test fun testFragment_multipleEventsPending_noConnection_uploadLogsButtonDisabled() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - logAnalyticsEvent(profileId = null) - logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) - logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) + logAnalyticsEvent(profileId = null) + logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) + logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) - // The button is still disabled since there's no internet connection. - onUploadLogsButtonAt(position = 4).check(matches(not(isEnabled()))) + // The button is still disabled since there's no internet connection. + onUploadLogsButtonAt(position = 4).check(matches(not(isEnabled()))) + } } @Test fun testFragment_multipleEventsPending_uploadLogsButtonEnabled() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. - logAnalyticsEvent(profileId = null) - logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) - logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) - connectNetwork() - logAnalyticsEvent(profileId = null) // Log an event to trigger tracking the network change. + logAnalyticsEvent(profileId = null) + logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) + logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) + connectNetwork() + logAnalyticsEvent(profileId = null) // Log an event to trigger tracking the network change. - // With events pending & connectivity, the upload button should now be available to press. - onUploadLogsButtonAt(position = 4).check(matches(isEnabled())) + // With events pending & connectivity, the upload button should now be available to press. + onUploadLogsButtonAt(position = 4).check(matches(isEnabled())) + } } @Test fun testFragment_multipleEventsPending_clickUploadLogs_wait_uploadsEventLogs() { profileTestHelper.addMoreProfiles(numProfiles = 1) - initializeActivityAndAddFragment() - disconnectNetwork() // Ensure events are cached. - logAnalyticsEvent(profileId = null) - logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) - logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) - connectNetwork() - logAnalyticsEvent(profileId = null) // Log an event to trigger tracking the network change. - fakeAnalyticsEventLogger.clearAllEvents() - - // Click the 'upload logs' button and wait. - onUploadLogsButtonAt(position = 4).perform(click()) - testCoroutineDispatchers.runCurrent() - - // The events should be uploaded. - assertThat(fakeAnalyticsEventLogger.getEventListCount()).isEqualTo(3) + runWithLaunchedActivityAndAddedFragment { + disconnectNetwork() // Ensure events are cached. + logAnalyticsEvent(profileId = null) + logAnalyticsEvent(profileId = ADMIN_PROFILE_ID) + logAnalyticsEvent(profileId = LEARNER_PROFILE_ID_0) + connectNetwork() + logAnalyticsEvent(profileId = null) // Log an event to trigger tracking the network change. + fakeAnalyticsEventLogger.clearAllEvents() + + // Click the 'upload logs' button and wait. + onUploadLogsButtonAt(position = 4).perform(click()) + testCoroutineDispatchers.runCurrent() + + // The events should be uploaded. + assertThat(fakeAnalyticsEventLogger.getEventListCount()).isEqualTo(3) + } } - private fun initializeActivityAndAddFragment() { - activityRule.scenario.onActivity { activity -> - activity.setContentView(R.layout.test_activity) - - activity.supportFragmentManager.beginTransaction() - .add(R.id.test_fragment_placeholder, ProfileAndDeviceIdFragment()) - .commitNow() + private fun runWithLaunchedActivityAndAddedFragment( + testBlock: ActivityScenario.() -> Unit + ) { + ActivityScenario.launch(TestActivity.createIntent(context)).use { scenario -> + scenario.onActivity { activity -> + activity.setContentView(R.layout.test_activity) + + activity.supportFragmentManager.beginTransaction() + .add(R.id.test_fragment_placeholder, ProfileAndDeviceIdFragment()) + .commitNow() + } + connectNetwork() // Start with internet connectivity. + testCoroutineDispatchers.runCurrent() + scenario.testBlock() } - connectNetwork() // Start with internet connectivity. - testCoroutineDispatchers.runCurrent() } private fun scrollTo(position: Int) { @@ -944,7 +1015,7 @@ class ProfileAndDeviceIdFragmentTest { private fun logAnalyticsEvent(profileId: ProfileId? = null) { learnerAnalyticsLogger.logAppInForeground( - installationId = "test_install_id", profileId, learnerId = "test_learner_id" + installationId = TEST_INSTALLATION_ID, profileId, learnerId = TEST_LEARNER_ID ) testCoroutineDispatchers.runCurrent() } @@ -985,6 +1056,48 @@ class ProfileAndDeviceIdFragmentTest { disconnectNetwork() } + private fun String.computeSha1Hash(): String { + return machineLocale.run { + MessageDigest.getInstance("SHA-1") + .digest(this@computeSha1Hash.toByteArray()) + .joinToString("") { "%02x".formatForMachines(it) } + } + } + + private fun decodeEventLogString(encodedEventLogs: String): OppiaEventLogs { + return GZIPInputStream(Base64.getDecoder().decode(encodedEventLogs).inputStream()).use { inps -> + OppiaEventLogs.newBuilder().mergeFrom(inps).build() + } + } + + private fun EventLogSubject.hasCommonProperties() { + hasNoLanguageInformation() + hasTimestampThat().isEqualTo(0) + isEssentialPriority() + hasAppInForegroundContextThat().hasDefaultIds() + } + + private fun EventLogSubject.hasCommonPropsWithNoProfileId() { + hasCommonProperties() + hasNoProfileId() + } + + private fun EventLogSubject.hasCommonPropsWithProfile(profileId: ProfileId) { + hasCommonProperties() + hasProfileIdThat().isEqualTo(profileId) + } + + private fun EventLogSubject.hasNoLanguageInformation() { + hasAppLanguageSelectionThat().isEqualToDefaultInstance() + hasWrittenTranslationLanguageSelectionThat().isEqualToDefaultInstance() + hasAudioTranslationLanguageSelectionThat().isEqualToDefaultInstance() + } + + private fun LearnerDetailsContextSubject.hasDefaultIds() { + hasLearnerIdThat().isEqualTo(TEST_LEARNER_ID) + hasInstallationIdThat().isEqualTo(TEST_INSTALLATION_ID) + } + private fun setUpTestApplicationComponent() { ApplicationProvider.getApplicationContext().inject(this) } @@ -1060,6 +1173,8 @@ class ProfileAndDeviceIdFragmentTest { private companion object { private const val DEFAULT_APPLICATION_ID = 123456789L + private const val TEST_LEARNER_ID = "test_learner_id" + private const val TEST_INSTALLATION_ID = "test_install_id" private val ADMIN_PROFILE_ID = createProfileId(internalProfileId = 0) private val LEARNER_PROFILE_ID_0 = createProfileId(internalProfileId = 1) diff --git a/app/src/sharedTest/java/org/oppia/android/app/devoptions/DeveloperOptionsFragmentTest.kt b/app/src/sharedTest/java/org/oppia/android/app/devoptions/DeveloperOptionsFragmentTest.kt index 29ea1a94163..e20e3828a89 100644 --- a/app/src/sharedTest/java/org/oppia/android/app/devoptions/DeveloperOptionsFragmentTest.kt +++ b/app/src/sharedTest/java/org/oppia/android/app/devoptions/DeveloperOptionsFragmentTest.kt @@ -418,7 +418,7 @@ class DeveloperOptionsFragmentTest { createDeveloperOptionsTestActivityIntent(internalProfileId) ).use { testCoroutineDispatchers.runCurrent() - val exception = assertThrows(RuntimeException::class) { + val exception = assertThrows() { scrollToPosition(position = 2) onView(withId(R.id.force_crash_text_view)).perform(click()) } @@ -433,7 +433,7 @@ class DeveloperOptionsFragmentTest { ).use { testCoroutineDispatchers.runCurrent() onView(isRoot()).perform(orientationLandscape()) - val exception = assertThrows(RuntimeException::class) { + val exception = assertThrows() { scrollToPosition(position = 2) onView(withId(R.id.force_crash_text_view)).perform(click()) } diff --git a/app/src/test/java/org/oppia/android/app/parser/StringToRatioParserTest.kt b/app/src/test/java/org/oppia/android/app/parser/StringToRatioParserTest.kt index acbf5c9fec8..b7d63c2d909 100644 --- a/app/src/test/java/org/oppia/android/app/parser/StringToRatioParserTest.kt +++ b/app/src/test/java/org/oppia/android/app/parser/StringToRatioParserTest.kt @@ -232,7 +232,7 @@ class StringToRatioParserTest { @Test fun testParser_parseRatioOrThrow_ratioWithInvalidRatio_throwsException() { - val exception = assertThrows(IllegalArgumentException::class) { + val exception = assertThrows() { stringToRatioParser.parseRatioOrThrow("a:b:c") } assertThat(exception) diff --git a/app/src/test/java/org/oppia/android/app/translation/AppLanguageLocaleHandlerTest.kt b/app/src/test/java/org/oppia/android/app/translation/AppLanguageLocaleHandlerTest.kt index 942fb06d5b6..67846ded7ad 100644 --- a/app/src/test/java/org/oppia/android/app/translation/AppLanguageLocaleHandlerTest.kt +++ b/app/src/test/java/org/oppia/android/app/translation/AppLanguageLocaleHandlerTest.kt @@ -73,7 +73,7 @@ class AppLanguageLocaleHandlerTest { @Test fun testGetDisplayLocale_initialState_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { appLanguageLocaleHandler.getDisplayLocale() } @@ -103,7 +103,7 @@ class AppLanguageLocaleHandlerTest { fun testInitializeLocale_twice_throwsException() { appLanguageLocaleHandler.initializeLocale(computeNewAppLanguageLocale(ENGLISH)) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { appLanguageLocaleHandler.initializeLocale(retrieveAppLanguageLocale()) } @@ -117,7 +117,7 @@ class AppLanguageLocaleHandlerTest { fun testUpdateLocale_uninitialized_throwsException() { setAppLanguage(ENGLISH) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { appLanguageLocaleHandler.updateLocale(retrieveAppLanguageLocale()) } @@ -186,7 +186,7 @@ class AppLanguageLocaleHandlerTest { fun testInitializeLocaleForActivity_uninitialized_throwsException() { val configuration = Configuration() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { appLanguageLocaleHandler.initializeLocaleForActivity(configuration) } diff --git a/app/src/test/java/org/oppia/android/app/translation/AppLanguageResourceHandlerTest.kt b/app/src/test/java/org/oppia/android/app/translation/AppLanguageResourceHandlerTest.kt index 5689577c68c..e4283fedc76 100644 --- a/app/src/test/java/org/oppia/android/app/translation/AppLanguageResourceHandlerTest.kt +++ b/app/src/test/java/org/oppia/android/app/translation/AppLanguageResourceHandlerTest.kt @@ -242,7 +242,7 @@ class AppLanguageResourceHandlerTest { updateAppLanguageTo(OppiaLanguage.ENGLISH) val handler = retrieveAppLanguageResourceHandler() - assertThrows(Resources.NotFoundException::class) { handler.getStringInLocale(-1) } + assertThrows() { handler.getStringInLocale(-1) } } @Test @@ -279,7 +279,7 @@ class AppLanguageResourceHandlerTest { updateAppLanguageTo(OppiaLanguage.ENGLISH) val handler = retrieveAppLanguageResourceHandler() - assertThrows(Resources.NotFoundException::class) { handler.getStringInLocaleWithWrapping(-1) } + assertThrows() { handler.getStringInLocaleWithWrapping(-1) } } @Test @@ -316,7 +316,7 @@ class AppLanguageResourceHandlerTest { updateAppLanguageTo(OppiaLanguage.ENGLISH) val handler = retrieveAppLanguageResourceHandler() - assertThrows(Resources.NotFoundException::class) { + assertThrows() { handler.getStringInLocaleWithoutWrapping(-1) } } @@ -336,7 +336,7 @@ class AppLanguageResourceHandlerTest { updateAppLanguageTo(OppiaLanguage.ENGLISH) val handler = retrieveAppLanguageResourceHandler() - assertThrows(Resources.NotFoundException::class) { handler.getStringArrayInLocale(-1) } + assertThrows() { handler.getStringArrayInLocale(-1) } } @Test @@ -366,7 +366,7 @@ class AppLanguageResourceHandlerTest { updateAppLanguageTo(OppiaLanguage.ENGLISH) val handler = retrieveAppLanguageResourceHandler() - assertThrows(Resources.NotFoundException::class) { handler.getQuantityStringInLocale(-1, 0) } + assertThrows() { handler.getQuantityStringInLocale(-1, 0) } } @Test @@ -397,7 +397,7 @@ class AppLanguageResourceHandlerTest { updateAppLanguageTo(OppiaLanguage.ENGLISH) val handler = retrieveAppLanguageResourceHandler() - assertThrows(Resources.NotFoundException::class) { + assertThrows() { handler.getQuantityStringInLocaleWithWrapping(-1, 0) } } @@ -432,7 +432,7 @@ class AppLanguageResourceHandlerTest { updateAppLanguageTo(OppiaLanguage.ENGLISH) val handler = retrieveAppLanguageResourceHandler() - assertThrows(Resources.NotFoundException::class) { + assertThrows() { handler.getQuantityStringInLocaleWithoutWrapping(-1, 0) } } diff --git a/domain/src/main/java/org/oppia/android/domain/oppialogger/LoggingIdentifierController.kt b/domain/src/main/java/org/oppia/android/domain/oppialogger/LoggingIdentifierController.kt index 5ce84fc4bcf..f0e35b7d079 100644 --- a/domain/src/main/java/org/oppia/android/domain/oppialogger/LoggingIdentifierController.kt +++ b/domain/src/main/java/org/oppia/android/domain/oppialogger/LoggingIdentifierController.kt @@ -28,7 +28,15 @@ class LoggingIdentifierController @Inject constructor( private val persistentCacheStoreFactory: PersistentCacheStore.Factory, private val oppiaLogger: OppiaLogger ) { - private val learnerIdRandom by lazy { Random(applicationIdSeed) } + // Use a base random to compute the per-ID random IDs in order so that test behaviors are + // consistent and deterministic when fixing the application ID seed. + private val baseRandom = Random(applicationIdSeed) + private val installationRandomSeed = baseRandom.nextLong() + private val sessionRandomSeed = baseRandom.nextLong() + private val learnerRandomSeed = baseRandom.nextLong() + private val installationIdRandom by lazy { Random(installationRandomSeed) } + private val sessionIdRandom by lazy { Random(sessionRandomSeed) } + private val learnerIdRandom by lazy { Random(learnerRandomSeed) } private val sessionId by lazy { MutableStateFlow(computeSessionId()) } private val sessionIdDataProvider by lazy { @@ -113,12 +121,12 @@ class LoggingIdentifierController @Inject constructor( sessionId.value = computeSessionId() } - private fun computeSessionId(): String = learnerIdRandom.randomUuid().toString() + private fun computeSessionId(): String = sessionIdRandom.randomUuid().toString() private fun computeInstallationId(): String { return machineLocale.run { MessageDigest.getInstance("SHA-1") - .digest(learnerIdRandom.randomUuid().toString().toByteArray()) + .digest(installationIdRandom.randomUuid().toString().toByteArray()) .joinToString("") { "%02x".formatForMachines(it) } .substring(startIndex = 0, endIndex = 12) } diff --git a/domain/src/test/java/org/oppia/android/domain/audio/AudioPlayerControllerTest.kt b/domain/src/test/java/org/oppia/android/domain/audio/AudioPlayerControllerTest.kt index f7652a7e08b..3f7a3d6b241 100644 --- a/domain/src/test/java/org/oppia/android/domain/audio/AudioPlayerControllerTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/audio/AudioPlayerControllerTest.kt @@ -435,7 +435,7 @@ class AudioPlayerControllerTest { @Test fun testController_notInitialized_releasePlayer_fails() { setUpMediaReadyApplication() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { audioPlayerController.releaseMediaPlayer() } @@ -446,7 +446,7 @@ class AudioPlayerControllerTest { @Test fun testError_notPrepared_invokePlay_fails() { setUpMediaReadyApplication() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { audioPlayerController.play(isPlayingFromAutoPlay = false, reloadingMainContent = false) } @@ -456,7 +456,7 @@ class AudioPlayerControllerTest { @Test fun testError_notPrepared_invokePause_fails() { setUpMediaReadyApplication() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { audioPlayerController.pause(isFromExplicitUserAction = true) } @@ -466,7 +466,7 @@ class AudioPlayerControllerTest { @Test fun testError_notPrepared_invokeSeekTo_fails() { setUpMediaReadyApplication() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { audioPlayerController.seekTo(500) } diff --git a/domain/src/test/java/org/oppia/android/domain/auth/AuthenticationControllerTest.kt b/domain/src/test/java/org/oppia/android/domain/auth/AuthenticationControllerTest.kt index 4208244c46e..2b69a7e7c76 100644 --- a/domain/src/test/java/org/oppia/android/domain/auth/AuthenticationControllerTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/auth/AuthenticationControllerTest.kt @@ -11,13 +11,21 @@ import dagger.Module import dagger.Provides import kotlinx.coroutines.CoroutineDispatcher import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mock +import org.mockito.Mockito.verify +import org.mockito.Mockito.verifyNoInteractions +import org.mockito.junit.MockitoJUnit +import org.mockito.junit.MockitoRule import org.oppia.android.domain.oppialogger.analytics.ApplicationLifecycleModule import org.oppia.android.testing.TestLogReportingModule -import org.oppia.android.testing.assertThrows import org.oppia.android.testing.firebase.FakeFirebaseAuthWrapperImpl import org.oppia.android.testing.firebase.TestAuthenticationModule +import org.oppia.android.testing.mockito.capture import org.oppia.android.testing.robolectric.RobolectricModule import org.oppia.android.testing.time.FakeOppiaClockModule import org.oppia.android.util.data.DataProvidersInjector @@ -36,17 +44,16 @@ import javax.inject.Singleton @LooperMode(LooperMode.Mode.PAUSED) @Config(application = AuthenticationControllerTest.TestApplication::class) class AuthenticationControllerTest { - @Inject - lateinit var firebaseAuthWrapper: FirebaseAuthWrapper + @field:[Rule JvmField] val mockitoRule: MockitoRule = MockitoJUnit.rule() - @Inject - lateinit var fakeFirebaseAuthWrapperImpl: FakeFirebaseAuthWrapperImpl + @Inject lateinit var firebaseAuthWrapper: FirebaseAuthWrapper + @Inject lateinit var fakeFirebaseAuthWrapperImpl: FakeFirebaseAuthWrapperImpl + @Inject lateinit var authenticationController: AuthenticationController + @field:[Inject BackgroundDispatcher] lateinit var backgroundDispatcher: CoroutineDispatcher - @Inject - lateinit var authenticationController: AuthenticationController - - @field:[Inject BackgroundDispatcher] - lateinit var backgroundDispatcher: CoroutineDispatcher + @Mock lateinit var mockFakeSuccessCallback: FakeSuccessCallback + @Mock lateinit var mockFakeFailureCallback: FakeFailureCallback + @Captor lateinit var throwableCaptor: ArgumentCaptor @Before fun setUp() { @@ -54,48 +61,49 @@ class AuthenticationControllerTest { } @Test - fun testAuthentication_getCurrentUser_userSignedIn_returnsInstanceOfFirebaseUserWrapper() { + fun testAuthentication_signInAnonymously_onlyOnSuccessCalled() { fakeFirebaseAuthWrapperImpl.simulateSignInSuccess() firebaseAuthWrapper.signInAnonymously( - onSuccess = {}, - onFailure = {} + onSuccess = mockFakeSuccessCallback::onSuccess, + onFailure = mockFakeFailureCallback::onFailure ) - val user = authenticationController.currentFirebaseUser - - assertThat(user).isInstanceOf(FirebaseUserWrapper::class.java) + // onSuccess should be called. + verify(mockFakeSuccessCallback).onSuccess() + verifyNoInteractions(mockFakeFailureCallback) } @Test - fun testAuthentication_signInAnonymously_succeeds() { - fakeFirebaseAuthWrapperImpl.simulateSignInSuccess() + fun testAuthentication_signInAnonymously_onlyOnFailureCalled() { + fakeFirebaseAuthWrapperImpl.simulateSignInFailure() firebaseAuthWrapper.signInAnonymously( - onSuccess = {}, - onFailure = {} + onSuccess = mockFakeSuccessCallback::onSuccess, + onFailure = mockFakeFailureCallback::onFailure ) - val user = authenticationController.currentFirebaseUser - - assertThat(user).isInstanceOf(FirebaseUserWrapper::class.java) + // onFailure should be called with the failure details. + verify(mockFakeFailureCallback).onFailure(capture(throwableCaptor)) + verifyNoInteractions(mockFakeSuccessCallback) + assertThat(throwableCaptor.value).hasMessageThat().contains("Sign-in failure") } @Test - fun testAuthentication_signInAnonymously_failure_returnsException() { - fakeFirebaseAuthWrapperImpl.simulateSignInFailure() + fun testAuthentication_getCurrentUser_userSignedIn_returnsInstanceOfFirebaseUserWrapper() { + fakeFirebaseAuthWrapperImpl.simulateSignInSuccess() + firebaseAuthWrapper.signInAnonymously( + onSuccess = mockFakeSuccessCallback::onSuccess, + onFailure = mockFakeFailureCallback::onFailure + ) - assertThrows(Throwable::class) { - firebaseAuthWrapper.signInAnonymously( - onSuccess = {}, - onFailure = {} - ) - } + val user = authenticationController.currentFirebaseUser + + assertThat(user).isInstanceOf(FirebaseUserWrapper::class.java) } private fun setUpTestApplicationComponent() { - ApplicationProvider.getApplicationContext() - .inject(this) + ApplicationProvider.getApplicationContext().inject(this) } @Module @@ -141,4 +149,8 @@ class AuthenticationControllerTest { override fun getDataProvidersInjector(): DataProvidersInjector = component } + + interface FakeSuccessCallback { fun onSuccess() } + + interface FakeFailureCallback { fun onFailure(failure: Throwable) } } diff --git a/domain/src/test/java/org/oppia/android/domain/classify/AnswerClassificationControllerTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/AnswerClassificationControllerTest.kt index 712ad585e86..8553d8d1f99 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/AnswerClassificationControllerTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/AnswerClassificationControllerTest.kt @@ -152,7 +152,7 @@ class AnswerClassificationControllerTest { fun testClassify_forUnknownInteraction_throwsException() { val interaction = Interaction.getDefaultInstance() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { answerClassificationController.classify( interaction, TEST_STRING_0, @@ -170,7 +170,7 @@ class AnswerClassificationControllerTest { .addAnswerGroups(AnswerGroup.newBuilder().addRuleSpecs(RuleSpec.getDefaultInstance())) .build() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { answerClassificationController.classify( interaction, TEST_STRING_0, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputHasElementXAtPositionYRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputHasElementXAtPositionYRuleClassifierProviderTest.kt index 53be477a285..c7d224753c4 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputHasElementXAtPositionYRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputHasElementXAtPositionYRuleClassifierProviderTest.kt @@ -55,7 +55,7 @@ class DragDropSortInputHasElementXAtPositionYRuleClassifierProviderTest { // Reverse the x and y parameters to ensure both have the incorrect type. val inputs = mapOf("x" to NON_NEGATIVE_VALUE_1, "y" to VALID_CONTENT_ID_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXAtPositionYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, @@ -75,7 +75,7 @@ class DragDropSortInputHasElementXAtPositionYRuleClassifierProviderTest { "y" to NON_NEGATIVE_VALUE_1 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXAtPositionYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, @@ -92,7 +92,7 @@ class DragDropSortInputHasElementXAtPositionYRuleClassifierProviderTest { fun testAnswer_nonNegativeInput_testString_yInputWithIncorrectType_throwsException() { val inputs = mapOf("x" to VALID_CONTENT_ID_2, "y" to VALID_CONTENT_ID_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXAtPositionYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, @@ -109,7 +109,7 @@ class DragDropSortInputHasElementXAtPositionYRuleClassifierProviderTest { fun testAnswer_testString_missingInputX_throwsException() { val inputs = mapOf("y" to VALID_CONTENT_ID_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXAtPositionYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, @@ -126,7 +126,7 @@ class DragDropSortInputHasElementXAtPositionYRuleClassifierProviderTest { fun testAnswer_nonNegativeInput_missingInputY_throwsException() { val inputs = mapOf("x" to VALID_CONTENT_ID_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXAtPositionYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, @@ -143,7 +143,7 @@ class DragDropSortInputHasElementXAtPositionYRuleClassifierProviderTest { fun testAnswer_bothInputsMissing_throwsException() { val inputs = mapOf("z" to VALID_CONTENT_ID_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXAtPositionYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputHasElementXBeforeElementYRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputHasElementXBeforeElementYRuleClassifierProviderTest.kt index c706db71f64..a40e47d06f4 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputHasElementXBeforeElementYRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputHasElementXBeforeElementYRuleClassifierProviderTest.kt @@ -56,7 +56,7 @@ class DragDropSortInputHasElementXBeforeElementYRuleClassifierProviderTest { "y" to NON_NEGATIVE_VALUE_1 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXBeforeElementYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, @@ -73,7 +73,7 @@ class DragDropSortInputHasElementXBeforeElementYRuleClassifierProviderTest { fun testAnswer_nonNegativeInput_testString_xInputWithIncorrectType_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_1, "y" to VALID_CONTENT_ID_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXBeforeElementYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, @@ -90,7 +90,7 @@ class DragDropSortInputHasElementXBeforeElementYRuleClassifierProviderTest { fun testAnswer_nonNegativeInput_testString_yInputWithIncorrectType_throwsException() { val inputs = mapOf("x" to VALID_CONTENT_ID_2, "y" to NON_NEGATIVE_VALUE_1) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXBeforeElementYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, @@ -107,7 +107,7 @@ class DragDropSortInputHasElementXBeforeElementYRuleClassifierProviderTest { fun testAnswer_testString_missingInputX_throwsException() { val inputs = mapOf("y" to VALID_CONTENT_ID_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXBeforeElementYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, @@ -124,7 +124,7 @@ class DragDropSortInputHasElementXBeforeElementYRuleClassifierProviderTest { fun testAnswer_nonNegativeInput_missingInputY_throwsException() { val inputs = mapOf("x" to VALID_CONTENT_ID_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXBeforeElementYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, @@ -141,7 +141,7 @@ class DragDropSortInputHasElementXBeforeElementYRuleClassifierProviderTest { fun testAnswer_bothInputsMissing_throwsException() { val inputs = mapOf("z" to VALID_CONTENT_ID_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasElementXBeforeElementYRuleClassifier.matches( answer = LIST_OF_SETS_OF_CONTENT_IDS, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputIsEqualToOrderingClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputIsEqualToOrderingClassifierProviderTest.kt index 2c65122884d..c6783f37ca1 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputIsEqualToOrderingClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputIsEqualToOrderingClassifierProviderTest.kt @@ -137,7 +137,7 @@ class DragDropSortInputIsEqualToOrderingClassifierProviderTest { fun testAnswer_testLisOfSetsOfHtmlString_incorrectInputMap_throwsException() { val inputs = mapOf("y" to LIST_OF_SETS_12_3_4) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { isEqualToOrderingClassifierProvider.matches( answer = LIST_OF_SETS_12_3_4, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputIsEqualToOrderingWithOneItemAtIncorrectPositionClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputIsEqualToOrderingWithOneItemAtIncorrectPositionClassifierProviderTest.kt index d62690db395..9da1c50711e 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputIsEqualToOrderingWithOneItemAtIncorrectPositionClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/dragAndDropSortInput/DragDropSortInputIsEqualToOrderingWithOneItemAtIncorrectPositionClassifierProviderTest.kt @@ -69,7 +69,7 @@ class DragDropSortInputIsEqualToOrderingWithOneItemAtIncorrectPositionClassifier fun testAnswer_nonNegativeInput_inputWithIncorrectType_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_0) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { isEqualToOrderingWithOneItemIncorrectClassifier.matches( answer = LIST_OF_SETS_12_4_5, inputs = inputs, @@ -144,7 +144,7 @@ class DragDropSortInputIsEqualToOrderingWithOneItemAtIncorrectPositionClassifier fun testAnswer_testLisOfSetsOfHtmlString_incorrectInputMap_throwsException() { val inputs = mapOf("y" to LIST_OF_SETS_12_4_5) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { isEqualToOrderingWithOneItemIncorrectClassifier.matches( answer = LIST_OF_SETS_12_4_5, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasDenominatorEqualToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasDenominatorEqualToRuleClassifierProviderTest.kt index a4641cc64ad..c0be3182da6 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasDenominatorEqualToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasDenominatorEqualToRuleClassifierProviderTest.kt @@ -124,7 +124,7 @@ class FractionInputHasDenominatorEqualToRuleClassifierProviderTest { fun testDenominatorEquals_nonNegativeInput_inputWithIncorrectType_throwsException() { val inputs = mapOf("x" to FRACTION_VALUE_TEST_2_OVER_4) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { denominatorIsEqualClassifierProvider.matches( answer = FRACTION_VALUE_TEST_2_OVER_4, inputs = inputs, @@ -143,7 +143,7 @@ class FractionInputHasDenominatorEqualToRuleClassifierProviderTest { fun testDenominatorEquals_missingInputF_throwsException() { val inputs = mapOf("y" to NON_NEGATIVE_VALUE_TEST_1) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { denominatorIsEqualClassifierProvider.matches( answer = FRACTION_VALUE_TEST_2_OVER_4, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasFractionalPartExactlyEqualToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasFractionalPartExactlyEqualToRuleClassifierProviderTest.kt index 56212d736d9..d5d95ca9253 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasFractionalPartExactlyEqualToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasFractionalPartExactlyEqualToRuleClassifierProviderTest.kt @@ -208,7 +208,7 @@ class FractionInputHasFractionalPartExactlyEqualToRuleClassifierProviderTest { fun testFractionalEquals_nonNegativeInput_inputWithIncorrectType_throwsException() { val inputs = mapOf("f" to NON_NEGATIVE_VALUE_TEST_0) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { fractionalPartIsExactlyEqualClassifierProvider.matches( answer = FRACTION_VALUE_TEST_2_OVER_4, inputs = inputs, @@ -227,7 +227,7 @@ class FractionInputHasFractionalPartExactlyEqualToRuleClassifierProviderTest { fun testFractionalEquals_missingInputF_throwsException() { val inputs = mapOf("y" to FRACTION_VALUE_TEST_2_OVER_4) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { fractionalPartIsExactlyEqualClassifierProvider.matches( answer = FRACTION_VALUE_TEST_2_OVER_4, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasIntegerPartEqualToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasIntegerPartEqualToRuleClassifierProviderTest.kt index 3d58861f475..c1212a3a082 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasIntegerPartEqualToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasIntegerPartEqualToRuleClassifierProviderTest.kt @@ -405,7 +405,7 @@ class FractionInputHasIntegerPartEqualToRuleClassifierProviderTest { fun testAnswer1Over2_inputMissing_throwsException() { val inputs = mapOf("y" to WHOLE_NUMBER_VALUE_TEST_0) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputHasIntegerPartEqualToRuleClassifier .matches( answer = FRACTION_VALUE_TEST_1_OVER_2, @@ -423,7 +423,7 @@ class FractionInputHasIntegerPartEqualToRuleClassifierProviderTest { fun testAnswer1Over2_inputString_throwsException() { val inputs = mapOf("x" to STRING_VALUE_TEST_LOWERCASE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputHasIntegerPartEqualToRuleClassifier .matches( answer = FRACTION_VALUE_TEST_1_OVER_2, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasNumeratorEqualToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasNumeratorEqualToRuleClassifierProviderTest.kt index 647d37cbdd3..bc4bb343c03 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasNumeratorEqualToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputHasNumeratorEqualToRuleClassifierProviderTest.kt @@ -145,7 +145,7 @@ class FractionInputHasNumeratorEqualToRuleClassifierProviderTest { fun testNumeratorEquals_nonNegativeInput_inputWithIncorrectType_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_TEST_0) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { numeratorIsEqualClassifierProvider.matches( answer = FRACTION_VALUE_TEST_2_OVER_4, inputs = inputs, @@ -164,7 +164,7 @@ class FractionInputHasNumeratorEqualToRuleClassifierProviderTest { fun testNumeratorEquals_missingInputF_throwsException() { val inputs = mapOf("y" to FRACTION_VALUE_TEST_2_OVER_4) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { numeratorIsEqualClassifierProvider.matches( answer = FRACTION_VALUE_TEST_2_OVER_4, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsEquivalentToAndInSimplestFormRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsEquivalentToAndInSimplestFormRuleClassifierProviderTest.kt index 1afbb516319..8a2d65bf340 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsEquivalentToAndInSimplestFormRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsEquivalentToAndInSimplestFormRuleClassifierProviderTest.kt @@ -288,7 +288,7 @@ class FractionInputIsEquivalentToAndInSimplestFormRuleClassifierProviderTest { val inputs = mapOf("y" to FRACTION_VALUE_TEST_1_OVER_2) val answer = FRACTION_VALUE_TEST_1_OVER_2 - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsEquivalentToAndInSimplestFormRuleClassifier.matches( answer = answer, inputs = inputs, @@ -306,7 +306,7 @@ class FractionInputIsEquivalentToAndInSimplestFormRuleClassifierProviderTest { val inputs = mapOf("f" to FRACTION_VALUE_TEST_1_OVER_2) val answer = STRING_VALUE_TEST - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsEquivalentToAndInSimplestFormRuleClassifier.matches( answer = answer, inputs = inputs, @@ -324,7 +324,7 @@ class FractionInputIsEquivalentToAndInSimplestFormRuleClassifierProviderTest { val inputs = mapOf("f" to STRING_VALUE_TEST) val answer = FRACTION_VALUE_TEST_1_OVER_2 - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsEquivalentToAndInSimplestFormRuleClassifier.matches( answer = answer, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsEquivalentToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsEquivalentToRuleClassifierProviderTest.kt index a61d6a03b41..4788fa0e9d9 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsEquivalentToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsEquivalentToRuleClassifierProviderTest.kt @@ -250,7 +250,7 @@ class FractionInputIsEquivalentToRuleClassifierProviderTest { fun testEquivalence_missingInput_throwsException() { val inputs = mapOf("y" to FRACTION_VALUE_TEST_2_OVER_8) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsEquivalentToRuleClassifier.matches( answer = FRACTION_VALUE_TEST_2_OVER_8, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsExactlyEqualToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsExactlyEqualToRuleClassifierProviderTest.kt index 5280da48f8a..67f4cdba623 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsExactlyEqualToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsExactlyEqualToRuleClassifierProviderTest.kt @@ -235,7 +235,7 @@ class FractionInputIsExactlyEqualToRuleClassifierProviderTest { fun testEquals_nonNegativeInput_inputWithIncorrectType_throwsException() { val inputs = mapOf("f" to NON_NEGATIVE_VALUE_TEST_0) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { isExactlyEqualClassifierProvider.matches( answer = FRACTION_VALUE_TEST_2_OVER_4, inputs = inputs, @@ -254,7 +254,7 @@ class FractionInputIsExactlyEqualToRuleClassifierProviderTest { fun testEquals_missingInputF_throwsException() { val inputs = mapOf("y" to FRACTION_VALUE_TEST_2_OVER_4) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { isExactlyEqualClassifierProvider.matches( answer = FRACTION_VALUE_TEST_2_OVER_4, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsGreaterThanRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsGreaterThanRuleClassifierProviderTest.kt index b14d9993e06..aecd631ac68 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsGreaterThanRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsGreaterThanRuleClassifierProviderTest.kt @@ -409,7 +409,7 @@ class FractionInputIsGreaterThanRuleClassifierProviderTest { fun testFractionalAnswer_missingInput_throwsException() { val inputs = mapOf("y" to FRACTION_VALUE_TEST_1_OVER_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputGreaterThanRuleClassifier .matches( answer = FRACTION_VALUE_TEST_1_OVER_2, @@ -427,7 +427,7 @@ class FractionInputIsGreaterThanRuleClassifierProviderTest { fun testFractionalAnswer_stringInput_throwsException() { val inputs = mapOf("x" to STRING_VALUE_TEST_LOWERCASE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputGreaterThanRuleClassifier .matches( answer = FRACTION_VALUE_TEST_1_OVER_2, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsLessThanRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsLessThanRuleClassifierProviderTest.kt index 1dda20b3d7c..03a00646b82 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsLessThanRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/fractioninput/FractionInputIsLessThanRuleClassifierProviderTest.kt @@ -409,7 +409,7 @@ class FractionInputIsLessThanRuleClassifierProviderTest { fun testAnswer1Over2_inputMissing_throwsException() { val inputs = mapOf("y" to FRACTION_VALUE_TEST_1_OVER_2) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputLessThanRuleClassifier .matches( answer = FRACTION_VALUE_TEST_1_OVER_2, @@ -427,7 +427,7 @@ class FractionInputIsLessThanRuleClassifierProviderTest { fun testAnswer1Over2_inputString_throwsException() { val inputs = mapOf("x" to STRING_VALUE_TEST_LOWERCASE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputLessThanRuleClassifier .matches( answer = FRACTION_VALUE_TEST_1_OVER_2, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/imageClickInput/ImageClickInputIsInRegionRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/imageClickInput/ImageClickInputIsInRegionRuleClassifierProviderTest.kt index 0694388d0c9..565da313100 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/imageClickInput/ImageClickInputIsInRegionRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/imageClickInput/ImageClickInputIsInRegionRuleClassifierProviderTest.kt @@ -89,7 +89,7 @@ class ImageClickInputIsInRegionRuleClassifierProviderTest { fun testAnswer_nonNegativeInput_inputWithIncorrectType_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_0) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { isInRegionClassifierProvider.matches( answer = IMAGE_REGION_ABC_POSITION_1, inputs = inputs, @@ -108,7 +108,7 @@ class ImageClickInputIsInRegionRuleClassifierProviderTest { fun testAnswer_testString_missingInputX_throwsException() { val inputs = mapOf("y" to createString(ITEM_REGION_A)) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { isInRegionClassifierProvider.matches( answer = IMAGE_REGION_ABC_POSITION_1, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputDoesNotContainAtLeastOneOfRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputDoesNotContainAtLeastOneOfRuleClassifierProviderTest.kt index 99be995d0bc..b6eedff3056 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputDoesNotContainAtLeastOneOfRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputDoesNotContainAtLeastOneOfRuleClassifierProviderTest.kt @@ -156,7 +156,7 @@ class ItemSelectionInputDoesNotContainAtLeastOneOfRuleClassifierProviderTest { fun testItemSet_inputIsMissing_throwsException() { val inputs = mapOf("y" to ITEM_SET_1) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputDoesNotContainAtLeastOneOfRuleClassifier.matches( answer = ITEM_SET_12345, inputs = inputs, @@ -173,7 +173,7 @@ class ItemSelectionInputDoesNotContainAtLeastOneOfRuleClassifierProviderTest { fun testItemSet_inputHasTheWrongType_throwsException() { val inputs = mapOf("x" to DIFFERENT_INTERACTION_OBJECT_TYPE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputDoesNotContainAtLeastOneOfRuleClassifier.matches( answer = ITEM_SET_12345, inputs = inputs, @@ -190,7 +190,7 @@ class ItemSelectionInputDoesNotContainAtLeastOneOfRuleClassifierProviderTest { fun testItemSet_answerHasTheWrongType_throwsException() { val inputs = mapOf("x" to ITEM_SET_12345) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputDoesNotContainAtLeastOneOfRuleClassifier.matches( answer = DIFFERENT_INTERACTION_OBJECT_TYPE, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputEqualsRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputEqualsRuleClassifierProviderTest.kt index 927dcdc5f3f..a3c467dcbdc 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputEqualsRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputEqualsRuleClassifierProviderTest.kt @@ -162,7 +162,7 @@ class ItemSelectionInputEqualsRuleClassifierProviderTest { fun testLowercaseAnswer_missingInput_throwsException() { val inputs = mapOf("y" to TEST_HTML_STRING_SET_LOWERCASE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputEqualsRuleClassifierProvider.matches( answer = TEST_HTML_STRING_SET_LOWERCASE, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputIsProperSubsetOfRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputIsProperSubsetOfRuleClassifierProviderTest.kt index 8997d85c434..a4d3a9fadb4 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputIsProperSubsetOfRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/itemselectioninput/ItemSelectionInputIsProperSubsetOfRuleClassifierProviderTest.kt @@ -169,7 +169,7 @@ class ItemSelectionInputIsProperSubsetOfRuleClassifierProviderTest() { fun testIsProperSubset_withInvalidInput_forAnswer12345_throwsException() { val inputs = mapOf("x" to ITEM_SELECTION_INVAILD) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputContainsAtLeastOneOfRuleClassifier.matches( answer = ITEM_SELECTION_12345, inputs = inputs, @@ -186,7 +186,7 @@ class ItemSelectionInputIsProperSubsetOfRuleClassifierProviderTest() { fun testIsProperSubset_withInput12345_forInvalidAnswer_throwsException() { val inputs = mapOf("x" to ITEM_SELECTION_12345) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputContainsAtLeastOneOfRuleClassifier.matches( answer = ITEM_SELECTION_INVAILD, inputs = inputs, @@ -203,7 +203,7 @@ class ItemSelectionInputIsProperSubsetOfRuleClassifierProviderTest() { fun testIsProperSubset_missingInputX_throwsException() { val inputs = mapOf("a" to ITEM_SELECTION_12345) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputContainsAtLeastOneOfRuleClassifier.matches( answer = ITEM_SELECTION_12345, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/multiplechoiceinput/MultipleChoiceInputEqualsRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/multiplechoiceinput/MultipleChoiceInputEqualsRuleClassifierProviderTest.kt index d193f4c795b..c66ab000848 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/multiplechoiceinput/MultipleChoiceInputEqualsRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/multiplechoiceinput/MultipleChoiceInputEqualsRuleClassifierProviderTest.kt @@ -72,7 +72,7 @@ class MultipleChoiceInputEqualsRuleClassifierProviderTest { fun testNonNegativeAnswer_missingInput_throwsException() { val inputs = mapOf("y" to NON_NEGATIVE_VALUE_TEST_0) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputEqualsRuleClassifier.matches( answer = NON_NEGATIVE_VALUE_TEST_0, inputs = inputs, @@ -89,7 +89,7 @@ class MultipleChoiceInputEqualsRuleClassifierProviderTest { fun testUnexpectedStringAnswer_nonNegativeIntInput_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_TEST_0) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputEqualsRuleClassifier.matches( answer = STRING_VALUE_TEST, inputs = inputs, @@ -106,7 +106,7 @@ class MultipleChoiceInputEqualsRuleClassifierProviderTest { fun testNonNegativeAnswer_stringInput_throwsException() { val inputs = mapOf("x" to STRING_VALUE_TEST) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputEqualsRuleClassifier.matches( answer = NON_NEGATIVE_VALUE_TEST_0, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/numberwithunits/NumberWithUnitsIsEqualToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/numberwithunits/NumberWithUnitsIsEqualToRuleClassifierProviderTest.kt index 048e5574066..ee150667497 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/numberwithunits/NumberWithUnitsIsEqualToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/numberwithunits/NumberWithUnitsIsEqualToRuleClassifierProviderTest.kt @@ -185,7 +185,7 @@ class NumberWithUnitsIsEqualToRuleClassifierProviderTest { fun testWholeNumberInputValue_withRealAnswerNumWithUnits_throwsException() { val inputs = mapOf("f" to WHOLE_NUMBER_VALUE_9) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { unitsIsEqualsRuleClassifier.matches( answer = DOUBLE_VALUE_TEST_DIFFERENT_TYPE, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/numberwithunits/NumberWithUnitsIsEquivalentToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/numberwithunits/NumberWithUnitsIsEquivalentToRuleClassifierProviderTest.kt index d53553b9d79..4e6ed68a7e7 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/numberwithunits/NumberWithUnitsIsEquivalentToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/numberwithunits/NumberWithUnitsIsEquivalentToRuleClassifierProviderTest.kt @@ -179,7 +179,7 @@ class NumberWithUnitsIsEquivalentToRuleClassifierProviderTest { fun testInputNumberWithUnits_testAnswer_inputWithIncorrectType_verifyThrowsException() { val inputs = mapOf("f" to INPUT_TEST_NUMBER_WITH_UNITS) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { unitIsEquivalentRuleClassifier.matches( answer = DOUBLE_VALUE_TEST_DIFFERENT_TYPE, inputs = inputs, @@ -198,7 +198,7 @@ class NumberWithUnitsIsEquivalentToRuleClassifierProviderTest { fun testInputNumberWithUnits_testAnswerNumberWithUnits_withXMapping_verifyThrowsException() { val inputs = mapOf("x" to INPUT_TEST_NUMBER_WITH_UNITS) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { unitIsEquivalentRuleClassifier.matches( answer = ANSWER_TEST_NUMBER_WITH_UNITS, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputEqualsRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputEqualsRuleClassifierProviderTest.kt index 1a4c4c8b07a..daa27f53145 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputEqualsRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputEqualsRuleClassifierProviderTest.kt @@ -144,7 +144,7 @@ class NumericInputEqualsRuleClassifierProviderTest { fun testRealAnswer_missingInput_throwsException() { val inputs = mapOf("y" to POSITIVE_REAL_VALUE_1_5) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputEqualsRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -161,7 +161,7 @@ class NumericInputEqualsRuleClassifierProviderTest { fun testRealAnswer_stringInput_throwsException() { val inputs = mapOf("x" to STRING_VALUE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputEqualsRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsGreaterThanOrEqualToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsGreaterThanOrEqualToRuleClassifierProviderTest.kt index b7298602e46..95bab873ae0 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsGreaterThanOrEqualToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsGreaterThanOrEqualToRuleClassifierProviderTest.kt @@ -199,7 +199,7 @@ class NumericInputIsGreaterThanOrEqualToRuleClassifierProviderTest { fun testRealAnswer_missingInput_throwsException() { val inputs = mapOf("y" to POSITIVE_REAL_VALUE_1_5) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsGreaterThanOrEqualToRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -216,7 +216,7 @@ class NumericInputIsGreaterThanOrEqualToRuleClassifierProviderTest { fun testRealAnswer_stringInput_throwsException() { val inputs = mapOf("x" to STRING_VALUE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsGreaterThanOrEqualToRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsGreaterThanRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsGreaterThanRuleClassifierProviderTest.kt index aa4f78a021d..d488eba6b5a 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsGreaterThanRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsGreaterThanRuleClassifierProviderTest.kt @@ -200,7 +200,7 @@ class NumericInputIsGreaterThanRuleClassifierProviderTest { fun testRealAnswer_missingInput_throwsException() { val inputs = mapOf("y" to POSITIVE_REAL_VALUE_1_5) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsGreaterThanRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -217,7 +217,7 @@ class NumericInputIsGreaterThanRuleClassifierProviderTest { fun testRealAnswer_stringInput_throwsException() { val inputs = mapOf("x" to STRING_VALUE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsGreaterThanRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsInclusivelyBetweenRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsInclusivelyBetweenRuleClassifierProviderTest.kt index 504117c488e..948327a4ec9 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsInclusivelyBetweenRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsInclusivelyBetweenRuleClassifierProviderTest.kt @@ -231,7 +231,7 @@ class NumericInputIsInclusivelyBetweenRuleClassifierProviderTest { "c" to NEGATIVE_REAL_VALUE_3_5, "b" to POSITIVE_REAL_VALUE_3_5 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsInclusivelyBetweenRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -250,7 +250,7 @@ class NumericInputIsInclusivelyBetweenRuleClassifierProviderTest { "a" to NEGATIVE_REAL_VALUE_3_5, "c" to POSITIVE_REAL_VALUE_1_5 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsInclusivelyBetweenRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -269,7 +269,7 @@ class NumericInputIsInclusivelyBetweenRuleClassifierProviderTest { "a" to STRING_VALUE_1, "b" to NEGATIVE_REAL_VALUE_3_5 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsInclusivelyBetweenRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -288,7 +288,7 @@ class NumericInputIsInclusivelyBetweenRuleClassifierProviderTest { "a" to POSITIVE_REAL_VALUE_1_5, "b" to STRING_VALUE_2 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsInclusivelyBetweenRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -307,7 +307,7 @@ class NumericInputIsInclusivelyBetweenRuleClassifierProviderTest { "c" to POSITIVE_INT_VALUE_1, "b" to POSITIVE_INT_VALUE_3 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsInclusivelyBetweenRuleClassifier.matches( answer = POSITIVE_INT_VALUE_2, inputs = inputs, @@ -326,7 +326,7 @@ class NumericInputIsInclusivelyBetweenRuleClassifierProviderTest { "a" to POSITIVE_INT_VALUE_1, "c" to POSITIVE_INT_VALUE_3 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsInclusivelyBetweenRuleClassifier.matches( answer = POSITIVE_INT_VALUE_2, inputs = inputs, @@ -345,7 +345,7 @@ class NumericInputIsInclusivelyBetweenRuleClassifierProviderTest { "a" to STRING_VALUE_1, "b" to POSITIVE_INT_VALUE_3 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsInclusivelyBetweenRuleClassifier.matches( answer = POSITIVE_INT_VALUE_1, inputs = inputs, @@ -364,7 +364,7 @@ class NumericInputIsInclusivelyBetweenRuleClassifierProviderTest { "a" to NEGATIVE_INT_VALUE_3, "b" to STRING_VALUE_2 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsInclusivelyBetweenRuleClassifier.matches( answer = POSITIVE_INT_VALUE_2, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsLessThanOrEqualToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsLessThanOrEqualToRuleClassifierProviderTest.kt index 1bcc688f8c3..90cba1612af 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsLessThanOrEqualToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsLessThanOrEqualToRuleClassifierProviderTest.kt @@ -199,7 +199,7 @@ class NumericInputIsLessThanOrEqualToRuleClassifierProviderTest { fun testRealAnswer_missingInput_throwsException() { val inputs = mapOf("y" to POSITIVE_REAL_VALUE_1_5) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsLessThanOrEqualToRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -216,7 +216,7 @@ class NumericInputIsLessThanOrEqualToRuleClassifierProviderTest { fun testRealAnswer_stringInput_throwsException() { val inputs = mapOf("x" to STRING_VALUE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsLessThanOrEqualToRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -233,7 +233,7 @@ class NumericInputIsLessThanOrEqualToRuleClassifierProviderTest { fun testIntAnswer_missingInput_throwsException() { val inputs = mapOf("y" to POSITIVE_INT_VALUE_1) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsLessThanOrEqualToRuleClassifier.matches( answer = POSITIVE_INT_VALUE_1, inputs = inputs, @@ -250,7 +250,7 @@ class NumericInputIsLessThanOrEqualToRuleClassifierProviderTest { fun testIntAnswer_stringInput_throwsException() { val inputs = mapOf("x" to STRING_VALUE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsLessThanOrEqualToRuleClassifier.matches( answer = POSITIVE_INT_VALUE_1, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsLessThanRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsLessThanRuleClassifierProviderTest.kt index 97d152ce3e4..e1819859a89 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsLessThanRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsLessThanRuleClassifierProviderTest.kt @@ -199,7 +199,7 @@ class NumericInputIsLessThanRuleClassifierProviderTest { fun testRealAnswer_missingInput_throwsException() { val inputs = mapOf("y" to POSITIVE_REAL_VALUE_1_5) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsLessThanRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -216,7 +216,7 @@ class NumericInputIsLessThanRuleClassifierProviderTest { fun testRealAnswer_stringInput_throwsException() { val inputs = mapOf("x" to STRING_VALUE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsLessThanRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -233,7 +233,7 @@ class NumericInputIsLessThanRuleClassifierProviderTest { fun testIntAnswer_missingInput_throwsException() { val inputs = mapOf("y" to POSITIVE_INT_VALUE_1) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsLessThanRuleClassifier.matches( answer = POSITIVE_INT_VALUE_3, inputs = inputs, @@ -250,7 +250,7 @@ class NumericInputIsLessThanRuleClassifierProviderTest { fun testIntAnswer_stringInput_throwsException() { val inputs = mapOf("x" to STRING_VALUE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsLessThanRuleClassifier.matches( answer = NEGATIVE_INT_VALUE_1, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsWithinToleranceRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsWithinToleranceRuleClassifierProviderTest.kt index d5481c0ac89..710210dcc39 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsWithinToleranceRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/numericinput/NumericInputIsWithinToleranceRuleClassifierProviderTest.kt @@ -393,7 +393,7 @@ class NumericInputIsWithinToleranceRuleClassifierProviderTest { val inputs = mapOf( "tol" to POSITIVE_REAL_VALUE_3_5 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsWithinToleranceRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -411,7 +411,7 @@ class NumericInputIsWithinToleranceRuleClassifierProviderTest { val inputs = mapOf( "x" to NEGATIVE_REAL_VALUE_3_5 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsWithinToleranceRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -430,7 +430,7 @@ class NumericInputIsWithinToleranceRuleClassifierProviderTest { "c" to NEGATIVE_REAL_VALUE_3_5, "tol" to POSITIVE_REAL_VALUE_3_5 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsWithinToleranceRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -449,7 +449,7 @@ class NumericInputIsWithinToleranceRuleClassifierProviderTest { "x" to NEGATIVE_REAL_VALUE_3_5, "c" to POSITIVE_REAL_VALUE_1_5 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsWithinToleranceRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -468,7 +468,7 @@ class NumericInputIsWithinToleranceRuleClassifierProviderTest { "x" to STRING_VALUE_1, "tol" to NEGATIVE_REAL_VALUE_3_5 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsWithinToleranceRuleClassifier.matches( answer = POSITIVE_REAL_VALUE_1_5, inputs = inputs, @@ -486,7 +486,7 @@ class NumericInputIsWithinToleranceRuleClassifierProviderTest { val inputs = mapOf( "tol" to POSITIVE_INT_VALUE_3 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsWithinToleranceRuleClassifier.matches( answer = POSITIVE_INT_VALUE_2, inputs = inputs, @@ -504,7 +504,7 @@ class NumericInputIsWithinToleranceRuleClassifierProviderTest { val inputs = mapOf( "x" to POSITIVE_INT_VALUE_1 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsWithinToleranceRuleClassifier.matches( answer = POSITIVE_INT_VALUE_2, inputs = inputs, @@ -523,7 +523,7 @@ class NumericInputIsWithinToleranceRuleClassifierProviderTest { "c" to POSITIVE_INT_VALUE_1, "tol" to POSITIVE_INT_VALUE_3 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsWithinToleranceRuleClassifier.matches( answer = POSITIVE_INT_VALUE_2, inputs = inputs, @@ -542,7 +542,7 @@ class NumericInputIsWithinToleranceRuleClassifierProviderTest { "x" to POSITIVE_INT_VALUE_1, "c" to POSITIVE_INT_VALUE_3 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsWithinToleranceRuleClassifier.matches( answer = POSITIVE_INT_VALUE_2, inputs = inputs, @@ -561,7 +561,7 @@ class NumericInputIsWithinToleranceRuleClassifierProviderTest { "x" to STRING_VALUE_1, "tol" to POSITIVE_INT_VALUE_3 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputIsWithinToleranceRuleClassifier.matches( answer = POSITIVE_INT_VALUE_1, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputEqualsRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputEqualsRuleClassifierProviderTest.kt index 244cb981571..07945a20691 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputEqualsRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputEqualsRuleClassifierProviderTest.kt @@ -100,7 +100,7 @@ class RatioInputEqualsRuleClassifierProviderTest { fun testAnswer_nonNegativeInput_inputWithIncorrectType_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_TEST_0) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { equalsClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = inputs, @@ -119,7 +119,7 @@ class RatioInputEqualsRuleClassifierProviderTest { fun testAnswer_testRatio_missingInputX_throwsException() { val inputs = mapOf("y" to RATIO_VALUE_TEST_1_2_3) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { equalsClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputHasNumberOfTermsEqualToClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputHasNumberOfTermsEqualToClassifierProviderTest.kt index 2cbb3b324a4..a8c1b27243c 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputHasNumberOfTermsEqualToClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputHasNumberOfTermsEqualToClassifierProviderTest.kt @@ -82,7 +82,7 @@ class RatioInputHasNumberOfTermsEqualToClassifierProviderTest { fun testAnswer_nonNegativeInput_inputWithIncorrectType_throwsException() { val inputs = mapOf("y" to RATIO_VALUE_TEST_1_2_3) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasNumberOfTermsEqualToClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = inputs, @@ -101,7 +101,7 @@ class RatioInputHasNumberOfTermsEqualToClassifierProviderTest { fun testAnswer_testRatio_missingInputY_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_TEST_4) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasNumberOfTermsEqualToClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputHasSpecificTermEqualToRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputHasSpecificTermEqualToRuleClassifierProviderTest.kt index 81968647149..14101f1d79e 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputHasSpecificTermEqualToRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputHasSpecificTermEqualToRuleClassifierProviderTest.kt @@ -198,7 +198,7 @@ class RatioInputHasSpecificTermEqualToRuleClassifierProviderTest { fun testAnswer_threeTerms_indexInputWithIncorrectType_throwsException() { val inputs = mapOf("x" to STRING_VALUE, "y" to NON_NEGATIVE_VALUE_TEST_3) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasSpecificTermEqualToClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = inputs, @@ -215,7 +215,7 @@ class RatioInputHasSpecificTermEqualToRuleClassifierProviderTest { fun testAnswer_threeTerms_valueInputWithIncorrectType_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_TEST_4, "y" to STRING_VALUE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasSpecificTermEqualToClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = inputs, @@ -232,7 +232,7 @@ class RatioInputHasSpecificTermEqualToRuleClassifierProviderTest { fun testAnswer_threeTerms_missingIndexInput_throwsException() { val inputs = mapOf("y" to NON_NEGATIVE_VALUE_TEST_3) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasSpecificTermEqualToClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = inputs, @@ -249,7 +249,7 @@ class RatioInputHasSpecificTermEqualToRuleClassifierProviderTest { fun testAnswer_threeTerms_missingValueInput_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_TEST_4) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasSpecificTermEqualToClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = inputs, @@ -264,7 +264,7 @@ class RatioInputHasSpecificTermEqualToRuleClassifierProviderTest { @Test fun testAnswer_threeTerms_missingBothInputs_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hasSpecificTermEqualToClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = mapOf(), diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputIsEquivalentRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputIsEquivalentRuleClassifierProviderTest.kt index c93b44f8dc2..09fdeb952bb 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputIsEquivalentRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/ratioinput/RatioInputIsEquivalentRuleClassifierProviderTest.kt @@ -146,7 +146,7 @@ class RatioInputIsEquivalentRuleClassifierProviderTest { fun testAnswer_nonNegativeInput_inputWithIncorrectType_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_TEST_0) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { isEquivalentClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = inputs, @@ -165,7 +165,7 @@ class RatioInputIsEquivalentRuleClassifierProviderTest { fun testAnswer_testRatio_missingInputX_throwsException() { val inputs = mapOf("y" to RATIO_VALUE_TEST_1_2_3) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { isEquivalentClassifierProvider.matches( answer = RATIO_VALUE_TEST_1_2_3, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputContainsRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputContainsRuleClassifierProviderTest.kt index 6f4fc9013b1..1c258aec94e 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputContainsRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputContainsRuleClassifierProviderTest.kt @@ -268,7 +268,7 @@ class TextInputContainsRuleClassifierProviderTest { fun testStringAnswer_missingInput_throwsException() { val inputs = mapOf("y" to STRING_VALUE_TEST_ANSWER_INPUT_SET) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputContainsRuleClassifier.matches( answer = STRING_VALUE_TEST_ANSWER, inputs = inputs, @@ -285,7 +285,7 @@ class TextInputContainsRuleClassifierProviderTest { fun testStringAnswer_nonNegativeIntInput_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_VALUE_TEST_1) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputContainsRuleClassifier.matches( answer = STRING_VALUE_TEST_ANSWER, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputEqualsRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputEqualsRuleClassifierProviderTest.kt index 3b658cca5df..6c5c53471c2 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputEqualsRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputEqualsRuleClassifierProviderTest.kt @@ -210,7 +210,7 @@ class TextInputEqualsRuleClassifierProviderTest { fun testStringAnswer_missingInput_throwsException() { val inputs = mapOf("y" to STRING_VALUE_TEST_LOWERCASE_INPUT_SET) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputEqualsRuleClassifier.matches( answer = STRING_VALUE_TEST_LOWERCASE, inputs = inputs, @@ -227,7 +227,7 @@ class TextInputEqualsRuleClassifierProviderTest { fun testStringAnswer_nonNegativeIntInput_throwsException() { val inputs = mapOf("x" to INT_VALUE_TEST_NON_NEGATIVE) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputEqualsRuleClassifier.matches( answer = STRING_VALUE_TEST_UPPERCASE, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputFuzzyEqualsRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputFuzzyEqualsRuleClassifierProviderTest.kt index 67c7874d515..3bb592d1499 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputFuzzyEqualsRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputFuzzyEqualsRuleClassifierProviderTest.kt @@ -267,7 +267,7 @@ class TextInputFuzzyEqualsRuleClassifierProviderTest { fun testStringAnswer_nonNegativeIntInput_verifyThrowsException() { val inputs = mapOf("x" to NON_NEGATIVE_TEST_VALUE_1) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputFuzzyEqualsRuleClassifier.matches( answer = STRING_VALUE_TEST_ANSWER_UPPERCASE, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputStartsWithRuleClassifierProviderTest.kt b/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputStartsWithRuleClassifierProviderTest.kt index c88983ed5fc..60ea011ad34 100644 --- a/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputStartsWithRuleClassifierProviderTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/classify/rules/textinput/TextInputStartsWithRuleClassifierProviderTest.kt @@ -292,7 +292,7 @@ class TextInputStartsWithRuleClassifierProviderTest { fun testStringAns_missingInput_throwsException() { val inputs = mapOf("y" to STRING_VALUE_TEST_STRING_LOWERCASE_INPUT_SET) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputStartsWithRuleClassifier.matches( answer = STRING_VALUE_TEST_STRING_LOWERCASE, inputs = inputs, @@ -309,7 +309,7 @@ class TextInputStartsWithRuleClassifierProviderTest { fun testStringAns_nonNegativeIntInput_throwsException() { val inputs = mapOf("x" to NON_NEGATIVE_TEST_VALUE_1) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { inputStartsWithRuleClassifier.matches( answer = STRING_VALUE_TEST_STRING_LOWERCASE, inputs = inputs, diff --git a/domain/src/test/java/org/oppia/android/domain/exploration/ExplorationActiveTimeControllerTest.kt b/domain/src/test/java/org/oppia/android/domain/exploration/ExplorationActiveTimeControllerTest.kt index d012e057068..7f33cbe96ab 100644 --- a/domain/src/test/java/org/oppia/android/domain/exploration/ExplorationActiveTimeControllerTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/exploration/ExplorationActiveTimeControllerTest.kt @@ -229,7 +229,7 @@ class ExplorationActiveTimeControllerTest { fun testStopTimer_beforeStarting_isFailure() { setUpTestApplicationComponent() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { stopExploration() } assertThat(exception) diff --git a/domain/src/test/java/org/oppia/android/domain/exploration/ExplorationProgressControllerTest.kt b/domain/src/test/java/org/oppia/android/domain/exploration/ExplorationProgressControllerTest.kt index af38311d4b5..b75654bcdf7 100644 --- a/domain/src/test/java/org/oppia/android/domain/exploration/ExplorationProgressControllerTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/exploration/ExplorationProgressControllerTest.kt @@ -167,7 +167,7 @@ class ExplorationProgressControllerTest { @Test fun testGetCurrentState_noExploration_throwsException() { // Can't retrieve the current state until the play session is started. - assertThrows(UninitializedPropertyAccessException::class) { + assertThrows() { explorationProgressController.getCurrentState() } } diff --git a/domain/src/test/java/org/oppia/android/domain/exploration/testing/FakeExplorationRetrieverTest.kt b/domain/src/test/java/org/oppia/android/domain/exploration/testing/FakeExplorationRetrieverTest.kt index ae53ac8a2e0..6d8ed9c82fa 100644 --- a/domain/src/test/java/org/oppia/android/domain/exploration/testing/FakeExplorationRetrieverTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/exploration/testing/FakeExplorationRetrieverTest.kt @@ -58,7 +58,7 @@ class FakeExplorationRetrieverTest { @Test fun testLoadExploration_noProxySet_fakeExpId_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runBlocking { fakeExplorationRetriever.loadExploration("fake_id") } } @@ -83,7 +83,7 @@ class FakeExplorationRetrieverTest { expIdToLoad = TEST_EXPLORATION_ID_2, expIdToLoadInstead = "fake_id" ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runBlocking { fakeExplorationRetriever.loadExploration(TEST_EXPLORATION_ID_2) } } @@ -120,7 +120,7 @@ class FakeExplorationRetrieverTest { expIdToLoad = "fake_id", expIdToLoadInstead = "other_fake_id" ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runBlocking { fakeExplorationRetriever.loadExploration("fake_id") } } @@ -133,7 +133,7 @@ class FakeExplorationRetrieverTest { expIdToLoad = TEST_EXPLORATION_ID_2, expIdToLoadInstead = TEST_EXPLORATION_ID_5 ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runBlocking { fakeExplorationRetriever.loadExploration("fake_id") } } @@ -175,7 +175,7 @@ class FakeExplorationRetrieverTest { ) fakeExplorationRetriever.clearExplorationProxy("fake_id") - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runBlocking { fakeExplorationRetriever.loadExploration("fake_id") } } diff --git a/domain/src/test/java/org/oppia/android/domain/hintsandsolution/HintHandlerProdImplTest.kt b/domain/src/test/java/org/oppia/android/domain/hintsandsolution/HintHandlerProdImplTest.kt index faa4e98c9f2..c66cc01efe6 100644 --- a/domain/src/test/java/org/oppia/android/domain/hintsandsolution/HintHandlerProdImplTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/hintsandsolution/HintHandlerProdImplTest.kt @@ -976,7 +976,7 @@ class HintHandlerProdImplTest { val state = expWithHintsAndSolution.getInitialState() hintHandler.startWatchingForHintsInNewStateSync(state) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hintHandler.viewHintSync(hintIndex = 0) } @@ -1157,7 +1157,7 @@ class HintHandlerProdImplTest { hintHandler.startWatchingForHintsInNewStateSync(state) triggerAndRevealFirstHint() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hintHandler.viewHintSync(hintIndex = 0) } @@ -1172,7 +1172,7 @@ class HintHandlerProdImplTest { triggerAndRevealFirstHint() triggerAndRevealSecondHint() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hintHandler.viewHintSync(hintIndex = 0) } @@ -1188,7 +1188,7 @@ class HintHandlerProdImplTest { triggerAndRevealSecondHint() triggerAndRevealSolution() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hintHandler.viewHintSync(hintIndex = 0) } @@ -1203,7 +1203,7 @@ class HintHandlerProdImplTest { val state = expWithHintsAndSolution.getInitialState() hintHandler.startWatchingForHintsInNewStateSync(state) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hintHandler.viewSolutionSync() } @@ -1217,7 +1217,7 @@ class HintHandlerProdImplTest { hintHandler.startWatchingForHintsInNewStateSync(state) triggerFirstHint() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hintHandler.viewSolutionSync() } @@ -1231,7 +1231,7 @@ class HintHandlerProdImplTest { hintHandler.startWatchingForHintsInNewStateSync(state) triggerAndRevealFirstHint() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hintHandler.viewSolutionSync() } @@ -1247,7 +1247,7 @@ class HintHandlerProdImplTest { triggerAndRevealFirstHint() triggerAndRevealSecondHint() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hintHandler.viewSolutionSync() } @@ -1344,7 +1344,7 @@ class HintHandlerProdImplTest { triggerAndRevealSecondHint() triggerAndRevealSolution() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { hintHandler.viewSolutionSync() } diff --git a/domain/src/test/java/org/oppia/android/domain/locale/LocaleControllerTest.kt b/domain/src/test/java/org/oppia/android/domain/locale/LocaleControllerTest.kt index 098fcde27de..30467ee6263 100644 --- a/domain/src/test/java/org/oppia/android/domain/locale/LocaleControllerTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/locale/LocaleControllerTest.kt @@ -775,7 +775,7 @@ class LocaleControllerTest { @Test fun testSetAsDefault_customLocaleImpl_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { localeController.setAsDefault(mockDisplayLocale, Configuration()) } diff --git a/domain/src/test/java/org/oppia/android/domain/oppialogger/LoggingIdentifierControllerTest.kt b/domain/src/test/java/org/oppia/android/domain/oppialogger/LoggingIdentifierControllerTest.kt index 303d6f466ac..b2c74d34ad0 100644 --- a/domain/src/test/java/org/oppia/android/domain/oppialogger/LoggingIdentifierControllerTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/oppialogger/LoggingIdentifierControllerTest.kt @@ -52,7 +52,6 @@ import org.robolectric.annotation.LooperMode import java.io.File import java.io.FileOutputStream import java.lang.IllegalStateException -import java.util.Random import javax.inject.Inject import javax.inject.Singleton @@ -77,17 +76,6 @@ class LoggingIdentifierControllerTest { setUpTestApplicationComponent() } - @Test - fun testCreateLearnerId_verifyCreatesCorrectRandomValue() { - val randomLearnerId = loggingIdentifierController.createLearnerId() - - val testLearnerId = machineLocale.run { - "%08x".formatForMachines(Random(TestLoggingIdentifierModule.applicationIdSeed).nextInt()) - } - assertThat(randomLearnerId).isEqualTo(testLearnerId) - assertThat(randomLearnerId.length).isEqualTo(8) - } - @Test fun testCreateLearnerId_twice_bothAreDifferent() { val learnerId1 = loggingIdentifierController.createLearnerId() @@ -104,7 +92,7 @@ class LoggingIdentifierControllerTest { val installationId = monitorFactory.waitForNextSuccessfulResult(loggingIdentifierController.getInstallationId()) - assertThat(installationId).isEqualTo("bc1f80ab5d8c") + assertThat(installationId).isEqualTo("1d079efe67ee") assertThat(installationId.length).isEqualTo(12) } @@ -117,7 +105,7 @@ class LoggingIdentifierControllerTest { monitorFactory.waitForNextSuccessfulResult(loggingIdentifierController.getInstallationId()) // The same value should return for the second instance of the controller. - assertThat(installationId).isEqualTo("bc1f80ab5d8c") + assertThat(installationId).isEqualTo("1d079efe67ee") } @Test @@ -135,7 +123,7 @@ class LoggingIdentifierControllerTest { fun testFetchInstallationId_initialAppState_returnsNewInstallationIdValue() { val installationId = fetchSuccessfulAsyncValue(loggingIdentifierController::fetchInstallationId) - assertThat(installationId).isEqualTo("bc1f80ab5d8c") + assertThat(installationId).isEqualTo("1d079efe67ee") assertThat(installationId?.length).isEqualTo(12) } @@ -147,7 +135,7 @@ class LoggingIdentifierControllerTest { val installationId = fetchSuccessfulAsyncValue(loggingIdentifierController::fetchInstallationId) // The same value should return for the second instance of the controller. - assertThat(installationId).isEqualTo("bc1f80ab5d8c") + assertThat(installationId).isEqualTo("1d079efe67ee") } @Test @@ -165,7 +153,7 @@ class LoggingIdentifierControllerTest { val sessionIdProvider = loggingIdentifierController.getSessionId() val sessionId = monitorFactory.waitForNextSuccessfulResult(sessionIdProvider) - assertThat(sessionId).isEqualTo("1c46e9d5-5902-311a-bbba-a75973c3ccd2") + assertThat(sessionId).isEqualTo("4d0a66f3-82b6-3aa9-8f61-140bdd5f49d3") } @Test @@ -176,7 +164,7 @@ class LoggingIdentifierControllerTest { // The second call should return the same ID (since the ID doesn't automatically change). val sessionId = monitorFactory.waitForNextSuccessfulResult(sessionIdProvider) - assertThat(sessionId).isEqualTo("1c46e9d5-5902-311a-bbba-a75973c3ccd2") + assertThat(sessionId).isEqualTo("4d0a66f3-82b6-3aa9-8f61-140bdd5f49d3") } @Test @@ -184,7 +172,7 @@ class LoggingIdentifierControllerTest { val sessionIdFlow = loggingIdentifierController.getSessionIdFlow() val sessionId = sessionIdFlow.waitForLatestValue() - assertThat(sessionId).isEqualTo("1c46e9d5-5902-311a-bbba-a75973c3ccd2") + assertThat(sessionId).isEqualTo("4d0a66f3-82b6-3aa9-8f61-140bdd5f49d3") } @Test @@ -195,7 +183,7 @@ class LoggingIdentifierControllerTest { // The second call should return the same ID (since the ID doesn't automatically change). val sessionId = sessionIdFlow.waitForLatestValue() - assertThat(sessionId).isEqualTo("1c46e9d5-5902-311a-bbba-a75973c3ccd2") + assertThat(sessionId).isEqualTo("4d0a66f3-82b6-3aa9-8f61-140bdd5f49d3") } @Test @@ -207,7 +195,7 @@ class LoggingIdentifierControllerTest { // The session ID should be changed since updateSessionId() was called. val sessionId = monitorFactory.waitForNextSuccessfulResult(sessionIdProvider) - assertThat(sessionId).isEqualTo("8808493e-6576-3e26-9cbf-d1008051b253") + assertThat(sessionId).isEqualTo("59aea8d4-af4b-3249-b889-dfeba06d0495") } @Test @@ -221,7 +209,7 @@ class LoggingIdentifierControllerTest { // The existing provider should've been notified of the changed session ID. val sessionId = monitor.ensureNextResultIsSuccess() - assertThat(sessionId).isEqualTo("8808493e-6576-3e26-9cbf-d1008051b253") + assertThat(sessionId).isEqualTo("59aea8d4-af4b-3249-b889-dfeba06d0495") } @Test @@ -236,7 +224,7 @@ class LoggingIdentifierControllerTest { // The session ID should be changed yet again due to updateSessionId() being called twice. val sessionId = monitorFactory.waitForNextSuccessfulResult(sessionIdProvider) - assertThat(sessionId).isEqualTo("8aeabb00-af70-39e4-89b3-c47c9900ec4f") + assertThat(sessionId).isEqualTo("8cbd31f7-bb52-3129-9fac-78dcb5cb857a") } @Test @@ -248,7 +236,7 @@ class LoggingIdentifierControllerTest { // The session ID should be changed since updateSessionId() was called. val sessionId = sessionIdFlow.waitForLatestValue() - assertThat(sessionId).isEqualTo("8808493e-6576-3e26-9cbf-d1008051b253") + assertThat(sessionId).isEqualTo("59aea8d4-af4b-3249-b889-dfeba06d0495") } @Test @@ -260,7 +248,7 @@ class LoggingIdentifierControllerTest { testCoroutineDispatchers.runCurrent() // The current value of the exist flow should be changed now since the session ID was updated. - assertThat(sessionIdFlow.value).isEqualTo("8808493e-6576-3e26-9cbf-d1008051b253") + assertThat(sessionIdFlow.value).isEqualTo("59aea8d4-af4b-3249-b889-dfeba06d0495") } private fun writeFileCache(cacheName: String, value: T) { diff --git a/domain/src/test/java/org/oppia/android/domain/oppialogger/analytics/CpuPerformanceSnapshotterTest.kt b/domain/src/test/java/org/oppia/android/domain/oppialogger/analytics/CpuPerformanceSnapshotterTest.kt index 1641eb00223..adf3376b77d 100644 --- a/domain/src/test/java/org/oppia/android/domain/oppialogger/analytics/CpuPerformanceSnapshotterTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/oppialogger/analytics/CpuPerformanceSnapshotterTest.kt @@ -426,7 +426,7 @@ class CpuPerformanceSnapshotterTest { @Test fun testSnapshotter_initializeOnce_initializeAgain_throwsErrorOnReinitialization() { cpuPerformanceSnapshotter.initialiseSnapshotter() - val exception = assertThrows(IllegalArgumentException::class) { + val exception = assertThrows() { cpuPerformanceSnapshotter.initialiseSnapshotter() } diff --git a/domain/src/test/java/org/oppia/android/domain/oppialogger/analytics/LearnerAnalyticsLoggerTest.kt b/domain/src/test/java/org/oppia/android/domain/oppialogger/analytics/LearnerAnalyticsLoggerTest.kt index a036c2a304d..80368c18df9 100644 --- a/domain/src/test/java/org/oppia/android/domain/oppialogger/analytics/LearnerAnalyticsLoggerTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/oppialogger/analytics/LearnerAnalyticsLoggerTest.kt @@ -87,7 +87,7 @@ class LearnerAnalyticsLoggerTest { private const val TEST_STORY_ID = "test_story_id" private const val TEST_EXP_5_STATE_THREE_NAME = "NumericExpressionInput.IsEquivalentTo" private const val TEST_EXP_5_STATE_FOUR_NAME = "AlgebraicExpressionInput.MatchesExactlyWith" - private const val DEFAULT_INITIAL_SESSION_ID = "e6eacc69-e636-3c90-ba29-32bf3dd17161" + private const val DEFAULT_INITIAL_SESSION_ID = "ab4532d6-476c-3727-bc5a-ad84e5dae60f" } @Inject diff --git a/domain/src/test/java/org/oppia/android/domain/profile/ProfileManagementControllerTest.kt b/domain/src/test/java/org/oppia/android/domain/profile/ProfileManagementControllerTest.kt index e95142771be..ae98ccd5ae1 100644 --- a/domain/src/test/java/org/oppia/android/domain/profile/ProfileManagementControllerTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/profile/ProfileManagementControllerTest.kt @@ -156,7 +156,7 @@ class ProfileManagementControllerTest { val profileDatabase = readProfileDatabase() val profile = profileDatabase.profilesMap[0]!! - assertThat(profile.learnerId).isEqualTo("bb1ad573") + assertThat(profile.learnerId).isEqualTo("26504347") } @Test @@ -255,7 +255,7 @@ class ProfileManagementControllerTest { val profileProvider = profileManagementController.getProfile(profileId) val profile = monitorFactory.waitForNextSuccessfulResult(profileProvider) - assertThat(profile.learnerId).isEqualTo("68fb0e6f") + assertThat(profile.learnerId).isEqualTo("a625db55") } @Test @@ -430,7 +430,7 @@ class ProfileManagementControllerTest { val learnerId = fetchSuccessfulAsyncValue(profileManagementController::fetchCurrentLearnerId) - assertThat(learnerId).isEqualTo("19b89cd8") + assertThat(learnerId).isEqualTo("02308fa0") } @Test @@ -465,7 +465,7 @@ class ProfileManagementControllerTest { profileManagementController.fetchLearnerId(PROFILE_ID_2) } - assertThat(learnerId).isEqualTo("68fb0e6f") + assertThat(learnerId).isEqualTo("a625db55") } @Test diff --git a/domain/src/test/java/org/oppia/android/domain/question/QuestionAssessmentProgressControllerTest.kt b/domain/src/test/java/org/oppia/android/domain/question/QuestionAssessmentProgressControllerTest.kt index f5aad0432a1..0c686230064 100644 --- a/domain/src/test/java/org/oppia/android/domain/question/QuestionAssessmentProgressControllerTest.kt +++ b/domain/src/test/java/org/oppia/android/domain/question/QuestionAssessmentProgressControllerTest.kt @@ -134,7 +134,7 @@ class QuestionAssessmentProgressControllerTest { setUpTestApplicationWithSeed(questionSeed = 0) // Can't retrieve the current question until the training session is started. - assertThrows(UninitializedPropertyAccessException::class) { + assertThrows() { questionAssessmentProgressController.getCurrentQuestion() } } diff --git a/model/src/main/proto/BUILD.bazel b/model/src/main/proto/BUILD.bazel index a168e981191..e512512b10f 100644 --- a/model/src/main/proto/BUILD.bazel +++ b/model/src/main/proto/BUILD.bazel @@ -273,7 +273,10 @@ java_lite_proto_library( oppia_proto_library( name = "feedback_reporting_proto", srcs = ["feedback_reporting.proto"], - deps = [":profile_proto"], + deps = [ + ":languages_proto", + ":profile_proto", + ], ) java_lite_proto_library( diff --git a/scripts/assets/file_content_validation_checks.textproto b/scripts/assets/file_content_validation_checks.textproto index a53a46416f4..67116fbd5a2 100644 --- a/scripts/assets/file_content_validation_checks.textproto +++ b/scripts/assets/file_content_validation_checks.textproto @@ -511,3 +511,90 @@ file_content_checks { failure_message: "Badly formatted KDoc. Single-line KDocs should end with punctuation." exempted_file_name: "scripts/src/javatests/org/oppia/android/scripts/regex/RegexPatternValidationCheckTest.kt" } +file_content_checks { + file_path_regex: ".+?Test\\.kt" + prohibited_content_regex: "androidx.test.rule.ActivityTestRule" + failure_message: "ActivityTestRule is deprecated since it operates test activities in sometimes unsafe situations. Use ActivityScenario, instead." + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/AdministratorControlsActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/AppVersionActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/completedstorylist/CompletedStoryListActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/customview/LessonThumbnailImageViewTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/devoptions/DeveloperOptionsActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/devoptions/DeveloperOptionsFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/devoptions/MarkChaptersCompletedActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/devoptions/MarkStoriesCompletedActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/devoptions/MarkStoriesCompletedFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/devoptions/MarkTopicsCompletedActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/devoptions/MarkTopicsCompletedFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/devoptions/ViewEventLogsActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/devoptions/forcenetworktype/ForceNetworkTypeActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/faq/FAQSingleActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/faq/FaqListActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/help/HelpActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/home/RecentlyPlayedFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/onboarding/OnboardingActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/ongoingtopiclist/OngoingTopicListActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/options/AppLanguageActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/options/AudioLanguageActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/options/OptionsActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/options/OptionsFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/options/ReadingTextSizeActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/player/exploration/ExplorationActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/profile/AddProfileActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/profile/AdminAuthActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/profile/AdminPinActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/profile/PinPasswordActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/profile/ProfileChooserActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/profile/ProfileChooserFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/profileprogress/ProfileProgressActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/resumelesson/ResumeLessonActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/resumelesson/ResumeLessonFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/settings/profile/ProfileListActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/settings/profile/ProfileRenameActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/settings/profile/ProfileRenameFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/settings/profile/ProfileResetPinActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/settings/profile/ProfileResetPinFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/story/StoryActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/story/StoryFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/survey/SurveyActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/survey/SurveyFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/thirdparty/LicenseListActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/thirdparty/LicenseTextViewerActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/thirdparty/ThirdPartyDependencyListActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/topic/TopicFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/topic/info/TopicInfoFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/topic/questionplayer/QuestionPlayerActivityTest.kt" + exempted_file_name: "scripts/src/javatests/org/oppia/android/scripts/regex/RegexPatternValidationCheckTest.kt" +} +file_content_checks { + file_path_regex: ".+?Test\\.kt" + prohibited_content_regex: "androidx.test.ext.junit.rules.ActivityScenarioRule" + failure_message: "ActivityScenarioRule can result in order dependence when static state leaks across tests (such as static module variables), and can make staging much more difficult for platform parameters. Use ActivityScenario directly, instead." + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/administratorcontrols/learneranalytics/ProfileAndDeviceIdActivityTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/databinding/AppCompatCheckBoxBindingAdaptersTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/databinding/CircularProgressIndicatorAdaptersTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/databinding/DrawableBindingAdaptersTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/databinding/ImageViewBindingAdaptersTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/databinding/MarginBindingAdaptersTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/databinding/StateAssemblerMarginBindingAdaptersTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/databinding/StateAssemblerPaddingBindingAdaptersTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/databinding/TextViewBindingAdaptersTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/databinding/ViewBindingAdaptersTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/devoptions/mathexpressionparser/MathExpressionParserFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/parser/HtmlParserTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/policies/PoliciesFragmentTest.kt" + exempted_file_name: "app/src/sharedTest/java/org/oppia/android/app/utility/RatioExtensionsTest.kt" + exempted_file_name: "app/src/test/java/org/oppia/android/app/activity/ActivityIntentFactoriesTest.kt" + exempted_file_name: "app/src/test/java/org/oppia/android/app/activity/route/ActivityRouterModuleTest.kt" + exempted_file_name: "app/src/test/java/org/oppia/android/app/activity/route/ActivityRouterTest.kt" + exempted_file_name: "app/src/test/java/org/oppia/android/app/parser/FractionParsingUiErrorTest.kt" + exempted_file_name: "app/src/test/java/org/oppia/android/app/parser/ListItemLeadingMarginSpanTest.kt" + exempted_file_name: "app/src/test/java/org/oppia/android/app/parser/StringToRatioParserTest.kt" + exempted_file_name: "app/src/test/java/org/oppia/android/app/translation/ActivityLanguageLocaleHandlerTest.kt" + exempted_file_name: "app/src/test/java/org/oppia/android/app/translation/AppLanguageResourceHandlerTest.kt" + exempted_file_name: "app/src/test/java/org/oppia/android/app/utility/datetime/DateTimeUtilTest.kt" + exempted_file_name: "app/src/test/java/org/oppia/android/app/utility/math/MathExpressionAccessibilityUtilTest.kt" + exempted_file_name: "domain/src/test/java/org/oppia/android/domain/oppialogger/analytics/ApplicationLifecycleObserverTest.kt" + exempted_file_name: "scripts/src/javatests/org/oppia/android/scripts/regex/RegexPatternValidationCheckTest.kt" + exempted_file_name: "testing/src/test/java/org/oppia/android/testing/espresso/TextInputActionTest.kt" +} diff --git a/scripts/assets/todo_open_exemptions.textproto b/scripts/assets/todo_open_exemptions.textproto index cb81317adae..8b201928380 100644 --- a/scripts/assets/todo_open_exemptions.textproto +++ b/scripts/assets/todo_open_exemptions.textproto @@ -1,37 +1,37 @@ todo_open_exemption { exempted_file_path: "scripts/src/javatests/org/oppia/android/scripts/todo/TodoOpenCheckTest.kt" - line_number: 67 - line_number: 68 + line_number: 65 + line_number: 66 + line_number: 72 line_number: 74 - line_number: 76 + line_number: 96 + line_number: 97 line_number: 98 line_number: 99 line_number: 100 - line_number: 101 - line_number: 102 + line_number: 132 + line_number: 133 line_number: 136 - line_number: 137 - line_number: 140 - line_number: 173 + line_number: 167 + line_number: 168 + line_number: 169 line_number: 174 - line_number: 175 - line_number: 180 - line_number: 182 - line_number: 221 + line_number: 176 + line_number: 213 + line_number: 214 + line_number: 215 + line_number: 220 line_number: 222 - line_number: 223 line_number: 228 - line_number: 230 - line_number: 236 - line_number: 275 - line_number: 279 - line_number: 317 - line_number: 318 - line_number: 322 - line_number: 371 - line_number: 372 - line_number: 373 - line_number: 377 + line_number: 265 + line_number: 269 + line_number: 307 + line_number: 308 + line_number: 312 + line_number: 359 + line_number: 360 + line_number: 361 + line_number: 365 } todo_open_exemption { exempted_file_path: "scripts/src/javatests/org/oppia/android/scripts/todo/TodoCollectorTest.kt" diff --git a/scripts/src/java/org/oppia/android/scripts/ci/ComputeAffectedTests.kt b/scripts/src/java/org/oppia/android/scripts/ci/ComputeAffectedTests.kt index f7cc482c72a..5437874f191 100644 --- a/scripts/src/java/org/oppia/android/scripts/ci/ComputeAffectedTests.kt +++ b/scripts/src/java/org/oppia/android/scripts/ci/ComputeAffectedTests.kt @@ -1,6 +1,8 @@ package org.oppia.android.scripts.ci import org.oppia.android.scripts.common.BazelClient +import org.oppia.android.scripts.common.CommandExecutor +import org.oppia.android.scripts.common.CommandExecutorImpl import org.oppia.android.scripts.common.GitClient import org.oppia.android.scripts.common.ProtoStringEncoder.Companion.toCompressedBase64 import org.oppia.android.scripts.proto.AffectedTestsBucket @@ -73,9 +75,10 @@ private fun String.toBooleanStrictOrNull(): Boolean? { /** Utility used to compute affected test targets. */ class ComputeAffectedTests( - val maxTestCountPerLargeShard: Int = MAX_TEST_COUNT_PER_LARGE_SHARD, - val maxTestCountPerMediumShard: Int = MAX_TEST_COUNT_PER_MEDIUM_SHARD, - val maxTestCountPerSmallShard: Int = MAX_TEST_COUNT_PER_SMALL_SHARD + private val maxTestCountPerLargeShard: Int = MAX_TEST_COUNT_PER_LARGE_SHARD, + private val maxTestCountPerMediumShard: Int = MAX_TEST_COUNT_PER_MEDIUM_SHARD, + private val maxTestCountPerSmallShard: Int = MAX_TEST_COUNT_PER_SMALL_SHARD, + private val commandExecutor: CommandExecutor = CommandExecutorImpl() ) { private companion object { private const val GENERIC_TEST_BUCKET_NAME = "generic" @@ -106,7 +109,7 @@ class ComputeAffectedTests( println("Running from directory root: $rootDirectory") val gitClient = GitClient(rootDirectory, baseDevelopBranchReference) - val bazelClient = BazelClient(rootDirectory) + val bazelClient = BazelClient(rootDirectory, commandExecutor) println("Current branch: ${gitClient.currentBranch}") println("Most recent common commit: ${gitClient.branchMergeBase}") diff --git a/scripts/src/java/org/oppia/android/scripts/testing/TestBazelWorkspace.kt b/scripts/src/java/org/oppia/android/scripts/testing/TestBazelWorkspace.kt index 68487b6062b..7bec4b85889 100644 --- a/scripts/src/java/org/oppia/android/scripts/testing/TestBazelWorkspace.kt +++ b/scripts/src/java/org/oppia/android/scripts/testing/TestBazelWorkspace.kt @@ -4,6 +4,9 @@ import com.google.common.truth.Truth.assertThat import org.junit.rules.TemporaryFolder import java.io.File +/** The version of Bazel to use in tests that set up Bazel workspaces. */ +const val BAZEL_VERSION = "4.0.0" + /** * Test utility for generating various test & library targets in the specified [TemporaryFolder]. * This is meant to be used to arrange the local test filesystem for use with a real Bazel @@ -23,6 +26,13 @@ class TestBazelWorkspace(private val temporaryRootFolder: TemporaryFolder) { */ val rootBuildFile: File by lazy { temporaryRootFolder.newFile("BUILD.bazel") } + private val bazelVersionFile by lazy { + temporaryRootFolder.newFile(".bazelversion").also { it.writeText(BAZEL_VERSION) } + } + private val bazelRcFile by lazy { + temporaryRootFolder.newFile(".bazelrc").also { it.writeText("--noenable_bzlmod") } + } + private val testFileMap = mutableMapOf() private val libraryFileMap = mutableMapOf() private val testDependencyNameMap = mutableMapOf() @@ -33,9 +43,11 @@ class TestBazelWorkspace(private val temporaryRootFolder: TemporaryFolder) { /** Initializes the local Bazel workspace by introducing a new, empty WORKSPACE file. */ fun initEmptyWorkspace() { - // Sanity check, but in reality this is just initializing workspaceFile to ensure that it + // Sanity checks, but in reality this is just initializing workspaceFile to ensure that it // exists. assertThat(workspaceFile.exists()).isTrue() + assertThat(bazelVersionFile.exists()).isTrue() + assertThat(bazelRcFile.exists()).isTrue() } /** @@ -61,6 +73,8 @@ class TestBazelWorkspace(private val temporaryRootFolder: TemporaryFolder) { withExtraDependency: String? = null, subpackage: String? = null ): Iterable { + initEmptyWorkspace() // Ensure the workspace is at least initialized. + check(testName !in testFileMap) { "Test '$testName' already set up" } val prereqFiles = ensureWorkspaceIsConfiguredForKotlin() val (dependencyTargetName, libPrereqFiles) = if (withGeneratedDependency) { @@ -109,6 +123,9 @@ class TestBazelWorkspace(private val temporaryRootFolder: TemporaryFolder) { withExtraDependency: String? = null, subpackage: String? = null ): Iterable { + // Note that the workspace doesn't need to be explicitly initialized here since the call below + // to addTestToBuildFile() will initialize it. + check(testName !in testFileMap) { "Test '$testName' already exists" } val testFile = if (subpackage != null) { if (!File(temporaryRootFolder.root, subpackage.replace(".", "/")).exists()) { @@ -137,6 +154,8 @@ class TestBazelWorkspace(private val temporaryRootFolder: TemporaryFolder) { * iterable of files that were changed as part of generating this library */ fun createLibrary(dependencyName: String): Pair> { + initEmptyWorkspace() // Ensure the workspace is at least initialized. + val libTargetName = "${dependencyName}_lib" check("//:$libTargetName" !in libraryFileMap) { "Library '$dependencyName' already exists" } val prereqFiles = ensureWorkspaceIsConfiguredForKotlin() @@ -187,6 +206,7 @@ class TestBazelWorkspace(private val temporaryRootFolder: TemporaryFolder) { /** Appends rules_jvm_external configuration to the WORKSPACE file if not done already. */ fun setUpWorkspaceForRulesJvmExternal(depsList: List) { if (!isConfiguredForRulesJvmExternal) { + initEmptyWorkspace() workspaceFile.appendText("artifactsList = [") for (dep in depsList) { workspaceFile.appendText("\"$dep\",\n") @@ -198,23 +218,23 @@ class TestBazelWorkspace(private val temporaryRootFolder: TemporaryFolder) { RULES_JVM_EXTERNAL_TAG = "4.0" RULES_JVM_EXTERNAL_SHA = "31701ad93dbfe544d597dbe62c9a1fdd76d81d8a9150c2bf1ecf928ecdf97169" - + http_archive( name = "rules_jvm_external", strip_prefix = "rules_jvm_external-%s" % RULES_JVM_EXTERNAL_TAG, sha256 = RULES_JVM_EXTERNAL_SHA, url = "https://github.com/bazelbuild/rules_jvm_external/archive/%s.zip" % RULES_JVM_EXTERNAL_TAG, ) - + load("@rules_jvm_external//:defs.bzl", "maven_install") - + maven_install( artifacts = artifactsList, repositories = [ "https://maven.google.com", "https://repo1.maven.org/maven2", ], - ) + ) """.trimIndent() + "\n" ) diff --git a/scripts/src/java/org/oppia/android/scripts/testing/TestGitRepository.kt b/scripts/src/java/org/oppia/android/scripts/testing/TestGitRepository.kt index 61d5c055992..2de94e3fc1f 100644 --- a/scripts/src/java/org/oppia/android/scripts/testing/TestGitRepository.kt +++ b/scripts/src/java/org/oppia/android/scripts/testing/TestGitRepository.kt @@ -19,20 +19,29 @@ class TestGitRepository( private val commandExecutor: CommandExecutor ) { private val rootDirectory by lazy { temporaryRootFolder.root } + private val gitDirectory: File get() = File(rootDirectory, ".git") + private val userEmail: String? + get() = maybeExecuteGitCommand("config", "--local", "--get", "user.email")?.joinOutput()?.trim() + private val userName: String? + get() = maybeExecuteGitCommand("config", "--local", "--get", "user.name")?.joinOutput()?.trim() /** Creates the repository using git init. */ fun init() { + verifyNotInGitRepository() executeSuccessfulGitCommand("init") } /** Sets the user's [email] and [name] using git config. */ fun setUser(email: String, name: String) { - executeSuccessfulGitCommand("config", "user.email", email) - executeSuccessfulGitCommand("config", "user.name", name) + verifyInGitRepository() + verifyUserIsNotSet() + executeSuccessfulGitCommand("config", "--local", "user.email", email) + executeSuccessfulGitCommand("config", "--local", "user.name", name) } /** Creates a new branch with the specified name, and switches to it. */ fun checkoutNewBranch(branchName: String) { + verifyInGitRepository() executeSuccessfulGitCommand("checkout", "-b", branchName) } @@ -42,6 +51,7 @@ class TestGitRepository( * This does not perform a commit. See [commit] for actually committing the change. */ fun stageFileForCommit(file: File) { + verifyInGitRepository() executeSuccessfulGitCommand("add", file.toRelativeString(rootDirectory)) } @@ -57,6 +67,7 @@ class TestGitRepository( * This does not perform a commit. See [commit] for actually committing the change. */ fun removeFileForCommit(file: File) { + verifyInGitRepository() executeSuccessfulGitCommand("rm", file.toRelativeString(rootDirectory)) } @@ -67,6 +78,7 @@ class TestGitRepository( * This does not perform a commit. See [commit] for actually committing the change. */ fun moveFileForCommit(oldFile: File, newFile: File) { + verifyInGitRepository() executeSuccessfulGitCommand( "mv", oldFile.toRelativeString(rootDirectory), @@ -81,25 +93,59 @@ class TestGitRepository( * @param allowEmpty whether to allow empty commits (i.e. committing with no staged files) */ fun commit(message: String, allowEmpty: Boolean = false) { + verifyInGitRepository() + verifyUserIsSet() val arguments = mutableListOf("commit", "-m", message) if (allowEmpty) arguments += "--allow-empty" executeSuccessfulGitCommand(*arguments.toTypedArray()) } /** Returns the result of git status. */ - fun status(): String { - return commandExecutor.executeCommand(rootDirectory, "git", "status").output.joinOutputString() + fun status(checkForGitRepository: Boolean = true): String { + if (checkForGitRepository) verifyInGitRepository() + return executeGitCommand("status").joinOutput() } - private fun executeSuccessfulGitCommand(vararg arguments: String) { - verifySuccessfulCommand(commandExecutor.executeCommand(rootDirectory, "git", *arguments)) - } + private fun executeGitCommand(vararg arguments: String): CommandResult = + commandExecutor.executeCommand(rootDirectory, "git", *arguments) + + private fun maybeExecuteGitCommand(vararg arguments: String): CommandResult? = + executeGitCommand(*arguments).takeIf { it.exitCode == 0 } + + private fun executeSuccessfulGitCommand(vararg arguments: String) = + verifySuccessfulCommand(executeGitCommand(*arguments)) private fun verifySuccessfulCommand(result: CommandResult) { - assertWithMessage("Output: ${result.output.joinOutputString()}") + assertWithMessage("Output: ${result.joinOutput()}") .that(result.exitCode) .isEqualTo(0) } - private fun List.joinOutputString(): String = joinToString(separator = "\n") { " $it" } + private fun verifyInGitRepository() { + failUnless(gitDirectory.exists()) { "Not operating in an initialized Git repository." } + } + + private fun verifyNotInGitRepository() { + failUnless(!gitDirectory.exists()) { "Git repository is already initialized." } + } + + private fun verifyUserIsNotSet() { + verifyIsNotSet(name = "User email", userEmail) + verifyIsNotSet(name = "User name", userName) + } + + private fun verifyUserIsSet() { + failUnless(userEmail != null) { "User email has not yet been set." } + failUnless(userName != null) { "User name has not yet been set." } + } + + private fun verifyIsNotSet(name: String, value: String?) { + failUnless(value == null) { "$name has already been set: $value." } + } + + private fun failUnless(condition: Boolean, lazyMessage: () -> String) { + if (!condition) throw AssertionError(lazyMessage()) + } + + private fun CommandResult.joinOutput(): String = output.joinToString(separator = "\n") { " $it" } } diff --git a/scripts/src/javatests/org/oppia/android/scripts/build/FilterPerLanguageResourcesTest.kt b/scripts/src/javatests/org/oppia/android/scripts/build/FilterPerLanguageResourcesTest.kt index 8c217740d10..511b07f37e9 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/build/FilterPerLanguageResourcesTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/build/FilterPerLanguageResourcesTest.kt @@ -86,21 +86,21 @@ class FilterPerLanguageResourcesTest { @Test fun testUtility_noArgs_failsWithUsageString() { - val error = assertThrows(IllegalArgumentException::class) { runScript() } + val error = assertThrows() { runScript() } assertThat(error).hasMessageThat().contains(USAGE_STRING) } @Test fun testUtility_oneArg_failsWithUsageString() { - val error = assertThrows(IllegalArgumentException::class) { runScript("first_file.zip") } + val error = assertThrows() { runScript("first_file.zip") } assertThat(error).hasMessageThat().contains(USAGE_STRING) } @Test fun testUtility_threeArgs_failsWithUsageString() { - val error = assertThrows(IllegalArgumentException::class) { + val error = assertThrows() { runScript( tempFolder.getFilePath("input.zip"), tempFolder.getFilePath("output.zip"), "extra_param" ) @@ -114,7 +114,7 @@ class FilterPerLanguageResourcesTest { // Create an empty zip file. ZipOutputStream(File(tempFolder.root, "input.zip").outputStream()).close() - val error = assertThrows(IllegalStateException::class) { + val error = assertThrows() { runScript(tempFolder.getFilePath("input.zip"), tempFolder.getFilePath("output.zip")) } @@ -129,7 +129,7 @@ class FilterPerLanguageResourcesTest { ResourceTable.getDefaultInstance().writeTo(outputStream) } - val error = assertThrows(IllegalStateException::class) { + val error = assertThrows() { runScript(tempFolder.getFilePath("input.zip"), tempFolder.getFilePath("output.zip")) } @@ -147,7 +147,7 @@ class FilterPerLanguageResourcesTest { supportedLanguages = SUPPORTED_LANGUAGES_EN ) - val error = assertThrows(IllegalStateException::class) { + val error = assertThrows() { runScript(tempFolder.getFilePath("input.zip"), tempFolder.getFilePath("output.zip")) } diff --git a/scripts/src/javatests/org/oppia/android/scripts/build/TransformAndroidManifestTest.kt b/scripts/src/javatests/org/oppia/android/scripts/build/TransformAndroidManifestTest.kt index 424d22b661f..5d197b04615 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/build/TransformAndroidManifestTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/build/TransformAndroidManifestTest.kt @@ -70,7 +70,7 @@ class TransformAndroidManifestTest { fun testUtility_noArgs_failsWithUsageString() { initializeEmptyGitRepository() - val exception = assertThrows(IllegalStateException::class) { runScript() } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(USAGE_STRING) } @@ -79,7 +79,7 @@ class TransformAndroidManifestTest { fun testUtility_oneArg_failsWithUsageString() { initializeEmptyGitRepository() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript(tempFolder.root.absolutePath) } @@ -91,7 +91,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript(tempFolder.root.absolutePath, manifestFile.absolutePath) } @@ -103,7 +103,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, manifestFile.absolutePath, @@ -119,7 +119,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, manifestFile.absolutePath, @@ -136,7 +136,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, manifestFile.absolutePath, @@ -154,7 +154,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, manifestFile.absolutePath, @@ -173,7 +173,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, manifestFile.absolutePath, @@ -193,7 +193,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, manifestFile.absolutePath, @@ -214,7 +214,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, manifestFile.absolutePath, @@ -236,7 +236,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, manifestFile.absolutePath, @@ -258,7 +258,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, manifestFile.absolutePath, @@ -280,7 +280,7 @@ class TransformAndroidManifestTest { initializeEmptyGitRepository() val manifestFile = tempFolder.newFile(TEST_MANIFEST_FILE_NAME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( "nowhere", manifestFile.absolutePath, @@ -301,7 +301,7 @@ class TransformAndroidManifestTest { fun testUtility_allArgs_manifestDoesNotExist_failsWithError() { initializeEmptyGitRepository() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, "fake_manifest_file", @@ -325,7 +325,7 @@ class TransformAndroidManifestTest { writeText(TEST_MANIFEST_CONTENT_WITHOUT_VERSIONS_AND_APPLICATION) } - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript( tempFolder.root.absolutePath, manifestFile.absolutePath, diff --git a/scripts/src/javatests/org/oppia/android/scripts/ci/BUILD.bazel b/scripts/src/javatests/org/oppia/android/scripts/ci/BUILD.bazel index cb9eafb6d21..fcdb77f2f1d 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/ci/BUILD.bazel +++ b/scripts/src/javatests/org/oppia/android/scripts/ci/BUILD.bazel @@ -8,7 +8,7 @@ kt_jvm_test( name = "ComputeAffectedTestsTest", size = "large", srcs = ["ComputeAffectedTestsTest.kt"], - shard_count = 4, + shard_count = 24, deps = [ "//scripts/src/java/org/oppia/android/scripts/ci:compute_affected_tests_lib", "//scripts/src/java/org/oppia/android/scripts/common:proto_string_encoder", diff --git a/scripts/src/javatests/org/oppia/android/scripts/ci/ComputeAffectedTestsTest.kt b/scripts/src/javatests/org/oppia/android/scripts/ci/ComputeAffectedTestsTest.kt index 654e42425c8..2bf59212f66 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/ci/ComputeAffectedTestsTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/ci/ComputeAffectedTestsTest.kt @@ -16,6 +16,7 @@ import java.io.ByteArrayOutputStream import java.io.File import java.io.OutputStream import java.io.PrintStream +import java.util.concurrent.TimeUnit /** * Tests for the compute_affected_tests utility. @@ -28,13 +29,12 @@ import java.io.PrintStream // Function name: test names are conventionally named with underscores. @Suppress("SameParameterValue", "FunctionName") class ComputeAffectedTestsTest { - @Rule - @JvmField - var tempFolder = TemporaryFolder() + @field:[Rule JvmField] val tempFolder = TemporaryFolder() + + private val commandExecutor by lazy { initiazeCommandExecutorWithLongProcessWaitTime() } private lateinit var testBazelWorkspace: TestBazelWorkspace private lateinit var testGitRepository: TestGitRepository - private lateinit var pendingOutputStream: ByteArrayOutputStream private lateinit var originalStandardOutputStream: OutputStream @@ -57,12 +57,12 @@ class ComputeAffectedTestsTest { // Print the status of the git repository to help with debugging in the cases of test failures // and to help manually verify the expect git state at the end of each test. println("git status (at end of test):") - println(testGitRepository.status()) + println(testGitRepository.status(checkForGitRepository = false)) } @Test fun testUtility_noArguments_printsUsageStringAndExits() { - val exception = assertThrows(SecurityException::class) { main(arrayOf()) } + val exception = assertThrows() { main(arrayOf()) } // Bazel catches the System.exit() call and throws a SecurityException. This is a bit hacky way // to verify that System.exit() is called, but it's helpful. @@ -72,7 +72,7 @@ class ComputeAffectedTestsTest { @Test fun testUtility_oneArgument_printsUsageStringAndExits() { - val exception = assertThrows(SecurityException::class) { main(arrayOf("first")) } + val exception = assertThrows() { main(arrayOf("first")) } // Bazel catches the System.exit() call and throws a SecurityException. This is a bit hacky way // to verify that System.exit() is called, but it's helpful. @@ -82,7 +82,7 @@ class ComputeAffectedTestsTest { @Test fun testUtility_twoArguments_printsUsageStringAndExits() { - val exception = assertThrows(SecurityException::class) { main(arrayOf("first", "second")) } + val exception = assertThrows() { main(arrayOf("first", "second")) } // Bazel catches the System.exit() call and throws a SecurityException. This is a bit hacky way // to verify that System.exit() is called, but it's helpful. @@ -92,7 +92,7 @@ class ComputeAffectedTestsTest { @Test fun testUtility_threeArguments_printsUsageStringAndExits() { - val exception = assertThrows(SecurityException::class) { + val exception = assertThrows() { main(arrayOf("first", "second", "third")) } @@ -104,7 +104,7 @@ class ComputeAffectedTestsTest { @Test fun testUtility_directoryRootDoesNotExist_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { main(arrayOf("fake", "alsofake", "andstillfake", "compute_all_tests=false")) } @@ -113,7 +113,7 @@ class ComputeAffectedTestsTest { @Test fun testUtility_invalid_lastArgument_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { main(arrayOf("fake", "alsofake", "andstillfake", "compute_all_testss=false")) } @@ -123,7 +123,7 @@ class ComputeAffectedTestsTest { @Test fun testUtility_invalid_lastArgumentValue_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { main(arrayOf("fake", "alsofake", "andstillfake", "compute_all_tests=blah")) } @@ -133,7 +133,7 @@ class ComputeAffectedTestsTest { @Test fun testUtility_emptyDirectory_throwsException() { - val exception = assertThrows(IllegalStateException::class) { runScript() } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains("run from the workspace's root directory") } @@ -724,7 +724,8 @@ class ComputeAffectedTestsTest { ComputeAffectedTests( maxTestCountPerLargeShard = maxTestCountPerLargeShard, maxTestCountPerMediumShard = maxTestCountPerMediumShard, - maxTestCountPerSmallShard = maxTestCountPerSmallShard + maxTestCountPerSmallShard = maxTestCountPerSmallShard, + commandExecutor = commandExecutor ).compute( pathToRoot = tempFolder.root.absolutePath, pathToOutputFile = outputLog.absolutePath, @@ -862,4 +863,8 @@ class ComputeAffectedTestsTest { testGitRepository.stageFileForCommit(libFile) testGitRepository.commit(message = "Modified library $name") } + + private fun initiazeCommandExecutorWithLongProcessWaitTime(): CommandExecutorImpl { + return CommandExecutorImpl(processTimeout = 5, processTimeoutUnit = TimeUnit.MINUTES) + } } diff --git a/scripts/src/javatests/org/oppia/android/scripts/ci/RetrieveAffectedTestsTest.kt b/scripts/src/javatests/org/oppia/android/scripts/ci/RetrieveAffectedTestsTest.kt index d43a7055f51..e449b856a6f 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/ci/RetrieveAffectedTestsTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/ci/RetrieveAffectedTestsTest.kt @@ -45,7 +45,7 @@ class RetrieveAffectedTestsTest { @Test fun testUtility_noArguments_printsUsageStringAndExits() { - val exception = assertThrows(SecurityException::class) { runScript() } + val exception = assertThrows() { runScript() } // Bazel catches the System.exit() call and throws a SecurityException. This is a bit hacky way // to verify that System.exit() is called, but it's helpful. @@ -55,7 +55,7 @@ class RetrieveAffectedTestsTest { @Test fun testUtility_oneArgument_printsUsageStringAndExits() { - val exception = assertThrows(SecurityException::class) { runScript("arg1") } + val exception = assertThrows() { runScript("arg1") } // Bazel catches the System.exit() call and throws a SecurityException. This is a bit hacky way // to verify that System.exit() is called, but it's helpful. @@ -65,7 +65,7 @@ class RetrieveAffectedTestsTest { @Test fun testUtility_twoArguments_printsUsageStringAndExits() { - val exception = assertThrows(SecurityException::class) { runScript("arg1", "arg2") } + val exception = assertThrows() { runScript("arg1", "arg2") } // Bazel catches the System.exit() call and throws a SecurityException. This is a bit hacky way // to verify that System.exit() is called, but it's helpful. @@ -75,7 +75,7 @@ class RetrieveAffectedTestsTest { @Test fun testUtility_invalidBase64_throwsException() { - assertThrows(IllegalArgumentException::class) { runScript("badbase64", "file1", "file2") } + assertThrows() { runScript("badbase64", "file1", "file2") } } @Test diff --git a/scripts/src/javatests/org/oppia/android/scripts/common/BUILD.bazel b/scripts/src/javatests/org/oppia/android/scripts/common/BUILD.bazel index e47fc741ab6..bceb5cfe864 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/common/BUILD.bazel +++ b/scripts/src/javatests/org/oppia/android/scripts/common/BUILD.bazel @@ -8,6 +8,7 @@ load("@io_bazel_rules_kotlin//kotlin:kotlin.bzl", "kt_jvm_test") kt_jvm_test( name = "BazelClientTest", srcs = ["BazelClientTest.kt"], + shard_count = 4, deps = [ "//scripts/src/java/org/oppia/android/scripts/common:bazel_client", "//scripts/src/java/org/oppia/android/scripts/testing:test_bazel_workspace", diff --git a/scripts/src/javatests/org/oppia/android/scripts/common/BazelClientTest.kt b/scripts/src/javatests/org/oppia/android/scripts/common/BazelClientTest.kt index f2e7914682c..2109155025f 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/common/BazelClientTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/common/BazelClientTest.kt @@ -25,20 +25,14 @@ import java.util.concurrent.TimeUnit // Function name: test names are conventionally named with underscores. @Suppress("SameParameterValue", "FunctionName") class BazelClientTest { - @Rule - @JvmField - var tempFolder = TemporaryFolder() + @field:[Rule JvmField] val tempFolder = TemporaryFolder() + @field:[Rule JvmField] val mockitoRule: MockitoRule = MockitoJUnit.rule() - @Rule - @JvmField - val mockitoRule: MockitoRule = MockitoJUnit.rule() + @Mock lateinit var mockCommandExecutor: CommandExecutor private val commandExecutor by lazy { initiazeCommandExecutorWithLongProcessWaitTime() } private lateinit var testBazelWorkspace: TestBazelWorkspace - @Mock - lateinit var mockCommandExecutor: CommandExecutor - @Before fun setUp() { testBazelWorkspace = TestBazelWorkspace(tempFolder) @@ -46,9 +40,9 @@ class BazelClientTest { @Test fun testRetrieveTestTargets_emptyFolder_fails() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { bazelClient.retrieveAllTestTargets() } @@ -59,10 +53,10 @@ class BazelClientTest { @Test fun testRetrieveTestTargets_emptyWorkspace_fails() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { bazelClient.retrieveAllTestTargets() } @@ -73,7 +67,7 @@ class BazelClientTest { @Test fun testRetrieveTestTargets_workspaceWithTest_returnsTestTarget() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest("ExampleTest") @@ -84,7 +78,7 @@ class BazelClientTest { @Test fun testRetrieveTestTargets_workspaceWithMultipleTests_returnsTestTargets() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest("FirstTest") testBazelWorkspace.createTest("SecondTest") @@ -106,7 +100,7 @@ class BazelClientTest { @Test fun testRetrieveBazelTargets_forFileNotInBuildGraph_returnsEmptyList() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() tempFolder.newFile("filenotingraph") @@ -117,7 +111,7 @@ class BazelClientTest { @Test fun testRetrieveBazelTargets_forTestFile_returnsBazelTarget() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest("FirstTest") @@ -128,7 +122,7 @@ class BazelClientTest { @Test fun testRetrieveBazelTargets_forMultipleMixedFiles_returnsBazelTargets() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest("FirstTest") testBazelWorkspace.createTest("SecondTest", withGeneratedDependency = true) @@ -157,7 +151,7 @@ class BazelClientTest { @Test fun testRetrieveRelatedTestTargets_forTargetWithNoTestDependency_returnsNoTargets() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createLibrary("SomeDependency") testBazelWorkspace.createTest("FirstTest") @@ -170,7 +164,7 @@ class BazelClientTest { @Test fun testRetrieveRelatedTestTargets_forTestFileTarget_returnsTestTarget() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest("FirstTest") @@ -181,7 +175,7 @@ class BazelClientTest { @Test fun testRetrieveRelatedTestTargets_forDependentFileTarget_returnsTestTarget() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest("FirstTest", withGeneratedDependency = true) @@ -192,7 +186,7 @@ class BazelClientTest { @Test fun testRetrieveRelatedTestTargets_forMixedFileTargets_returnsRelatedTestTargets() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createLibrary("ExtraDep") testBazelWorkspace.createTest("FirstTest", withExtraDependency = "//:ExtraDep_lib") @@ -227,7 +221,7 @@ class BazelClientTest { @Test fun testRetrieveTransitiveTestTargets_forNoFiles_returnsEmptyList() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() val testTargets = bazelClient.retrieveTransitiveTestTargets(listOf()) @@ -238,7 +232,7 @@ class BazelClientTest { @Test fun testRetrieveTransitiveTestTargets_forBuildFile_returnsAllTestsInThatBuildFile() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest("FirstTest") testBazelWorkspace.createTest("SecondTest") @@ -253,7 +247,7 @@ class BazelClientTest { @Test fun testRetrieveTransitiveTestTargets_forMultipleBuildFiles_returnsAllRelatedTests() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest("FirstTest") testBazelWorkspace.createTest("SecondTest", subpackage = "two") @@ -269,7 +263,7 @@ class BazelClientTest { @Test fun testRetrieveTransitiveTestTargets_forBzlFile_returnsRelatedTests() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() // Generate tests. testBazelWorkspace.createTest("FirstTest") @@ -298,7 +292,7 @@ class BazelClientTest { @Test fun testRetrieveTransitiveTestTargets_forWorkspace_returnsAllTests() { - val bazelClient = BazelClient(tempFolder.root) + val bazelClient = BazelClient(tempFolder.root, commandExecutor) testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest("FirstTest") testBazelWorkspace.createTest("SecondTest", subpackage = "two") diff --git a/scripts/src/javatests/org/oppia/android/scripts/common/CommandExecutorImplTest.kt b/scripts/src/javatests/org/oppia/android/scripts/common/CommandExecutorImplTest.kt index e04c0954b85..78dc945dff6 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/common/CommandExecutorImplTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/common/CommandExecutorImplTest.kt @@ -37,7 +37,7 @@ class CommandExecutorImplTest { fun testExecute_echo_invalidDirectory_throwsException() { val commandExecutor = CommandExecutorImpl() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { commandExecutor.executeCommand(File("invaliddirectory"), "echo", "value") } @@ -53,7 +53,7 @@ class CommandExecutorImplTest { // Produce a large output so that echo takes a bit longer to reduce the likelihood of this test // flaking on faster machines. val largeOutput = "a".repeat(100_000) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { commandExecutor.executeCommand(tempFolder.root, "echo", largeOutput) } @@ -65,7 +65,7 @@ class CommandExecutorImplTest { fun testExecute_nonexistentCommand_throwsException() { val commandExecutor = CommandExecutorImpl() - val exception = assertThrows(IOException::class) { + val exception = assertThrows() { commandExecutor.executeCommand(tempFolder.root, "commanddoesnotexist") } diff --git a/scripts/src/javatests/org/oppia/android/scripts/common/GitClientTest.kt b/scripts/src/javatests/org/oppia/android/scripts/common/GitClientTest.kt index 9362d7dd006..c3126339eca 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/common/GitClientTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/common/GitClientTest.kt @@ -35,16 +35,16 @@ class GitClientTest { @After fun tearDown() { // Print the status of the git repository to help with debugging in the cases of test failures - // and to help manually verify the expect git state at the end of each test. + // and to help manually verify the expected git state at the end of each test. println("git status (at end of test):") - println(testGitRepository.status()) + println(testGitRepository.status(checkForGitRepository = false)) } @Test fun testCurrentCommit_forNonRepository_throwsException() { val gitClient = GitClient(tempFolder.root, "develop") - val exception = assertThrows(IllegalStateException::class) { gitClient.currentCommit } + val exception = assertThrows() { gitClient.currentCommit } assertThat(exception).hasMessageThat().contains("Expected non-zero exit code") assertThat(exception).hasMessageThat().ignoringCase().contains("not a git repository") @@ -80,7 +80,7 @@ class GitClientTest { fun testCurrentBranch_forNonRepository_throwsException() { val gitClient = GitClient(tempFolder.root, "develop") - val exception = assertThrows(IllegalStateException::class) { gitClient.currentBranch } + val exception = assertThrows() { gitClient.currentBranch } assertThat(exception).hasMessageThat().contains("Expected non-zero exit code") assertThat(exception).hasMessageThat().ignoringCase().contains("not a git repository") diff --git a/scripts/src/javatests/org/oppia/android/scripts/common/ProtoStringEncoderTest.kt b/scripts/src/javatests/org/oppia/android/scripts/common/ProtoStringEncoderTest.kt index b03c106500a..bed9db19a1b 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/common/ProtoStringEncoderTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/common/ProtoStringEncoderTest.kt @@ -34,14 +34,14 @@ class ProtoStringEncoderTest { @Test fun testDecode_emptyString_throwsException() { - assertThrows(EOFException::class) { + assertThrows() { TestMessage.getDefaultInstance().mergeFromCompressedBase64(base64 = "") } } @Test fun testDecode_badString_throwsException() { - assertThrows(ZipException::class) { + assertThrows() { TestMessage.getDefaultInstance().mergeFromCompressedBase64(base64 = "asdf") } } diff --git a/scripts/src/javatests/org/oppia/android/scripts/docs/KdocValidityCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/docs/KdocValidityCheckTest.kt index 9a7b61faa6a..6850c951041 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/docs/KdocValidityCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/docs/KdocValidityCheckTest.kt @@ -46,7 +46,7 @@ class KdocValidityCheckTest { val testContent = """ /** - * Returns the string corresponding to this error's string resources, or null if there + * Returns the string corresponding to this error's string resources, or null if there * is none. */ fun getErrorMessageFromStringRes(context: Context): String? { @@ -260,7 +260,7 @@ class KdocValidityCheckTest { val testContent = """ val testVal = "testContent" - + fun provideContext(application: Application): Context """.trimIndent() val tempFile = tempFolder.newFile("testfiles/TempFileTest.kt") @@ -281,16 +281,14 @@ class KdocValidityCheckTest { val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:2 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -352,21 +350,19 @@ class KdocValidityCheckTest { fun testKdoc_class_withoutKdoc_checkShouldFail() { val testContent = """ - class TestClass {} + class TestClass {} """.trimIndent() val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:1 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -382,21 +378,19 @@ class KdocValidityCheckTest { class NestedClass { class NestedLevel2Class {} } - } + } """.trimIndent() val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:5 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -409,16 +403,14 @@ class KdocValidityCheckTest { /** Test KDoc 1. */ class TestClass { val testVal = "test" - + fun testFunc(){} - } + } """.trimIndent() val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -426,7 +418,7 @@ class KdocValidityCheckTest { KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:3 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:5 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -442,9 +434,7 @@ class KdocValidityCheckTest { val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -452,7 +442,7 @@ class KdocValidityCheckTest { KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:1 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:2 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -468,16 +458,14 @@ class KdocValidityCheckTest { val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:2 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -495,16 +483,14 @@ class KdocValidityCheckTest { val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:4 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -522,9 +508,7 @@ class KdocValidityCheckTest { val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -533,7 +517,7 @@ class KdocValidityCheckTest { - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:1 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:2 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:3 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -544,15 +528,13 @@ class KdocValidityCheckTest { val testContent = """ const val TABLE_USER_ATTRIBUTE_EMPID = "_id" - + const val TABLE_USER_ATTRIBUTE_DATA = "data" """.trimIndent() val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -560,7 +542,7 @@ class KdocValidityCheckTest { KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:1 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:3 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -572,21 +554,19 @@ class KdocValidityCheckTest { """ fun getErrorMessageFromStringRes(context: Context): String? { return error?.let(context::getString) - } + } """.trimIndent() val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:1 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -604,16 +584,14 @@ class KdocValidityCheckTest { val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:3 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -627,14 +605,12 @@ class KdocValidityCheckTest { WELCOME(0), TOPIC_LIST(1), FINAL(2) - } + } """.trimIndent() val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -644,7 +620,7 @@ class KdocValidityCheckTest { - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:2 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:3 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:4 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -655,22 +631,20 @@ class KdocValidityCheckTest { val testContent = """ interface ChapterSelector { - + fun chapterSelected(chapterIndex: Int, nextStoryIndex: Int, explorationId: String) - + fun chapterUnselected(chapterIndex: Int, nextStoryIndex: Int) - + interface ChildInterface { fun testFunction() } - } + } """.trimIndent() val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -681,7 +655,7 @@ class KdocValidityCheckTest { - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:5 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:7 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:8 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -695,11 +669,11 @@ class KdocValidityCheckTest { class TestClass { companion object { val pos = 1 - + fun incrementedPosition(position: Int): Int { return position+1 } - + fun decrementedPosition(position: Int): Int { return position-1 } @@ -709,9 +683,7 @@ class KdocValidityCheckTest { val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -720,7 +692,7 @@ class KdocValidityCheckTest { - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:4 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:6 - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:10 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -748,23 +720,21 @@ class KdocValidityCheckTest { val testContent = """ import javax.inject.Qualifier - + @Qualifier annotation class DelayShowAdditionalHintsFromWrongAnswerMillis """.trimIndent() val tempFile = tempFolder.newFile("testfiles/TempFile.kt") tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/TempFile.kt:4 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -775,7 +745,7 @@ class KdocValidityCheckTest { val testContent1 = """ import javax.inject.Qualifier - + @Qualifier annotation class DelayShowAdditionalHintsFromWrongAnswerMillis """.trimIndent() @@ -783,9 +753,9 @@ class KdocValidityCheckTest { """ class TestClass { fun testFunc(){} - + private val testVal = "test" - + val testVal2 = "test2" } """.trimIndent() @@ -800,9 +770,7 @@ class KdocValidityCheckTest { tempFile2.writeText(testContent2) tempFile3.writeText(testContent3) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -813,7 +781,7 @@ class KdocValidityCheckTest { - ${retrieveTestFilesDirectoryPath()}/TempFile2.kt:2 - ${retrieveTestFilesDirectoryPath()}/TempFile2.kt:6 - ${retrieveTestFilesDirectoryPath()}/TempFile3.kt:1 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -825,9 +793,9 @@ class KdocValidityCheckTest { """ /** test kdoc. */ val testVal1 = "test content" - + val testVal2 = "test content" - + fun getErrorMessageFromStringRes(context: Context): String? { return error?.let(context::getString) } @@ -858,7 +826,7 @@ class KdocValidityCheckTest { """ /** test Kdoc1. */ val testVal = "test content" - + /** test Kdoc2. */ fun getErrorMessageFromStringRes(context: Context): String? { return error?.let(context::getString) @@ -879,9 +847,7 @@ class KdocValidityCheckTest { }.build() exemptions.writeTo(exemptionFile.outputStream()) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -913,9 +879,7 @@ class KdocValidityCheckTest { }.build() exemptions.writeTo(exemptionFile.outputStream()) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(KDOC_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -923,10 +887,10 @@ class KdocValidityCheckTest { Redundant exemptions: - app/src/main/java/org/oppia/android/app/splash/SplashActivity.kt Please remove them from scripts/assets/kdoc_validity_exemptions.textproto - + KDoc missing for files: - ${retrieveTestFilesDirectoryPath()}/HomeActivity.kt:1 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) diff --git a/scripts/src/javatests/org/oppia/android/scripts/label/AccessibilityLabelCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/label/AccessibilityLabelCheckTest.kt index a1410b3ead2..900140e93f7 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/label/AccessibilityLabelCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/label/AccessibilityLabelCheckTest.kt @@ -92,7 +92,7 @@ class AccessibilityLabelCheckTest { val manifestFile = tempFolder.newFile("testfiles/$tempFileRelativePath") manifestFile.writeText(testContent) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main( retrieveTestFilesDirectoryPath(), "${tempFolder.root}/$pathToProtoBinary", @@ -134,7 +134,7 @@ class AccessibilityLabelCheckTest { val manifestFile = tempFolder.newFile("testfiles/$tempFileRelativePath") manifestFile.writeText(testContent) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main( retrieveTestFilesDirectoryPath(), "${tempFolder.root}/$pathToProtoBinary", @@ -244,7 +244,7 @@ class AccessibilityLabelCheckTest { appManifestFile.writeText(testContent1) splashManifestFile.writeText(testContent2) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main( retrieveTestFilesDirectoryPath(), "${tempFolder.root}/$pathToProtoBinary", @@ -308,7 +308,7 @@ class AccessibilityLabelCheckTest { appManifestFile.writeText(testContent1) splashManifestFile.writeText(testContent2) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main( retrieveTestFilesDirectoryPath(), "${tempFolder.root}/$pathToProtoBinary", @@ -393,7 +393,7 @@ class AccessibilityLabelCheckTest { }.build() exemptions.writeTo(exemptionFile.outputStream()) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main( retrieveTestFilesDirectoryPath(), "${tempFolder.root}/$pathToProtoBinary", @@ -436,7 +436,7 @@ class AccessibilityLabelCheckTest { }.build() exemptions.writeTo(exemptionFile.outputStream()) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main( retrieveTestFilesDirectoryPath(), "${tempFolder.root}/$pathToProtoBinary", diff --git a/scripts/src/javatests/org/oppia/android/scripts/license/BUILD.bazel b/scripts/src/javatests/org/oppia/android/scripts/license/BUILD.bazel index 707ec3e8081..ab6b739a3b8 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/license/BUILD.bazel +++ b/scripts/src/javatests/org/oppia/android/scripts/license/BUILD.bazel @@ -19,6 +19,7 @@ kt_jvm_test( name = "MavenDependenciesListCheckTest", size = "large", srcs = ["MavenDependenciesListCheckTest.kt"], + shard_count = 4, deps = [ "//scripts/src/java/org/oppia/android/scripts/license:maven_dependencies_list_check_lib", "//scripts/src/java/org/oppia/android/scripts/testing:test_bazel_workspace", diff --git a/scripts/src/javatests/org/oppia/android/scripts/license/LicenseTextsCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/license/LicenseTextsCheckTest.kt index 8a70436c6c7..baf034a9095 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/license/LicenseTextsCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/license/LicenseTextsCheckTest.kt @@ -41,7 +41,7 @@ class LicenseTextsCheckTest { val thirdPartyDepsXmlFile = tempFolder.newFile("values/third_party_dependencies.xml") thirdPartyDepsXmlFile.writeText(WARNING_COMMENT) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main(arrayOf()) } @@ -53,7 +53,7 @@ class LicenseTextsCheckTest { val thirdPartyDepsXmlFile = tempFolder.newFile("values/third_party_dependencies.xml") thirdPartyDepsXmlFile.writeText("") - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main(arrayOf("${tempFolder.root}/values/third_party_dependencies.xml")) } @@ -72,7 +72,7 @@ class LicenseTextsCheckTest { """.trimIndent() ) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main(arrayOf("${tempFolder.root}/values/third_party_dependencies.xml")) } @@ -110,7 +110,7 @@ class LicenseTextsCheckTest { @Test fun testLicenseTexsCheck_xmlFileNotPresent_checkFailsWithFileNotFoundException() { val pathToThirdPartyDepsXml = "${tempFolder.root}/values/third_party_dependencies.xml" - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main(arrayOf("${tempFolder.root}/values/third_party_dependencies.xml")) } diff --git a/scripts/src/javatests/org/oppia/android/scripts/license/MavenDependenciesListCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/license/MavenDependenciesListCheckTest.kt index f30b261f53a..5fdc807e3db 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/license/MavenDependenciesListCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/license/MavenDependenciesListCheckTest.kt @@ -110,7 +110,7 @@ class MavenDependenciesListCheckTest { val coordsList = listOf(DATA_BINDING_DEP, FIREBASE_ANALYTICS_DEP) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor @@ -186,7 +186,7 @@ class MavenDependenciesListCheckTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor @@ -250,7 +250,7 @@ class MavenDependenciesListCheckTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor @@ -326,7 +326,7 @@ class MavenDependenciesListCheckTest { val coordsList = listOf(GLIDE_DEP) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor @@ -405,7 +405,7 @@ class MavenDependenciesListCheckTest { val coordsList = listOf(GLIDE_DEP) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor @@ -481,7 +481,7 @@ class MavenDependenciesListCheckTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor @@ -559,7 +559,7 @@ class MavenDependenciesListCheckTest { ) setUpBazelEnvironmentWithUpdatedFirebaseDependency(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor @@ -637,7 +637,7 @@ class MavenDependenciesListCheckTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor @@ -770,7 +770,7 @@ class MavenDependenciesListCheckTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor @@ -819,7 +819,7 @@ class MavenDependenciesListCheckTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor @@ -874,7 +874,7 @@ class MavenDependenciesListCheckTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { MavenDependenciesListCheck( mockLicenseFetcher, commandExecutor diff --git a/scripts/src/javatests/org/oppia/android/scripts/maven/BUILD.bazel b/scripts/src/javatests/org/oppia/android/scripts/maven/BUILD.bazel index a46ee7ad500..68b0d6fad28 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/maven/BUILD.bazel +++ b/scripts/src/javatests/org/oppia/android/scripts/maven/BUILD.bazel @@ -9,6 +9,7 @@ kt_jvm_test( name = "GenerateMavenDependenciesListTest", size = "large", srcs = ["GenerateMavenDependenciesListTest.kt"], + shard_count = 4, deps = [ "//scripts/src/java/org/oppia/android/scripts/common:command_executor", "//scripts/src/java/org/oppia/android/scripts/maven:generate_maven_dependencies_list_lib", diff --git a/scripts/src/javatests/org/oppia/android/scripts/maven/GenerateMavenDependenciesListTest.kt b/scripts/src/javatests/org/oppia/android/scripts/maven/GenerateMavenDependenciesListTest.kt index 6d63a6e9c6d..4507d76a5dc 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/maven/GenerateMavenDependenciesListTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/maven/GenerateMavenDependenciesListTest.kt @@ -96,7 +96,7 @@ class GenerateMavenDependenciesListTest { val coordsList = listOf(DEP_WITH_SCRAPABLE_LICENSE, DEP_WITH_DIRECT_LINK_ONLY_LICENSE) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { GenerateMavenDependenciesList( mockLicenseFetcher, commandExecutor @@ -180,7 +180,7 @@ class GenerateMavenDependenciesListTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { GenerateMavenDependenciesList( mockLicenseFetcher, commandExecutor @@ -204,7 +204,7 @@ class GenerateMavenDependenciesListTest { val coordsList = listOf(DEP_WITH_DIRECT_LINK_ONLY_LICENSE) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { GenerateMavenDependenciesList( mockLicenseFetcher, commandExecutor @@ -246,7 +246,7 @@ class GenerateMavenDependenciesListTest { val coordsList = listOf(DEP_WITH_SCRAPABLE_AND_EXTRACTED_COPY_LICENSES) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { GenerateMavenDependenciesList( mockLicenseFetcher, commandExecutor @@ -313,7 +313,7 @@ class GenerateMavenDependenciesListTest { val coordsList = listOf(DEP_WITH_INVALID_LINKS) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { GenerateMavenDependenciesList( mockLicenseFetcher, commandExecutor @@ -355,7 +355,7 @@ class GenerateMavenDependenciesListTest { val coordsList = listOf(DEP_WITH_NO_LICENSE) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { GenerateMavenDependenciesList( mockLicenseFetcher, commandExecutor @@ -614,7 +614,7 @@ class GenerateMavenDependenciesListTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { GenerateMavenDependenciesList( mockLicenseFetcher, commandExecutor @@ -790,7 +790,7 @@ class GenerateMavenDependenciesListTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { GenerateMavenDependenciesList( mockLicenseFetcher, commandExecutor @@ -915,7 +915,7 @@ class GenerateMavenDependenciesListTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { GenerateMavenDependenciesList( mockLicenseFetcher, commandExecutor @@ -1028,7 +1028,7 @@ class GenerateMavenDependenciesListTest { ) setUpBazelEnvironment(coordsList) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { GenerateMavenDependenciesList( mockLicenseFetcher, commandExecutor diff --git a/scripts/src/javatests/org/oppia/android/scripts/maven/RetrieveLicenseTextsTest.kt b/scripts/src/javatests/org/oppia/android/scripts/maven/RetrieveLicenseTextsTest.kt index 6be3f9c0d71..d889d6ede2b 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/maven/RetrieveLicenseTextsTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/maven/RetrieveLicenseTextsTest.kt @@ -63,7 +63,7 @@ class RetrieveLicenseTextsTest { @Test fun testScript_oneArgument_printsUsageStringAndThrowsException() { - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { RetrieveLicenseTexts(mockLicenseFetcher).main(arrayOf()) } @@ -73,7 +73,7 @@ class RetrieveLicenseTextsTest { @Test fun testScript_oneArguments_printsUsageStringAndThrowsException() { - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { RetrieveLicenseTexts(mockLicenseFetcher).main( arrayOf( "${tempFolder.root}/values" @@ -92,7 +92,7 @@ class RetrieveLicenseTextsTest { val pbFile = tempFolder.newFile("scripts/assets/maven_dependencies.pb") pbFile.outputStream().use { mavenDependencyList.writeTo(it) } - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { RetrieveLicenseTexts(mockLicenseFetcher).main( arrayOf( "${tempFolder.root}/values", @@ -111,7 +111,7 @@ class RetrieveLicenseTextsTest { val pbFile = tempFolder.newFile("scripts/assets/maven_dependencies.pb") pbFile.outputStream().use { mavenDependencyList.writeTo(it) } - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { RetrieveLicenseTexts(mockLicenseFetcher).main( arrayOf( "${tempFolder.root}/values", @@ -141,7 +141,7 @@ class RetrieveLicenseTextsTest { val pbFile = tempFolder.newFile("scripts/assets/maven_dependencies.pb") pbFile.outputStream().use { mavenDependencyList.writeTo(it) } - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { RetrieveLicenseTexts(mockLicenseFetcher).main( arrayOf( "${tempFolder.root}/values", diff --git a/scripts/src/javatests/org/oppia/android/scripts/regex/RegexPatternValidationCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/regex/RegexPatternValidationCheckTest.kt index 20fd219f857..a3eb9c825d9 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/regex/RegexPatternValidationCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/regex/RegexPatternValidationCheckTest.kt @@ -211,6 +211,13 @@ class RegexPatternValidationCheckTest { " should immediately follow the at-clause without any additional linking with brackets." private val badSingleLineKdocShouldEndWithPunctuation = "Badly formatted KDoc. Single-line KDocs should end with punctuation." + private val activityTestRuleShouldNotBeUsed = + "ActivityTestRule is deprecated since it operates test activities in sometimes unsafe" + + " situations. Use ActivityScenario, instead." + private val activityScenarioRuleShouldNotBeUsed = + "ActivityScenarioRule can result in order dependence when static state leaks across tests" + + " (such as static module variables), and can make staging much more difficult for platform" + + " parameters. Use ActivityScenario directly, instead." private val wikiReferenceNote = "Refer to https://github.com/oppia/oppia-android/wiki/Static-Analysis-Checks" + "#regexpatternvalidation-check for more details on how to fix this." @@ -259,9 +266,7 @@ class RegexPatternValidationCheckTest { val tempFile = tempFolder.newFile("testfiles/data/src/main/TestActivity.kt") tempFile.writeText(requiredContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()).isEqualTo( @@ -289,9 +294,7 @@ class RegexPatternValidationCheckTest { tempFolder.newFolder("testfiles", "app", "src", "main", "res", "values", "subdir") tempFolder.newFile("testfiles/app/src/main/res/values/subdir/strings.xml") - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()).isEqualTo( @@ -309,16 +312,14 @@ class RegexPatternValidationCheckTest { tempFolder.newFolder("testfiles", "domain", "src", "main", "res", "drawable", "subdir") tempFolder.newFile("testfiles/domain/src/main/res/drawable/subdir/example.png") - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()).isEqualTo( """ File name/path violation: $nestedResourceSubdirectoryErrorMessage - domain/src/main/res/drawable/subdir/example.png - + $wikiReferenceNote """.trimIndent() ) @@ -339,9 +340,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/TestFile.kt") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -359,9 +358,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/TestFile.kt") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -379,9 +376,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/TestFile.kt") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -399,9 +394,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/TestFile.kt") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -419,9 +412,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/TestFile.kt") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -439,9 +430,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -459,9 +448,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -479,9 +466,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -499,9 +484,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -519,9 +502,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -539,9 +520,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -559,9 +538,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -579,9 +556,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -599,9 +574,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -619,9 +592,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -639,9 +610,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -659,9 +628,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -679,9 +646,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -699,9 +664,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -719,9 +682,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -739,9 +700,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -759,9 +718,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -779,9 +736,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -799,9 +754,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -819,9 +772,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -839,9 +790,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -859,9 +808,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -879,9 +826,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -899,9 +844,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -919,9 +862,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -939,9 +880,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -959,9 +898,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -979,9 +916,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -999,9 +934,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = tempFolder.newFile("testfiles/test_layout.xml") fileContainsSupportLibraryImport.writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1020,9 +953,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/strings.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1041,9 +972,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/strings.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1074,9 +1003,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/untranslated_strings.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1095,9 +1022,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/untranslated_strings.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1116,9 +1041,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "data/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1137,9 +1060,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "data/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1209,9 +1130,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "data/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -1252,9 +1171,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "data/src/main/SomeController.java" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -1287,9 +1204,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "data/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -1319,9 +1234,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/strings.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -1347,9 +1260,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/strings.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1372,9 +1283,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/strings.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1402,9 +1311,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/strings.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -1445,9 +1352,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/SomeActivity.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent + requiredContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1467,9 +1372,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/SomeActivity.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent + requiredContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1489,9 +1392,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/SomeActivity.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent + requiredContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1510,9 +1411,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/SomeDialogFragment.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1543,9 +1442,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/AndroidManifest.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1573,9 +1470,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/AndroidManifest.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1603,9 +1498,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/AndroidManifest.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1624,9 +1517,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "domain/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1645,9 +1536,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "domain/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1671,9 +1560,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "domain/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1694,9 +1581,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "domain/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1715,9 +1600,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "domain/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1747,9 +1630,7 @@ class RegexPatternValidationCheckTest { val fileContainsSupportLibraryImport = "test_layout.xml" tempFolder.newFile("testfiles/$fileContainsSupportLibraryImport").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1776,9 +1657,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "domain/src/test/SomeTest.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1798,9 +1677,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "data/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1819,9 +1696,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "domain/src/main/BUILD" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1840,9 +1715,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "domain/src/main/BUILD.bazel" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1861,9 +1734,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "domain/src/main/SomeController.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -1883,9 +1754,7 @@ class RegexPatternValidationCheckTest { val prohibitedFile = tempFolder.newFile("testfiles/data/src/main/TestActivity.kt") prohibitedFile.writeText(prohibitedContent + requiredContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()).isEqualTo( @@ -1916,9 +1785,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/color_palette.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -1966,9 +1833,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/color_defs.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2014,9 +1879,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/component_colors.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2061,9 +1924,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/color_defs.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2125,9 +1986,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/component_colors.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2173,9 +2032,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/color_palette.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2220,9 +2077,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/color_defs.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2265,9 +2120,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/component_colors.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2313,9 +2166,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/layout/test_layout.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2358,9 +2209,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/drawable/test_layout.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2411,9 +2260,7 @@ class RegexPatternValidationCheckTest { tempFolder.newFile("testfiles/$stringFilePath5").writeText(prohibitedContent) tempFolder.newFile("testfiles/$stringFilePath6").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2468,9 +2315,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/res/values/color_palette.xml" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2490,9 +2335,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/activity/HomeActivity.kt" tempFolder.newFile("testfiles/$stringFilePath") - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -2522,9 +2365,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/activity/HomeActivityTest.kt" tempFolder.newFile("testfiles/$stringFilePath") - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -2558,9 +2399,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/SomeInitializer.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } // Verify that all patterns are properly detected & prohibited. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2583,9 +2422,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/TestPresenter.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2608,9 +2445,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/TestPresenter.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2633,9 +2468,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/TestPresenter.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2663,7 +2496,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/TestPresenter.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { runScript() } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -2687,7 +2520,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/TestPresenter.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { runScript() } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -2712,7 +2545,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/TestPresenter.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { runScript() } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -2732,7 +2565,7 @@ class RegexPatternValidationCheckTest { /** Content here.*/ /** Content here. **/ /** Correct KDoc. */ - + /* * Incorrect block comment. **/ @@ -2750,7 +2583,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/TestPresenter.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { runScript() } + val exception = assertThrows() { runScript() } // Two patterns are combined in this check because they slightly overlap in affected cases (e.g. // line 2 fails due to three different checks), and one pattern is subequently needed for the @@ -2782,7 +2615,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/TestPresenter.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { runScript() } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -2812,7 +2645,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/TestPresenter.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { runScript() } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) assertThat(outContent.toString().trim()) @@ -2837,7 +2670,7 @@ class RegexPatternValidationCheckTest { val stringFilePath = "app/src/main/java/org/oppia/android/TestPresenter.kt" tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) - val exception = assertThrows(Exception::class) { runScript() } + val exception = assertThrows() { runScript() } // 'Punctuation' currently assumes a period. assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) @@ -2851,6 +2684,50 @@ class RegexPatternValidationCheckTest { ) } + @Test + fun testFileContent_referencesActivityTestRule_fileContentIsNotCorrect() { + val prohibitedContent = + """ + import androidx.test.rule.ActivityTestRule + """.trimIndent() + tempFolder.newFolder("testfiles", "app", "src", "test", "java", "org", "oppia", "android") + val stringFilePath = "app/src/test/java/org/oppia/android/PresenterTest.kt" + tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) + + val exception = assertThrows() { runScript() } + + assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) + assertThat(outContent.toString().trim()) + .isEqualTo( + """ + $stringFilePath:1: $activityTestRuleShouldNotBeUsed + $wikiReferenceNote + """.trimIndent() + ) + } + + @Test + fun testFileContent_referencesActivityScenarioRule_fileContentIsNotCorrect() { + val prohibitedContent = + """ + import androidx.test.ext.junit.rules.ActivityScenarioRule + """.trimIndent() + tempFolder.newFolder("testfiles", "app", "src", "test", "java", "org", "oppia", "android") + val stringFilePath = "app/src/test/java/org/oppia/android/PresenterTest.kt" + tempFolder.newFile("testfiles/$stringFilePath").writeText(prohibitedContent) + + val exception = assertThrows() { runScript() } + + assertThat(exception).hasMessageThat().contains(REGEX_CHECK_FAILED_OUTPUT_INDICATOR) + assertThat(outContent.toString().trim()) + .isEqualTo( + """ + $stringFilePath:1: $activityScenarioRuleShouldNotBeUsed + $wikiReferenceNote + """.trimIndent() + ) + } + /** Runs the regex_pattern_validation_check. */ private fun runScript() { main(File(tempFolder.root, "testfiles").absolutePath) diff --git a/scripts/src/javatests/org/oppia/android/scripts/testfile/TestFileCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/testfile/TestFileCheckTest.kt index a0fc700b720..1b6ded9633a 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/testfile/TestFileCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/testfile/TestFileCheckTest.kt @@ -52,15 +52,13 @@ class TestFileCheckTest { tempFolder.newFile("testfiles/ProdFile1Test.kt") tempFolder.newFile("testfiles/ProdFile2.kt") - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(TEST_FILE_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ File ${retrieveTestFilesDirectoryPath()}/ProdFile2.kt $errorMessage - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -73,16 +71,14 @@ class TestFileCheckTest { tempFolder.newFile("testfiles/ProdFile2.kt") tempFolder.newFile("testfiles/ProdFile3.kt") - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(TEST_FILE_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ File ${retrieveTestFilesDirectoryPath()}/ProdFile2.kt does not have a corresponding test file. File ${retrieveTestFilesDirectoryPath()}/ProdFile3.kt does not have a corresponding test file. - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -95,16 +91,14 @@ class TestFileCheckTest { tempFolder.newFile("testfiles/ProdFile3.kt") tempFolder.newFile("testfiles/ProdFile2.kt") - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(TEST_FILE_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ File ${retrieveTestFilesDirectoryPath()}/ProdFile2.kt does not have a corresponding test file. File ${retrieveTestFilesDirectoryPath()}/ProdFile3.kt does not have a corresponding test file. - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) diff --git a/scripts/src/javatests/org/oppia/android/scripts/testing/TestBazelWorkspaceTest.kt b/scripts/src/javatests/org/oppia/android/scripts/testing/TestBazelWorkspaceTest.kt index 9bec557f4ac..e20b633bbc9 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/testing/TestBazelWorkspaceTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/testing/TestBazelWorkspaceTest.kt @@ -23,9 +23,7 @@ import java.lang.IllegalStateException // Function name: test names are conventionally named with underscores. @Suppress("FunctionName") class TestBazelWorkspaceTest { - @Rule - @JvmField - var tempFolder = TemporaryFolder() + @field:[Rule JvmField] val tempFolder = TemporaryFolder() @Test fun testCreateTestUtility_doesNotImmediatelyCreateAnyFiles() { @@ -37,7 +35,7 @@ class TestBazelWorkspaceTest { } @Test - fun testInitEmptyWorkspace_emptyDirectory_createsEmptyWorkspace() { + fun testInitEmptyWorkspace_emptyDirectory_createsEmptyWorkspaceFile() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) testBazelWorkspace.initEmptyWorkspace() @@ -48,6 +46,30 @@ class TestBazelWorkspaceTest { assertThat(workspaceFile.readLines()).isEmpty() } + @Test + fun testInitEmptyWorkspace_emptyDirectory_createsBazelVersionFile() { + val testBazelWorkspace = TestBazelWorkspace(tempFolder) + + testBazelWorkspace.initEmptyWorkspace() + + // A .bazelversion file should now exist with the correct version. + val bazelVersionFile = File(tempFolder.root, ".bazelversion") + assertThat(bazelVersionFile.exists()).isTrue() + assertThat(bazelVersionFile.readText().trim()).isEqualTo("4.0.0") + } + + @Test + fun testInitEmptyWorkspace_emptyDirectory_createsBazelRcFile() { + val testBazelWorkspace = TestBazelWorkspace(tempFolder) + + testBazelWorkspace.initEmptyWorkspace() + + // A .bazelversion file should now exist with the correct flags. + val bazelRcFile = File(tempFolder.root, ".bazelrc") + assertThat(bazelRcFile.exists()).isTrue() + assertThat(bazelRcFile.readText().trim()).isEqualTo("--noenable_bzlmod") + } + @Test fun testInitEmptyWorkspace_fileCreationFails_throwsAssertionError() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) @@ -59,7 +81,7 @@ class TestBazelWorkspaceTest { // Verify that when initializing an empty workspace fails, an AssertionError is thrown (which // would fail for calling tests). - assertThrows(AssertionError::class) { testBazelWorkspace.initEmptyWorkspace() } + assertThrows() { testBazelWorkspace.initEmptyWorkspace() } } @Test @@ -85,11 +107,34 @@ class TestBazelWorkspaceTest { ) val workspaceFile = testBazelWorkspace.workspaceFile - val workspaceContent = workspaceFile.readAsJoinedString() - + val workspaceContent = workspaceFile.readText() assertThat(workspaceContent).contains("com.android.support:support-annotations:28.0.0") } + @Test + fun testSetupWorkspaceForRulesJvmExternal_withOneDep_setsUpBazelVersion() { + val testBazelWorkspace = TestBazelWorkspace(tempFolder) + + testBazelWorkspace.setUpWorkspaceForRulesJvmExternal( + listOf("com.android.support:support-annotations:28.0.0") + ) + + val bazelVersionContent = tempFolder.getBazelVersionFile().readText().trim() + assertThat(bazelVersionContent).isEqualTo("4.0.0") + } + + @Test + fun testSetupWorkspaceForRulesJvmExternal_withOneDep_setsUpBazelRc() { + val testBazelWorkspace = TestBazelWorkspace(tempFolder) + + testBazelWorkspace.setUpWorkspaceForRulesJvmExternal( + listOf("com.android.support:support-annotations:28.0.0") + ) + + val bazelRcContent = tempFolder.getBazelRcFile().readText().trim() + assertThat(bazelRcContent).isEqualTo("--noenable_bzlmod") + } + @Test fun testSetupWorkspaceForRulesJvmExternal_withTwoDeps_containsCorrectList() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) @@ -102,7 +147,7 @@ class TestBazelWorkspaceTest { ) val workspaceFile = testBazelWorkspace.workspaceFile - val workspaceContent = workspaceFile.readAsJoinedString() + val workspaceContent = workspaceFile.readText() assertThat(workspaceContent).contains("com.android.support:support-annotations:28.0.0") assertThat(workspaceContent).contains("io.fabric.sdk.android:fabric:1.4.7") @@ -122,7 +167,7 @@ class TestBazelWorkspaceTest { ) val workspaceFile = testBazelWorkspace.workspaceFile - val workspaceContent = workspaceFile.readAsJoinedString() + val workspaceContent = workspaceFile.readText() assertThat(workspaceContent).contains("com.android.support:support-annotations:28.0.0") assertThat(workspaceContent).contains("io.fabric.sdk.android:fabric:1.4.7") @@ -143,7 +188,7 @@ class TestBazelWorkspaceTest { ) val workspaceFile = testBazelWorkspace.workspaceFile - val workspaceContent = workspaceFile.readAsJoinedString() + val workspaceContent = workspaceFile.readText() assertThat(workspaceContent).contains("com.android.support:support-annotations:28.0.0") assertThat(workspaceContent).doesNotContain("io.fabric.sdk.android:fabric:1.4.7") @@ -158,7 +203,7 @@ class TestBazelWorkspaceTest { ) val workspaceFile = testBazelWorkspace.workspaceFile - val workspaceContent = workspaceFile.readAsJoinedString() + val workspaceContent = workspaceFile.readText() assertThat(workspaceContent).contains( """ @@ -212,10 +257,9 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_reusedTestName_throwsException() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest(testName = "FirstTest") - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", testFile = tempFolder.newFile("FirstTestOther.kt") @@ -228,21 +272,45 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_firstTest_setsUpWorkspace() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", testFile = tempFolder.newFile("FirstTest.kt") ) - val workspaceContent = tempFolder.getWorkspaceFile().readAsJoinedString() + val workspaceContent = tempFolder.getWorkspaceFile().readText() assertThat(workspaceContent).contains("kt_register_toolchains()") } + @Test + fun testAddTestToBuildFile_firstTest_setsUpBazelVersion() { + val testBazelWorkspace = TestBazelWorkspace(tempFolder) + + testBazelWorkspace.addTestToBuildFile( + testName = "FirstTest", + testFile = tempFolder.newFile("FirstTest.kt") + ) + + val bazelVersionContent = tempFolder.getBazelVersionFile().readText().trim() + assertThat(bazelVersionContent).isEqualTo("4.0.0") + } + + @Test + fun testAddTestToBuildFile_firstTest_setsUpBazelRc() { + val testBazelWorkspace = TestBazelWorkspace(tempFolder) + + testBazelWorkspace.addTestToBuildFile( + testName = "FirstTest", + testFile = tempFolder.newFile("FirstTest.kt") + ) + + val bazelRcContent = tempFolder.getBazelRcFile().readText().trim() + assertThat(bazelRcContent).isEqualTo("--noenable_bzlmod") + } + @Test fun testAddTestToBuildFile_firstTest_returnsTestBuildWorkspaceFiles() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() val files = testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", @@ -255,7 +323,6 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_secondTest_doesNotChangeWorkspace() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", testFile = tempFolder.newFile("FirstTest.kt") @@ -275,14 +342,13 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_firstTest_initializesBuildFileOnlyForTests() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", testFile = tempFolder.newFile("FirstTest.kt") ) - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("load\\(.+?kt_jvm_test")).isEqualTo(1) assertThat(buildContent.countMatches("load\\(.+?kt_jvm_library")).isEqualTo(0) } @@ -290,7 +356,6 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_secondTest_doesNotReinitializeBuildFile() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", testFile = tempFolder.newFile("FirstTest.kt") @@ -302,14 +367,13 @@ class TestBazelWorkspaceTest { ) // The load line should only exist once in the file. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("load\\(.+?kt_jvm_test")).isEqualTo(1) } @Test fun testAddTestToBuildFile_unusedTestName_appendsBasicTest() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", @@ -317,7 +381,7 @@ class TestBazelWorkspaceTest { ) // There should be 1 test in the file with empty deps and correct source. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("kt_jvm_test\\(")).isEqualTo(1) assertThat(buildContent).contains("srcs = [\"FirstTest.kt\"]") assertThat(buildContent).contains("deps = []") @@ -326,7 +390,6 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_unusedTestName_withGeneratedDep_configuresBuildFileForLibraries() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", @@ -335,14 +398,13 @@ class TestBazelWorkspaceTest { ) // The build file should now be initialized for libraries. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("load\\(.+?kt_jvm_library")).isEqualTo(1) } @Test fun testAddTestToBuildFile_unusedTestName_withGeneratedDep_appendsLibraryAndTestWithDep() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", @@ -351,7 +413,7 @@ class TestBazelWorkspaceTest { ) // Ensure the test is arranged correctly. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("kt_jvm_test\\(")).isEqualTo(1) assertThat(buildContent).contains("srcs = [\"FirstTest.kt\"]") assertThat(buildContent).contains("deps = [\"//:FirstTestDependency_lib\",]") @@ -363,7 +425,6 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_firstTest_withGeneratedDep_returnsTestDepBuildWorkspaceFiles() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() val files = testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", @@ -378,7 +439,6 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_secondTest_withGeneratedDep_returnsTestDepBuildWorkspaceFiles() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", testFile = tempFolder.newFile("FirstTest.kt") @@ -397,7 +457,6 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_unusedTestName_withExtraDep_appendsTestWithDep() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", @@ -406,7 +465,7 @@ class TestBazelWorkspaceTest { ) // Ensure the test is arranged correctly. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("kt_jvm_test\\(")).isEqualTo(1) assertThat(buildContent).contains("srcs = [\"FirstTest.kt\"]") assertThat(buildContent).contains("deps = [\"//:ExtraDep\",]") @@ -415,7 +474,6 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_unusedTestName_withSubpackage_appendsToSubpackageBuildFile() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() tempFolder.newFolder("subpackage") testBazelWorkspace.addTestToBuildFile( @@ -437,7 +495,6 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_unusedTestName_withSubpackage_returnsNewBuildAndTestFiles() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() tempFolder.newFolder("subpackage") val files = testBazelWorkspace.addTestToBuildFile( @@ -453,7 +510,6 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_unusedTestName_withMultipleSubpackages_returnsNewBuildAndTestFiles() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() val subpackage = "subpackage.first.second" tempFolder.newFolder(*(subpackage.split(".")).toTypedArray()) val files = testBazelWorkspace.addTestToBuildFile( @@ -471,7 +527,6 @@ class TestBazelWorkspaceTest { @Test fun testAddTestToBuildFile_unusedTestName_withGeneratedAndExtraDeps_includesBothInTestDeps() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.addTestToBuildFile( testName = "FirstTest", @@ -481,7 +536,7 @@ class TestBazelWorkspaceTest { ) // Both dependencies should be included in the test's deps. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("kt_jvm_test\\(")).isEqualTo(1) assertThat(buildContent).contains("deps = [\"//:FirstTestDependency_lib\",\"//:ExtraDep\",]") } @@ -489,10 +544,9 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_reusedTestName_throwsException() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest(testName = "FirstTest") - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { testBazelWorkspace.createTest(testName = "FirstTest") } @@ -502,18 +556,36 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_firstTest_setsUpWorkspace() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest(testName = "FirstTest") - val workspaceContent = tempFolder.getWorkspaceFile().readAsJoinedString() + val workspaceContent = tempFolder.getWorkspaceFile().readText() assertThat(workspaceContent).contains("kt_register_toolchains()") } + @Test + fun testCreateTest_firstTest_setsUpBazelVersion() { + val testBazelWorkspace = TestBazelWorkspace(tempFolder) + + testBazelWorkspace.createTest(testName = "FirstTest") + + val bazelVersionContent = tempFolder.getBazelVersionFile().readText().trim() + assertThat(bazelVersionContent).isEqualTo("4.0.0") + } + + @Test + fun testCreateTest_firstTest_setsUpBazelRc() { + val testBazelWorkspace = TestBazelWorkspace(tempFolder) + + testBazelWorkspace.createTest(testName = "FirstTest") + + val bazelRcContent = tempFolder.getBazelRcFile().readText().trim() + assertThat(bazelRcContent).isEqualTo("--noenable_bzlmod") + } + @Test fun testCreateTest_firstTest_returnsTestBuildWorkspaceFiles() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() val files = testBazelWorkspace.createTest(testName = "FirstTest") @@ -523,7 +595,6 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_secondTest_doesNotChangeWorkspace() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest(testName = "FirstTest") val workspaceSize = tempFolder.getWorkspaceFile().length() @@ -537,11 +608,10 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_firstTest_initializesBuildFileOnlyForTests() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest(testName = "FirstTest") - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("load\\(.+?kt_jvm_test")).isEqualTo(1) assertThat(buildContent.countMatches("load\\(.+?kt_jvm_library")).isEqualTo(0) } @@ -549,25 +619,23 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_secondTest_doesNotReinitializeBuildFile() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest(testName = "FirstTest") testBazelWorkspace.createTest(testName = "SecondTest") // The load line should only exist once in the file. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("load\\(.+?kt_jvm_test")).isEqualTo(1) } @Test fun testCreateTest_unusedTestName_appendsBasicTest() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest(testName = "FirstTest") // There should be 1 test in the file with empty deps and correct source. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("kt_jvm_test\\(")).isEqualTo(1) assertThat(buildContent).contains("srcs = [\"FirstTest.kt\"]") assertThat(buildContent).contains("deps = []") @@ -576,7 +644,6 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_unusedTestName_withGeneratedDep_configuresBuildFileForLibraries() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest( testName = "FirstTest", @@ -584,14 +651,13 @@ class TestBazelWorkspaceTest { ) // The build file should now be initialized for libraries. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("load\\(.+?kt_jvm_library")).isEqualTo(1) } @Test fun testCreateTest_unusedTestName_withGeneratedDep_appendsLibraryAndTestWithDep() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest( testName = "FirstTest", @@ -599,7 +665,7 @@ class TestBazelWorkspaceTest { ) // Ensure the test is arranged correctly. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("kt_jvm_test\\(")).isEqualTo(1) assertThat(buildContent).contains("srcs = [\"FirstTest.kt\"]") assertThat(buildContent).contains("deps = [\"//:FirstTestDependency_lib\",]") @@ -611,7 +677,6 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_firstTest_withGeneratedDep_returnsTestDepBuildWorkspaceFiles() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() val files = testBazelWorkspace.createTest( testName = "FirstTest", @@ -625,7 +690,6 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_secondTest_withGeneratedDep_returnsTestDepBuildWorkspaceFiles() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest(testName = "FirstTest") val files = testBazelWorkspace.createTest( @@ -640,12 +704,11 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_unusedTestName_withExtraDep_appendsTestWithDep() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest(testName = "FirstTest", withExtraDependency = "//:ExtraDep") // Ensure the test is arranged correctly. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("kt_jvm_test\\(")).isEqualTo(1) assertThat(buildContent).contains("srcs = [\"FirstTest.kt\"]") assertThat(buildContent).contains("deps = [\"//:ExtraDep\",]") @@ -654,7 +717,6 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_unusedTestName_withSubpackage_appendsToSubpackageBuildFile() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest(testName = "FirstTest", subpackage = "subpackage") @@ -671,7 +733,6 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_unusedTestName_withSubpackage_returnsNewBuildAndTestFiles() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() val files = testBazelWorkspace.createTest(testName = "FirstTest", subpackage = "subpackage") @@ -682,7 +743,6 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_unusedTestName_withMultipleSubpackages_returnsNewBuildAndTestFiles() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() val files = testBazelWorkspace.createTest( testName = "FirstTest", @@ -698,7 +758,6 @@ class TestBazelWorkspaceTest { @Test fun testCreateTest_unusedTestName_withGeneratedAndExtraDeps_includesBothInTestDeps() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createTest( testName = "FirstTest", @@ -707,7 +766,7 @@ class TestBazelWorkspaceTest { ) // Both dependencies should be included in the test's deps. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("kt_jvm_test\\(")).isEqualTo(1) assertThat(buildContent).contains("deps = [\"//:FirstTestDependency_lib\",\"//:ExtraDep\",]") } @@ -715,24 +774,42 @@ class TestBazelWorkspaceTest { @Test fun testCreateLibrary_firstLib_unusedName_configuresWorkspaceAndBuild() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createLibrary(dependencyName = "ExampleDep") - val workspaceContent = tempFolder.getWorkspaceFile().readAsJoinedString() - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val workspaceContent = tempFolder.getWorkspaceFile().readText() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(workspaceContent).contains("kt_register_toolchains()") assertThat(buildContent.countMatches("load\\(.+?kt_jvm_library")).isEqualTo(1) } + @Test + fun testCreateLibrary_firstLib_unusedName_setsUpBazelVersion() { + val testBazelWorkspace = TestBazelWorkspace(tempFolder) + + testBazelWorkspace.createLibrary(dependencyName = "ExampleDep") + + val bazelVersionContent = tempFolder.getBazelVersionFile().readText().trim() + assertThat(bazelVersionContent).isEqualTo("4.0.0") + } + + @Test + fun testCreateLibrary_firstLib_unusedName_setsUpBazelRc() { + val testBazelWorkspace = TestBazelWorkspace(tempFolder) + + testBazelWorkspace.createLibrary(dependencyName = "ExampleDep") + + val bazelRcContent = tempFolder.getBazelRcFile().readText().trim() + assertThat(bazelRcContent).isEqualTo("--noenable_bzlmod") + } + @Test fun testCreateLibrary_firstLib_unusedName_appendsJvmLibraryDeclaration() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createLibrary(dependencyName = "ExampleDep") - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("kt_jvm_library\\(")).isEqualTo(1) assertThat(buildContent).contains("name = \"ExampleDep_lib\"") assertThat(buildContent).contains("srcs = [\"ExampleDep.kt\"]") @@ -741,7 +818,6 @@ class TestBazelWorkspaceTest { @Test fun testCreateLibrary_firstLib_unusedName_returnsBuildLibAndWorkspaceFilesWithTargetName() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() val (targetName, files) = testBazelWorkspace.createLibrary(dependencyName = "ExampleDep") @@ -752,7 +828,6 @@ class TestBazelWorkspaceTest { @Test fun testCreateLibrary_secondLib_unusedName_doesNotChangeWorkspace() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createLibrary(dependencyName = "FirstLib") val workspaceSize = tempFolder.getWorkspaceFile().length() @@ -765,13 +840,12 @@ class TestBazelWorkspaceTest { @Test fun testCreateLibrary_secondLib_unusedName_appendsJvmLibraryDeclaration() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createLibrary(dependencyName = "FirstLib") testBazelWorkspace.createLibrary(dependencyName = "SecondLib") // The kt_jvm_library declaration should only exist once, and both libraries should exist. - val buildContent = testBazelWorkspace.rootBuildFile.readAsJoinedString() + val buildContent = testBazelWorkspace.rootBuildFile.readText() assertThat(buildContent.countMatches("load\\(.+?kt_jvm_library")).isEqualTo(1) assertThat(buildContent.countMatches("kt_jvm_library\\(")).isEqualTo(2) assertThat(buildContent).contains("name = \"FirstLib_lib\"") @@ -783,10 +857,9 @@ class TestBazelWorkspaceTest { @Test fun testCreateLibrary_secondLib_reusedName_throwsException() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - testBazelWorkspace.initEmptyWorkspace() testBazelWorkspace.createLibrary(dependencyName = "FirstLib") - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { testBazelWorkspace.createLibrary(dependencyName = "FirstLib") } @@ -801,7 +874,7 @@ class TestBazelWorkspaceTest { testBazelWorkspace.createTest(testName = "FirstTest") // The workspace should only be configured once (due to the library initialization). - val workspaceContent = tempFolder.getWorkspaceFile().readAsJoinedString() + val workspaceContent = tempFolder.getWorkspaceFile().readText() assertThat(workspaceContent.countMatches("http_archive\\(")).isEqualTo(1) } @@ -813,7 +886,7 @@ class TestBazelWorkspaceTest { testBazelWorkspace.createLibrary(dependencyName = "FirstLib") // The workspace should only be configured once (due to the test initialization). - val workspaceContent = tempFolder.getWorkspaceFile().readAsJoinedString() + val workspaceContent = tempFolder.getWorkspaceFile().readText() assertThat(workspaceContent.countMatches("http_archive\\(")).isEqualTo(1) } @@ -822,7 +895,7 @@ class TestBazelWorkspaceTest { val testBazelWorkspace = TestBazelWorkspace(tempFolder) // A non-existent test file cannot be retrieved. - assertThrows(NoSuchElementException::class) { + assertThrows() { testBazelWorkspace.retrieveTestFile(testName = "Invalid") } } @@ -844,7 +917,7 @@ class TestBazelWorkspaceTest { val testBazelWorkspace = TestBazelWorkspace(tempFolder) // A non-existent library file cannot be retrieved. - assertThrows(NoSuchElementException::class) { + assertThrows() { testBazelWorkspace.retrieveLibraryFile(dependencyName = "Invalid") } } @@ -865,7 +938,7 @@ class TestBazelWorkspaceTest { fun testRetrieveTestDependencyFile_noTest_throwsExceptionWithHelpfulMessage() { val testBazelWorkspace = TestBazelWorkspace(tempFolder) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { testBazelWorkspace.retrieveTestDependencyFile(testName = "Invalid") } @@ -878,7 +951,7 @@ class TestBazelWorkspaceTest { val testBazelWorkspace = TestBazelWorkspace(tempFolder) testBazelWorkspace.createTest("ValidWithoutDep") - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { testBazelWorkspace.retrieveTestDependencyFile(testName = "ValidWithoutDep") } @@ -901,7 +974,9 @@ class TestBazelWorkspaceTest { private fun TemporaryFolder.getWorkspaceFile(): File = File(root, "WORKSPACE") - private fun File.readAsJoinedString(): String = readLines().joinToString(separator = "\n") + private fun TemporaryFolder.getBazelVersionFile(): File = File(root, ".bazelversion") + + private fun TemporaryFolder.getBazelRcFile(): File = File(root, ".bazelrc") private fun File.isRelativeTo(base: File): Boolean = relativeToOrNull(base) != null diff --git a/scripts/src/javatests/org/oppia/android/scripts/testing/TestGitRepositoryTest.kt b/scripts/src/javatests/org/oppia/android/scripts/testing/TestGitRepositoryTest.kt index 59aa28bdc84..453f17da044 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/testing/TestGitRepositoryTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/testing/TestGitRepositoryTest.kt @@ -59,11 +59,11 @@ class TestGitRepositoryTest { fun testSetUser_noGitRepository_throwsAssertionError() { val testGitRepository = TestGitRepository(tempFolder, commandExecutorInterceptor) - val error = assertThrows(AssertionError::class) { + val error = assertThrows() { testGitRepository.setUser(email = "test@oppia.org", name = "Test User") } - assertThat(error).hasMessageThat().contains("not in a git directory") + assertThat(error).hasMessageThat().contains("Not operating in an initialized Git repository.") } @Test @@ -92,11 +92,11 @@ class TestGitRepositoryTest { fun testCheckOutNewBranch_notGitRepository_throwsAssertionError() { val testGitRepository = TestGitRepository(tempFolder, commandExecutorInterceptor) - val error = assertThrows(AssertionError::class) { + val error = assertThrows() { testGitRepository.checkoutNewBranch("develop") } - assertThat(error).hasMessageThat().ignoringCase().contains("not a git repository") + assertThat(error).hasMessageThat().contains("Not operating in an initialized Git repository.") } @Test @@ -116,7 +116,7 @@ class TestGitRepositoryTest { testGitRepository.init() testGitRepository.checkoutNewBranch("develop") - val error = assertThrows(AssertionError::class) { + val error = assertThrows() { testGitRepository.stageFileForCommit(File(tempFolder.root, "fake_file")) } @@ -188,7 +188,7 @@ class TestGitRepositoryTest { testGitRepository.init() testGitRepository.checkoutNewBranch("develop") - val error = assertThrows(AssertionError::class) { + val error = assertThrows() { testGitRepository.stageFilesForCommit( listOf( tempFolder.newFile("new_file1"), @@ -207,7 +207,7 @@ class TestGitRepositoryTest { testGitRepository.init() testGitRepository.checkoutNewBranch("develop") - val error = assertThrows(AssertionError::class) { + val error = assertThrows() { testGitRepository.removeFileForCommit(File(tempFolder.root, "nonexistent_file")) } @@ -221,7 +221,7 @@ class TestGitRepositoryTest { testGitRepository.checkoutNewBranch("develop") tempFolder.newFile("untracked_file") - val error = assertThrows(AssertionError::class) { + val error = assertThrows() { testGitRepository.removeFileForCommit(File(tempFolder.root, "untracked_file")) } @@ -250,7 +250,7 @@ class TestGitRepositoryTest { testGitRepository.init() testGitRepository.checkoutNewBranch("develop") - val error = assertThrows(AssertionError::class) { + val error = assertThrows() { testGitRepository.moveFileForCommit( File(tempFolder.root, "nonexistent_file"), File(tempFolder.root, "new_file") ) @@ -266,7 +266,7 @@ class TestGitRepositoryTest { testGitRepository.checkoutNewBranch("develop") tempFolder.newFile("untracked_file") - val error = assertThrows(AssertionError::class) { + val error = assertThrows() { testGitRepository.moveFileForCommit( File(tempFolder.root, "untracked_file"), File(tempFolder.root, "new_file") ) @@ -304,11 +304,9 @@ class TestGitRepositoryTest { testGitRepository.checkoutNewBranch("develop") testGitRepository.stageFileForCommit(tempFolder.newFile("file_to_be_committed")) - val error = assertThrows(AssertionError::class) { - testGitRepository.commit("Commit new file.") - } + val error = assertThrows { testGitRepository.commit("Commit new file.") } - assertThat(error).hasMessageThat().contains("Please tell me who you are") + assertThat(error).hasMessageThat().contains("User email has not yet been set.") } @Test @@ -318,7 +316,7 @@ class TestGitRepositoryTest { testGitRepository.checkoutNewBranch("develop") testGitRepository.setUser(email = "test@oppia.org", name = "Test User") - val error = assertThrows(AssertionError::class) { + val error = assertThrows() { testGitRepository.commit("Attempting empty commit.", allowEmpty = false) } @@ -357,14 +355,34 @@ class TestGitRepositoryTest { } @Test - fun testStatus_noGitRepository_hasStatusWithError() { + fun testStatus_noGitRepository_doNotCheckForRepository_hasStatusWithError() { val testGitRepository = TestGitRepository(tempFolder, commandExecutorInterceptor) - val status = testGitRepository.status() + val status = testGitRepository.status(checkForGitRepository = false) assertThat(status).ignoringCase().contains("not a git repository") } + @Test + fun testStatus_noGitRepository_checkForRepository_throwsAssertionError() { + val testGitRepository = TestGitRepository(tempFolder, commandExecutorInterceptor) + + val error = assertThrows() { + testGitRepository.status(checkForGitRepository = true) + } + + assertThat(error).hasMessageThat().contains("Not operating in an initialized Git repository.") + } + + @Test + fun testStatus_noGitRepository_defaultCheckForRepository_throwsAssertionError() { + val testGitRepository = TestGitRepository(tempFolder, commandExecutorInterceptor) + + val error = assertThrows() { testGitRepository.status() } + + assertThat(error).hasMessageThat().contains("Not operating in an initialized Git repository.") + } + @Test fun testStatus_onBranch_nothingStaged_statusEmpty() { val testGitRepository = TestGitRepository(tempFolder, commandExecutorInterceptor) diff --git a/scripts/src/javatests/org/oppia/android/scripts/todo/TodoIssueCommentCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/todo/TodoIssueCommentCheckTest.kt index 6c4d5fb8a8c..2d33e0e2a60 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/todo/TodoIssueCommentCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/todo/TodoIssueCommentCheckTest.kt @@ -51,7 +51,7 @@ class TodoIssueCommentCheckTest { latestCommentFile.writeText(latestCommentContent) scriptFailureCommentFile.writeText(scriptFailureCommentContent) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main(tempFolder.root.toString(), "latest_comment.txt", "script_failures.txt") } assertThat(exception).hasMessageThat().contains("NEW COMMENT SHOULD BE POSTED") @@ -80,7 +80,7 @@ class TodoIssueCommentCheckTest { latestCommentFile.writeText(latestCommentContent) scriptFailureCommentFile.writeText(scriptFailureCommentContent) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main(tempFolder.root.toString(), "latest_comment.txt", "script_failures.txt") } assertThat(exception).hasMessageThat().contains("NEW COMMENT SHOULD BE POSTED") @@ -109,7 +109,7 @@ class TodoIssueCommentCheckTest { latestCommentFile.writeText(latestCommentContent) scriptFailureCommentFile.writeText(scriptFailureCommentContent) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main(tempFolder.root.toString(), "latest_comment.txt", "script_failures.txt") } assertThat(exception).hasMessageThat().contains("NEW COMMENT SHOULD BE POSTED") diff --git a/scripts/src/javatests/org/oppia/android/scripts/todo/TodoIssueResolvedCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/todo/TodoIssueResolvedCheckTest.kt index ae273159b92..4880c092ec5 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/todo/TodoIssueResolvedCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/todo/TodoIssueResolvedCheckTest.kt @@ -105,7 +105,7 @@ class TodoIssueResolvedCheckTest { tempFile1.writeText(testContent1) tempFile2.writeText(testContent2) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main(retrieveTestFilesDirectoryPath(), "169877", "abmzuyt") } @@ -149,7 +149,7 @@ class TodoIssueResolvedCheckTest { tempFile2.writeText(testContent2) tempFile3.writeText(testContent3) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main(retrieveTestFilesDirectoryPath(), "169877", "abmzuyt") } @@ -195,7 +195,7 @@ class TodoIssueResolvedCheckTest { tempFile2.writeText(testContent2) tempFile3.writeText(testContent3) - val exception = assertThrows(Exception::class) { + val exception = assertThrows() { main(retrieveTestFilesDirectoryPath(), "169877", "abmzuyt") } val fileContentList = diff --git a/scripts/src/javatests/org/oppia/android/scripts/todo/TodoOpenCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/todo/TodoOpenCheckTest.kt index 23f42c53f2c..6df3902ba9a 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/todo/TodoOpenCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/todo/TodoOpenCheckTest.kt @@ -43,9 +43,7 @@ class TodoOpenCheckTest { @Test fun testTodoCheck_noJsonFilePresent_checkShouldFail() { - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains( "${retrieveTestFilesDirectoryPath()}/open_issues.json: No such file exists" @@ -103,9 +101,7 @@ class TodoOpenCheckTest { """.trimIndent() tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -116,7 +112,7 @@ class TodoOpenCheckTest { - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:3 - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:4 - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:5 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -141,9 +137,7 @@ class TodoOpenCheckTest { """.trimIndent() tempFile.writeText(testContent) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -152,7 +146,7 @@ class TodoOpenCheckTest { - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:1 - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:2 - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:5 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -185,9 +179,7 @@ class TodoOpenCheckTest { tempFile1.writeText(testContent1) tempFile2.writeText(testContent2) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -195,11 +187,11 @@ class TodoOpenCheckTest { TODOs not in correct format: - ${retrieveTestFilesDirectoryPath()}/TempFile1.kt:2 - ${retrieveTestFilesDirectoryPath()}/TempFile2.kt:1 - + TODOs not corresponding to open issues on GitHub: - ${retrieveTestFilesDirectoryPath()}/TempFile1.kt:1 - ${retrieveTestFilesDirectoryPath()}/TempFile2.kt:3 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -239,9 +231,7 @@ class TodoOpenCheckTest { tempFile2.writeText(testContent2) tempFile3.writeText(testContent3) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -250,11 +240,11 @@ class TodoOpenCheckTest { - ${retrieveTestFilesDirectoryPath()}/Activity.kt:2 - ${retrieveTestFilesDirectoryPath()}/Fragment.kt:1 - ${retrieveTestFilesDirectoryPath()}/Presenter.kt:2 - + TODOs not corresponding to open issues on GitHub: - ${retrieveTestFilesDirectoryPath()}/Fragment.kt:3 - ${retrieveTestFilesDirectoryPath()}/Presenter.kt:1 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -340,9 +330,7 @@ class TodoOpenCheckTest { }.build() exemptions.writeTo(exemptionFile.outputStream()) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -391,9 +379,7 @@ class TodoOpenCheckTest { }.build() exemptions.writeTo(exemptionFile.outputStream()) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -401,13 +387,13 @@ class TodoOpenCheckTest { Redundant exemptions (there are no TODOs corresponding to these lines): - TempFile1.kt:2 Please remove them from scripts/assets/todo_exemptions.textproto - + TODOs not in correct format: - ${retrieveTestFilesDirectoryPath()}/TempFile2.kt:1 - + TODOs not corresponding to open issues on GitHub: - ${retrieveTestFilesDirectoryPath()}/TempFile1.kt:3 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) diff --git a/scripts/src/javatests/org/oppia/android/scripts/xml/StringLanguageTranslationCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/xml/StringLanguageTranslationCheckTest.kt index 00916b400e4..bbe2c2ca818 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/xml/StringLanguageTranslationCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/xml/StringLanguageTranslationCheckTest.kt @@ -65,7 +65,7 @@ class StringLanguageTranslationCheckTest { @Test fun testScript_missingPath_throwsException() { - val exception = assertThrows(IllegalArgumentException::class) { runScript(/* With no path. */) } + val exception = assertThrows() { runScript(/* With no path. */) } assertThat(exception) .hasMessageThat() @@ -74,7 +74,7 @@ class StringLanguageTranslationCheckTest { @Test fun testScript_validPath_noStringFiles_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript(tempFolder.root.absolutePath) } diff --git a/scripts/src/javatests/org/oppia/android/scripts/xml/StringResourceParserTest.kt b/scripts/src/javatests/org/oppia/android/scripts/xml/StringResourceParserTest.kt index 0e1edd3fa30..0bbe198f040 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/xml/StringResourceParserTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/xml/StringResourceParserTest.kt @@ -70,7 +70,7 @@ class StringResourceParserTest { fun testRetrieveBaseStringFile_noStrings_throwsException() { val parser = StringResourceParser(tempFolder.root) - val exception = assertThrows(IllegalStateException::class) { parser.retrieveBaseStringFile() } + val exception = assertThrows() { parser.retrieveBaseStringFile() } assertThat(exception) .hasMessageThat() @@ -88,7 +88,7 @@ class StringResourceParserTest { populateNigerianPidginTranslations() val parser = StringResourceParser(tempFolder.root) - val exception = assertThrows(IllegalStateException::class) { parser.retrieveBaseStringFile() } + val exception = assertThrows() { parser.retrieveBaseStringFile() } assertThat(exception) .hasMessageThat() @@ -103,7 +103,7 @@ class StringResourceParserTest { populateNigerianPidginTranslations() val parser = StringResourceParser(tempFolder.root) - val exception = assertThrows(IllegalStateException::class) { parser.retrieveBaseStringFile() } + val exception = assertThrows() { parser.retrieveBaseStringFile() } assertThat(exception) .hasMessageThat() @@ -118,7 +118,7 @@ class StringResourceParserTest { populateNigerianPidginTranslations() val parser = StringResourceParser(tempFolder.root) - val exception = assertThrows(IllegalStateException::class) { parser.retrieveBaseStringFile() } + val exception = assertThrows() { parser.retrieveBaseStringFile() } assertThat(exception) .hasMessageThat() @@ -133,7 +133,7 @@ class StringResourceParserTest { populateNigerianPidginTranslations() val parser = StringResourceParser(tempFolder.root) - val exception = assertThrows(IllegalStateException::class) { parser.retrieveBaseStringFile() } + val exception = assertThrows() { parser.retrieveBaseStringFile() } assertThat(exception) .hasMessageThat() @@ -148,7 +148,7 @@ class StringResourceParserTest { populateSwahiliTranslations() val parser = StringResourceParser(tempFolder.root) - val exception = assertThrows(IllegalStateException::class) { parser.retrieveBaseStringFile() } + val exception = assertThrows() { parser.retrieveBaseStringFile() } assertThat(exception) .hasMessageThat() @@ -161,7 +161,7 @@ class StringResourceParserTest { populateTranslations(appResources, "values-fake", mapOf()) val parser = StringResourceParser(tempFolder.root) - val exception = assertThrows(IllegalStateException::class) { parser.retrieveBaseStringFile() } + val exception = assertThrows() { parser.retrieveBaseStringFile() } assertThat(exception) .hasMessageThat() @@ -180,7 +180,7 @@ class StringResourceParserTest { populateTranslations(utilityResources, "values", mapOf()) val parser = StringResourceParser(tempFolder.root) - val exception = assertThrows(IllegalStateException::class) { parser.retrieveBaseStringFile() } + val exception = assertThrows() { parser.retrieveBaseStringFile() } // An exception is still thrown since resources outside the app directory are ignored. assertThat(exception) @@ -197,7 +197,7 @@ class StringResourceParserTest { writeTranslationsFile(appResources, "values", "") val parser = StringResourceParser(tempFolder.root) - assertThrows(SAXParseException::class) { parser.retrieveBaseStringFile() } + assertThrows() { parser.retrieveBaseStringFile() } } @Test diff --git a/scripts/src/javatests/org/oppia/android/scripts/xml/StringResourceValidationCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/xml/StringResourceValidationCheckTest.kt index e2152950a99..424a0adb8c3 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/xml/StringResourceValidationCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/xml/StringResourceValidationCheckTest.kt @@ -64,7 +64,7 @@ class StringResourceValidationCheckTest { @Test fun testScript_missingPath_throwsException() { - val exception = assertThrows(IllegalArgumentException::class) { runScript(/* With no path. */) } + val exception = assertThrows() { runScript(/* With no path. */) } assertThat(exception) .hasMessageThat() @@ -73,7 +73,7 @@ class StringResourceValidationCheckTest { @Test fun testScript_validPath_noStringFiles_fails() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { runScript(tempFolder.root.absolutePath) } @@ -105,7 +105,7 @@ class StringResourceValidationCheckTest { populateSwahiliTranslations(mapOf("str1" to SW_STRING_ONE_NEWLINE)) populateNigerianPidginTranslations(mapOf("str1" to PCM_STRING_ONE_NEWLINE)) - val exception = assertThrows(Exception::class) { runScript(tempFolder.root.absolutePath) } + val exception = assertThrows() { runScript(tempFolder.root.absolutePath) } // This output check also inadvertently verifies that the script doesn't care about missing // strings in translated string files. @@ -133,7 +133,7 @@ class StringResourceValidationCheckTest { populateSwahiliTranslations(mapOf("str1" to SW_STRING_ONE_NEWLINE)) populateNigerianPidginTranslations(mapOf("str1" to PCM_STRING_ONE_NEWLINE)) - val exception = assertThrows(Exception::class) { runScript(tempFolder.root.absolutePath) } + val exception = assertThrows() { runScript(tempFolder.root.absolutePath) } // This output check also inadvertently verifies that the script doesn't care about missing // strings in translated string files. @@ -161,7 +161,7 @@ class StringResourceValidationCheckTest { ) populateNigerianPidginTranslations(mapOf("str1" to PCM_STRING_ONE_NEWLINE)) - val exception = assertThrows(Exception::class) { runScript(tempFolder.root.absolutePath) } + val exception = assertThrows() { runScript(tempFolder.root.absolutePath) } // This output check also inadvertently verifies that the script doesn't care about missing // strings in translated string files. @@ -189,7 +189,7 @@ class StringResourceValidationCheckTest { mapOf("str1" to PCM_STRING_NO_NEWLINES, "str2" to PCM_STRING_TWO_NEWLINES) ) - val exception = assertThrows(Exception::class) { runScript(tempFolder.root.absolutePath) } + val exception = assertThrows() { runScript(tempFolder.root.absolutePath) } // This output check also inadvertently verifies that the script doesn't care about missing // strings in translated string files. @@ -223,7 +223,7 @@ class StringResourceValidationCheckTest { mapOf("str1" to PCM_STRING_NO_NEWLINES, "str2" to PCM_STRING_TWO_NEWLINES) ) - val exception = assertThrows(Exception::class) { runScript(tempFolder.root.absolutePath) } + val exception = assertThrows() { runScript(tempFolder.root.absolutePath) } // This output check also inadvertently verifies that the script doesn't care about missing // strings in translated string files. diff --git a/scripts/src/javatests/org/oppia/android/scripts/xml/XmlSyntaxCheckTest.kt b/scripts/src/javatests/org/oppia/android/scripts/xml/XmlSyntaxCheckTest.kt index 2e988cf0663..bc78d44296e 100644 --- a/scripts/src/javatests/org/oppia/android/scripts/xml/XmlSyntaxCheckTest.kt +++ b/scripts/src/javatests/org/oppia/android/scripts/xml/XmlSyntaxCheckTest.kt @@ -73,15 +73,13 @@ class XmlSyntaxCheckTest { val tempFile = tempFolder.newFile("testfiles/TestFile.xml") tempFile.writeText(invalidXml) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(XML_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ ${retrieveTestFilesDirectoryPath()}/TestFile.xml:6:8: $syntaxFailureMessage1 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -112,16 +110,14 @@ class XmlSyntaxCheckTest { tempFile1.writeText(invalidXmlForFile1) tempFile2.writeText(invalidXmlForFile2) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(XML_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = """ ${retrieveTestFilesDirectoryPath()}/TestFile1.xml:4:4: $syntaxFailureMessage2 ${retrieveTestFilesDirectoryPath()}/TestFile2.xml:6:8: $syntaxFailureMessage1 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) @@ -163,9 +159,7 @@ class XmlSyntaxCheckTest { tempFile2.writeText(invalidXmlForFile2) tempFile3.writeText(invalidXmlForFile3) - val exception = assertThrows(Exception::class) { - runScript() - } + val exception = assertThrows() { runScript() } assertThat(exception).hasMessageThat().contains(XML_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR) val failureMessage = @@ -173,7 +167,7 @@ class XmlSyntaxCheckTest { ${retrieveTestFilesDirectoryPath()}/TestFile1.xml:4:4: $syntaxFailureMessage2 ${retrieveTestFilesDirectoryPath()}/TestFile2.xml:6:8: $syntaxFailureMessage1 ${retrieveTestFilesDirectoryPath()}/TestFile3.xml:6:8: $syntaxFailureMessage1 - + $wikiReferenceNote """.trimIndent() assertThat(outContent.toString().trim()).isEqualTo(failureMessage) diff --git a/testing/BUILD.bazel b/testing/BUILD.bazel index 95a90957cfd..6a166ef498e 100644 --- a/testing/BUILD.bazel +++ b/testing/BUILD.bazel @@ -154,10 +154,7 @@ kt_android_library( testonly = True, srcs = ["src/main/java/org/oppia/android/testing/AssertionHelpers.kt"], visibility = ["//visibility:public"], - deps = [ - "//third_party:junit_junit", - "//third_party:org_jetbrains_kotlin_kotlin-reflect", - ], + deps = ["//third_party:junit_junit"], ) filegroup( diff --git a/testing/src/main/java/org/oppia/android/testing/AssertionHelpers.kt b/testing/src/main/java/org/oppia/android/testing/AssertionHelpers.kt index e40d985dad7..7927cd7b79b 100644 --- a/testing/src/main/java/org/oppia/android/testing/AssertionHelpers.kt +++ b/testing/src/main/java/org/oppia/android/testing/AssertionHelpers.kt @@ -1,42 +1,37 @@ package org.oppia.android.testing -import org.junit.Assert.fail -import kotlin.reflect.KClass -import kotlin.reflect.full.cast - /* This file contains generic assertion helpers which are meant to be usable in any test. Not for methods which are specific to a certain test or part of the codebase. */ /** * A replacement to JUnit5's assertThrows() that asserts an execution of the supplied operation - * throws an exception of the supplied type + * throws an exception of the indicated type. * * An example of this might be: * - * val exception = assertThrows(IllegalArgumentException::class) { + * ```kotlin + * val exception = assertThrows() { * stringToRatioParser.parseRatioOrThrow("a:b:c") * } - * assertThat(exception) - * .hasMessageThat() - * .contains("Incorrectly formatted ratio: a:b:c") + * assertThat(exception).hasMessageThat().contains("Incorrectly formatted ratio: a:b:c") + * ``` * - * @param type the type of exception to be thrown * @param operation the operation being run * @return the exception being thrown * @throws AssertionError if the specified exception is not thrown */ -fun assertThrows(type: KClass, operation: () -> Unit): T { - try { - operation() - fail("Expected to encounter exception of $type") - } catch (t: Throwable) { - if (type.isInstance(t)) { - return type.cast(t) +inline fun assertThrows(noinline operation: () -> Unit): T { + return when (val result = try { operation() } catch (t: Throwable) { t }) { + is T -> result + is Throwable -> { + throw AssertionError( + "Expected exception of type: ${T::class.java}, not: ${result::class.java}.", result + ) + } + else -> { + throw AssertionError( + "Expected exception of type: ${T::class.java}. No exception was thrown." + ) } - // Unexpected exception; throw it. - throw t } - throw AssertionError( - "Reached an impossible state when verifying that an exception was thrown." - ) } diff --git a/testing/src/main/java/org/oppia/android/testing/logging/EventLogSubject.kt b/testing/src/main/java/org/oppia/android/testing/logging/EventLogSubject.kt index 5f17e632be0..abec71d8ec0 100644 --- a/testing/src/main/java/org/oppia/android/testing/logging/EventLogSubject.kt +++ b/testing/src/main/java/org/oppia/android/testing/logging/EventLogSubject.kt @@ -97,6 +97,13 @@ class EventLogSubject private constructor( assertThat(actual.priority).isEqualTo(EventLog.Priority.OPTIONAL) } + /** + * Verifies that the [EventLog] under test has no profile ID defined per [EventLog.getProfileId]. + */ + fun hasNoProfileId() { + assertThat(actual.hasProfileId()).isFalse() + } + /** * Returns an [LiteProtoSubject] to verify the under-test [EventLog]'s [EventLog.getProfileId] * field. diff --git a/testing/src/test/java/org/oppia/android/testing/FakeAnalyticsEventLoggerTest.kt b/testing/src/test/java/org/oppia/android/testing/FakeAnalyticsEventLoggerTest.kt index c3d4b258494..b6b3870763a 100644 --- a/testing/src/test/java/org/oppia/android/testing/FakeAnalyticsEventLoggerTest.kt +++ b/testing/src/test/java/org/oppia/android/testing/FakeAnalyticsEventLoggerTest.kt @@ -75,7 +75,7 @@ class FakeAnalyticsEventLoggerTest { @Test fun testFakeEventLogger_logNothing_getMostRecent_returnsFailure() { - assertThrows(NoSuchElementException::class) { fakeAnalyticsEventLogger.getMostRecentEvent() } + assertThrows() { fakeAnalyticsEventLogger.getMostRecentEvent() } } @Test @@ -83,7 +83,7 @@ class FakeAnalyticsEventLoggerTest { analyticsEventLogger.logEvent(eventLog1) fakeAnalyticsEventLogger.clearAllEvents() - val eventException = assertThrows(NoSuchElementException::class) { + val eventException = assertThrows() { fakeAnalyticsEventLogger.getMostRecentEvent() } @@ -141,7 +141,7 @@ class FakeAnalyticsEventLoggerTest { @Test fun testGetOldestEvent_noEventsLogged_throwsException() { - assertThrows(NoSuchElementException::class) { fakeAnalyticsEventLogger.getOldestEvent() } + assertThrows() { fakeAnalyticsEventLogger.getOldestEvent() } } @Test @@ -169,7 +169,7 @@ class FakeAnalyticsEventLoggerTest { analyticsEventLogger.logEvent(eventLog1) fakeAnalyticsEventLogger.clearAllEvents() - assertThrows(NoSuchElementException::class) { fakeAnalyticsEventLogger.getOldestEvent() } + assertThrows() { fakeAnalyticsEventLogger.getOldestEvent() } } @Test @@ -234,7 +234,7 @@ class FakeAnalyticsEventLoggerTest { analyticsEventLogger.logEvent(eventLog2) analyticsEventLogger.logEvent(eventLog1) - assertThrows(IllegalArgumentException::class) { + assertThrows() { fakeAnalyticsEventLogger.getMostRecentEvents(count = -1) } } diff --git a/testing/src/test/java/org/oppia/android/testing/FakeExceptionLoggerTest.kt b/testing/src/test/java/org/oppia/android/testing/FakeExceptionLoggerTest.kt index baa7483b27e..433731da58c 100644 --- a/testing/src/test/java/org/oppia/android/testing/FakeExceptionLoggerTest.kt +++ b/testing/src/test/java/org/oppia/android/testing/FakeExceptionLoggerTest.kt @@ -69,7 +69,7 @@ class FakeExceptionLoggerTest { @Test fun testFakeExceptionLogger_logNothing_getMostRecent_returnsFailure() { - val exception = assertThrows(NoSuchElementException::class) { + val exception = assertThrows() { fakeExceptionLogger.getMostRecentException() } @@ -81,7 +81,7 @@ class FakeExceptionLoggerTest { exceptionLogger.logException(IllegalStateException("Test Exception")) fakeExceptionLogger.clearAllExceptions() - val exception = assertThrows(NoSuchElementException::class) { + val exception = assertThrows() { fakeExceptionLogger.getMostRecentException() } diff --git a/testing/src/test/java/org/oppia/android/testing/FakeFirestoreEventLoggerTest.kt b/testing/src/test/java/org/oppia/android/testing/FakeFirestoreEventLoggerTest.kt index 41ce667b82f..b04b5d13890 100644 --- a/testing/src/test/java/org/oppia/android/testing/FakeFirestoreEventLoggerTest.kt +++ b/testing/src/test/java/org/oppia/android/testing/FakeFirestoreEventLoggerTest.kt @@ -78,7 +78,7 @@ class FakeFirestoreEventLoggerTest { @Test fun testfakeEventLogger_logNothing_getMostRecent_returnsFailure() { - assertThrows(NoSuchElementException::class) { fakeEventLogger.getMostRecentEvent() } + assertThrows() { fakeEventLogger.getMostRecentEvent() } } @Test @@ -86,7 +86,7 @@ class FakeFirestoreEventLoggerTest { eventLogger.uploadEvent(eventLog1) fakeEventLogger.clearAllEvents() - val eventException = assertThrows(NoSuchElementException::class) { + val eventException = assertThrows() { fakeEventLogger.getMostRecentEvent() } @@ -144,7 +144,7 @@ class FakeFirestoreEventLoggerTest { @Test fun testGetOldestEvent_noEventsLogged_throwsException() { - assertThrows(NoSuchElementException::class) { fakeEventLogger.getOldestEvent() } + assertThrows() { fakeEventLogger.getOldestEvent() } } @Test @@ -172,7 +172,7 @@ class FakeFirestoreEventLoggerTest { eventLogger.uploadEvent(eventLog1) fakeEventLogger.clearAllEvents() - assertThrows(NoSuchElementException::class) { fakeEventLogger.getOldestEvent() } + assertThrows() { fakeEventLogger.getOldestEvent() } } @Test @@ -237,7 +237,7 @@ class FakeFirestoreEventLoggerTest { eventLogger.uploadEvent(eventLog2) eventLogger.uploadEvent(eventLog1) - assertThrows(IllegalArgumentException::class) { + assertThrows() { fakeEventLogger.getMostRecentEvents(count = -1) } } diff --git a/testing/src/test/java/org/oppia/android/testing/FakePerformanceMetricsEventLoggerTest.kt b/testing/src/test/java/org/oppia/android/testing/FakePerformanceMetricsEventLoggerTest.kt index 63afc482661..7f7b55a2d17 100644 --- a/testing/src/test/java/org/oppia/android/testing/FakePerformanceMetricsEventLoggerTest.kt +++ b/testing/src/test/java/org/oppia/android/testing/FakePerformanceMetricsEventLoggerTest.kt @@ -78,7 +78,7 @@ class FakePerformanceMetricsEventLoggerTest { @Test fun testFakeMetricsEventLogger_logNothing_getMostRecent_returnsFailure() { - assertThrows(NoSuchElementException::class) { + assertThrows() { fakePerformanceMetricsEventLogger.getMostRecentPerformanceMetricsEvent() } } @@ -88,7 +88,7 @@ class FakePerformanceMetricsEventLoggerTest { performanceMetricsEventLogger.logPerformanceMetric(metricLog1) fakePerformanceMetricsEventLogger.clearAllPerformanceMetricsEvents() - assertThrows(NoSuchElementException::class) { + assertThrows() { fakePerformanceMetricsEventLogger.getMostRecentPerformanceMetricsEvent() } } @@ -148,7 +148,7 @@ class FakePerformanceMetricsEventLoggerTest { @Test fun testGetOldestEvent_noEventsLogged_throwsException() { - assertThrows(NoSuchElementException::class) { + assertThrows() { fakePerformanceMetricsEventLogger.getOldestPerformanceMetricsEvent() } } @@ -178,7 +178,7 @@ class FakePerformanceMetricsEventLoggerTest { performanceMetricsEventLogger.logPerformanceMetric(metricLog1) fakePerformanceMetricsEventLogger.clearAllPerformanceMetricsEvents() - assertThrows(NoSuchElementException::class) { + assertThrows() { fakePerformanceMetricsEventLogger.getOldestPerformanceMetricsEvent() } } @@ -255,7 +255,7 @@ class FakePerformanceMetricsEventLoggerTest { performanceMetricsEventLogger.logPerformanceMetric(metricLog2) performanceMetricsEventLogger.logPerformanceMetric(metricLog1) - assertThrows(IllegalArgumentException::class) { + assertThrows() { fakePerformanceMetricsEventLogger.getMostRecentPerformanceMetricsEvents(count = -1) } } diff --git a/testing/src/test/java/org/oppia/android/testing/data/DataProviderTestMonitorTest.kt b/testing/src/test/java/org/oppia/android/testing/data/DataProviderTestMonitorTest.kt index 9df6e5257d3..aaa3f578c02 100644 --- a/testing/src/test/java/org/oppia/android/testing/data/DataProviderTestMonitorTest.kt +++ b/testing/src/test/java/org/oppia/android/testing/data/DataProviderTestMonitorTest.kt @@ -167,7 +167,7 @@ class DataProviderTestMonitorTest { } val monitor = monitorFactory.createMonitor(dataProvider) - val failure = assertThrows(IllegalStateException::class) { monitor.waitForNextSuccessResult() } + val failure = assertThrows() { monitor.waitForNextSuccessResult() } assertThat(failure).hasMessageThat().contains("Expected next result to be a success") } @@ -179,7 +179,7 @@ class DataProviderTestMonitorTest { } val monitor = monitorFactory.createMonitor(dataProvider) - val failure = assertThrows(IllegalStateException::class) { monitor.waitForNextSuccessResult() } + val failure = assertThrows() { monitor.waitForNextSuccessResult() } assertThat(failure).hasMessageThat().contains("Expected next result to be a success") } @@ -221,7 +221,7 @@ class DataProviderTestMonitorTest { monitor.waitForNextResult() // Wait for the first result. asyncDataSubscriptionManager.notifyChangeAsync("test") - val failure = assertThrows(IllegalStateException::class) { monitor.waitForNextSuccessResult() } + val failure = assertThrows() { monitor.waitForNextSuccessResult() } assertThat(failure).hasMessageThat().contains("Expected next result to be a success") } @@ -251,7 +251,7 @@ class DataProviderTestMonitorTest { val monitor = monitorFactory.createMonitor(dataProvider) // Internal expectation failure since the operation hasn't completed. - assertThrows(AssertionError::class) { monitor.ensureNextResultIsSuccess() } + assertThrows() { monitor.ensureNextResultIsSuccess() } } @Test @@ -275,7 +275,7 @@ class DataProviderTestMonitorTest { val monitor = monitorFactory.createMonitor(dataProvider) testCoroutineDispatchers.runCurrent() // Ensure the subscription is updated. - val failure = assertThrows(IllegalStateException::class) { monitor.ensureNextResultIsSuccess() } + val failure = assertThrows() { monitor.ensureNextResultIsSuccess() } assertThat(failure).hasMessageThat().contains("Expected next result to be a success") } @@ -288,26 +288,11 @@ class DataProviderTestMonitorTest { val monitor = monitorFactory.createMonitor(dataProvider) testCoroutineDispatchers.runCurrent() // Ensure the subscription is updated. - val failure = assertThrows(IllegalStateException::class) { monitor.ensureNextResultIsSuccess() } + val failure = assertThrows() { monitor.ensureNextResultIsSuccess() } assertThat(failure).hasMessageThat().contains("Expected next result to be a success") } - @Test - fun testEnsureNextResultIsSuccess_failureThenSuccess_notified_throwsException() { - val dataProvider = - createDataProviderWithResultsQueue( - "test", AsyncResult.Failure(Exception("Failure")), AsyncResult.Success("str value") - ) - val monitor = monitorFactory.createMonitor(dataProvider) - monitor.waitForNextResult() // Wait for the first result. - - asyncDataSubscriptionManager.notifyChangeAsync("test") - testCoroutineDispatchers.runCurrent() // Ensure the subscription is updated. - // Internal expectation failure since the operation hasn't completed. - assertThrows(AssertionError::class) { monitor.ensureNextResultIsSuccess() } - } - @Test fun testEnsureNextResultIsSuccess_failureThenSuccess_notified_wait_returnsLatest() { val dataProvider = @@ -335,7 +320,7 @@ class DataProviderTestMonitorTest { asyncDataSubscriptionManager.notifyChangeAsync("test") testCoroutineDispatchers.runCurrent() // Ensure the subscription is updated. - val failure = assertThrows(IllegalStateException::class) { monitor.ensureNextResultIsSuccess() } + val failure = assertThrows() { monitor.ensureNextResultIsSuccess() } assertThat(failure).hasMessageThat().contains("Expected next result to be a success") } @@ -365,7 +350,7 @@ class DataProviderTestMonitorTest { } val monitor = monitorFactory.createMonitor(dataProvider) - val failure = assertThrows(IllegalStateException::class) { monitor.waitForNextFailingResult() } + val failure = assertThrows() { monitor.waitForNextFailingResult() } assertThat(failure).hasMessageThat().contains("Expected next result to be a failure") } @@ -389,7 +374,7 @@ class DataProviderTestMonitorTest { } val monitor = monitorFactory.createMonitor(dataProvider) - val failure = assertThrows(IllegalStateException::class) { monitor.waitForNextFailingResult() } + val failure = assertThrows() { monitor.waitForNextFailingResult() } assertThat(failure).hasMessageThat().contains("Expected next result to be a failure") } @@ -419,7 +404,7 @@ class DataProviderTestMonitorTest { monitor.waitForNextResult() // Wait for the first result. asyncDataSubscriptionManager.notifyChangeAsync("test") - val failure = assertThrows(IllegalStateException::class) { monitor.waitForNextFailingResult() } + val failure = assertThrows() { monitor.waitForNextFailingResult() } assertThat(failure).hasMessageThat().contains("Expected next result to be a failure") } @@ -449,7 +434,7 @@ class DataProviderTestMonitorTest { val monitor = monitorFactory.createMonitor(dataProvider) // Internal expectation failure since the operation hasn't completed. - assertThrows(AssertionError::class) { monitor.ensureNextResultIsSuccess() } + assertThrows() { monitor.ensureNextResultIsSuccess() } } @Test @@ -473,7 +458,7 @@ class DataProviderTestMonitorTest { val monitor = monitorFactory.createMonitor(dataProvider) testCoroutineDispatchers.runCurrent() // Ensure the subscription is updated. - val failure = assertThrows(IllegalStateException::class) { monitor.ensureNextResultIsFailing() } + val failure = assertThrows() { monitor.ensureNextResultIsFailing() } assertThat(failure).hasMessageThat().contains("Expected next result to be a failure") } @@ -486,7 +471,7 @@ class DataProviderTestMonitorTest { val monitor = monitorFactory.createMonitor(dataProvider) testCoroutineDispatchers.runCurrent() // Ensure the subscription is updated. - val failure = assertThrows(IllegalStateException::class) { monitor.ensureNextResultIsFailing() } + val failure = assertThrows() { monitor.ensureNextResultIsFailing() } assertThat(failure).hasMessageThat().contains("Expected next result to be a failure") } @@ -502,7 +487,7 @@ class DataProviderTestMonitorTest { asyncDataSubscriptionManager.notifyChangeAsync("test") // Internal expectation failure since the operation hasn't completed. - assertThrows(AssertionError::class) { monitor.ensureNextResultIsFailing() } + assertThrows() { monitor.ensureNextResultIsFailing() } } @Test @@ -532,7 +517,7 @@ class DataProviderTestMonitorTest { asyncDataSubscriptionManager.notifyChangeAsync("test") testCoroutineDispatchers.runCurrent() // Ensure the subscription is updated. - val failure = assertThrows(IllegalStateException::class) { monitor.ensureNextResultIsFailing() } + val failure = assertThrows() { monitor.ensureNextResultIsFailing() } assertThat(failure).hasMessageThat().contains("Expected next result to be a failure") } @@ -563,7 +548,7 @@ class DataProviderTestMonitorTest { val monitor = monitorFactory.createMonitor(dataProvider) // Verify that the method wsa actually called despite not being expected to have been. - assertThrows(NeverWantedButInvoked::class) { monitor.verifyProviderIsNotUpdated() } + assertThrows() { monitor.verifyProviderIsNotUpdated() } } @Test @@ -574,7 +559,7 @@ class DataProviderTestMonitorTest { val monitor = monitorFactory.createMonitor(dataProvider) // Verify that the method wsa actually called despite not being expected to have been. - assertThrows(NeverWantedButInvoked::class) { monitor.verifyProviderIsNotUpdated() } + assertThrows() { monitor.verifyProviderIsNotUpdated() } } @Test @@ -585,7 +570,7 @@ class DataProviderTestMonitorTest { val monitor = monitorFactory.createMonitor(dataProvider) // Verify that the method wsa actually called despite not being expected to have been. - assertThrows(NeverWantedButInvoked::class) { monitor.verifyProviderIsNotUpdated() } + assertThrows() { monitor.verifyProviderIsNotUpdated() } } @Test @@ -599,7 +584,7 @@ class DataProviderTestMonitorTest { asyncDataSubscriptionManager.notifyChangeAsync("test") // Verify that the method wsa actually called despite not being expected to have been. - assertThrows(NeverWantedButInvoked::class) { monitor.verifyProviderIsNotUpdated() } + assertThrows() { monitor.verifyProviderIsNotUpdated() } } @Test @@ -615,7 +600,7 @@ class DataProviderTestMonitorTest { asyncDataSubscriptionManager.notifyChangeAsync("test") // Verify that the method wsa actually called despite not being expected to have been. - assertThrows(NeverWantedButInvoked::class) { monitor.verifyProviderIsNotUpdated() } + assertThrows() { monitor.verifyProviderIsNotUpdated() } } @Test @@ -630,7 +615,7 @@ class DataProviderTestMonitorTest { asyncDataSubscriptionManager.notifyChangeAsync("test") // Verify that the method wsa actually called despite not being expected to have been. - assertThrows(NeverWantedButInvoked::class) { monitor.verifyProviderIsNotUpdated() } + assertThrows() { monitor.verifyProviderIsNotUpdated() } } @Test @@ -657,7 +642,7 @@ class DataProviderTestMonitorTest { } val failure = - assertThrows(AssertionError::class) { + assertThrows() { monitorFactory.ensureDataProviderExecutes(dataProvider) } @@ -673,7 +658,7 @@ class DataProviderTestMonitorTest { } val failure = - assertThrows(AssertionError::class) { + assertThrows() { monitorFactory.ensureDataProviderExecutes(dataProvider) } @@ -688,7 +673,7 @@ class DataProviderTestMonitorTest { AsyncResult.Failure(Exception("Failure")) } - val failure = assertThrows(IllegalStateException::class) { + val failure = assertThrows() { monitorFactory.waitForNextSuccessfulResult(dataProvider) } @@ -727,7 +712,7 @@ class DataProviderTestMonitorTest { ) monitorFactory.waitForNextSuccessfulResult(dataProvider) - val failure = assertThrows(IllegalStateException::class) { + val failure = assertThrows() { monitorFactory.waitForNextSuccessfulResult(dataProvider) } @@ -770,7 +755,7 @@ class DataProviderTestMonitorTest { } val failure = - assertThrows(IllegalStateException::class) { + assertThrows() { monitorFactory.waitForNextSuccessfulResult(dataProvider) } @@ -783,7 +768,7 @@ class DataProviderTestMonitorTest { AsyncResult.Failure(Exception("Failure")) } - val failure = assertThrows(IllegalStateException::class) { + val failure = assertThrows() { monitorFactory.waitForNextSuccessfulResult(dataProvider) } @@ -822,7 +807,7 @@ class DataProviderTestMonitorTest { ) monitorFactory.waitForNextSuccessfulResult(dataProvider) - val failure = assertThrows(IllegalStateException::class) { + val failure = assertThrows() { monitorFactory.waitForNextSuccessfulResult(dataProvider) } @@ -864,7 +849,7 @@ class DataProviderTestMonitorTest { AsyncResult.Pending() } - val failure = assertThrows(IllegalStateException::class) { + val failure = assertThrows() { monitorFactory.waitForNextFailureResult(dataProvider) } @@ -888,7 +873,7 @@ class DataProviderTestMonitorTest { AsyncResult.Success("str value") } - val failure = assertThrows(IllegalStateException::class) { + val failure = assertThrows() { monitorFactory.waitForNextFailureResult(dataProvider) } @@ -916,7 +901,7 @@ class DataProviderTestMonitorTest { ) monitorFactory.waitForNextFailureResult(dataProvider) - val failure = assertThrows(IllegalStateException::class) { + val failure = assertThrows() { monitorFactory.waitForNextFailureResult(dataProvider) } diff --git a/testing/src/test/java/org/oppia/android/testing/junit/InitializeDefaultLocaleRuleOmissionTest.kt b/testing/src/test/java/org/oppia/android/testing/junit/InitializeDefaultLocaleRuleOmissionTest.kt index 5463cb0e542..8bf8b9194db 100644 --- a/testing/src/test/java/org/oppia/android/testing/junit/InitializeDefaultLocaleRuleOmissionTest.kt +++ b/testing/src/test/java/org/oppia/android/testing/junit/InitializeDefaultLocaleRuleOmissionTest.kt @@ -106,7 +106,7 @@ class InitializeDefaultLocaleRuleOmissionTest { @Test fun testSuite_withoutRule_doesNotInitializeLocaleHandlerWithDefaultContext() { // Not including the rule should result in a helpful exception being thrown. - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { appLanguageLocaleHandler.getDisplayLocale() } assertThat(exception) diff --git a/testing/src/test/java/org/oppia/android/testing/threading/CoroutineExecutorServiceTest.kt b/testing/src/test/java/org/oppia/android/testing/threading/CoroutineExecutorServiceTest.kt index 2e158ee93a1..3af786359ca 100644 --- a/testing/src/test/java/org/oppia/android/testing/threading/CoroutineExecutorServiceTest.kt +++ b/testing/src/test/java/org/oppia/android/testing/threading/CoroutineExecutorServiceTest.kt @@ -136,7 +136,7 @@ class CoroutineExecutorServiceTest { fun testExecute_nullParameter_throwsException() { val executorService = createExecutorService() - assertThrows(NullPointerException::class) { executorService.execute(/* command= */ null) } + assertThrows() { executorService.execute(/* command= */ null) } } @Test @@ -144,7 +144,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() executorService.shutdown() - assertThrows(RejectedExecutionException::class) { executorService.execute(mockRunnable) } + assertThrows() { executorService.execute(mockRunnable) } } @Test @@ -152,7 +152,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() executorService.shutdownNow() - assertThrows(RejectedExecutionException::class) { executorService.execute(mockRunnable) } + assertThrows() { executorService.execute(mockRunnable) } } @Test @@ -179,7 +179,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() val nullRunnable: Runnable? = null - assertThrows(NullPointerException::class) { executorService.submit(nullRunnable) } + assertThrows() { executorService.submit(nullRunnable) } } @Test @@ -187,7 +187,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() executorService.shutdown() - assertThrows(RejectedExecutionException::class) { executorService.submit(mockRunnable) } + assertThrows() { executorService.submit(mockRunnable) } } @Test @@ -195,7 +195,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() executorService.shutdownNow() - assertThrows(RejectedExecutionException::class) { executorService.submit(mockRunnable) } + assertThrows() { executorService.submit(mockRunnable) } } @Test @@ -222,7 +222,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() val nullCallable: Callable? = null - assertThrows(NullPointerException::class) { executorService.submit(nullCallable) } + assertThrows() { executorService.submit(nullCallable) } } @Test @@ -230,7 +230,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() executorService.shutdown() - assertThrows(RejectedExecutionException::class) { executorService.submit(mockCallable) } + assertThrows() { executorService.submit(mockCallable) } } @Test @@ -238,7 +238,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() executorService.shutdownNow() - assertThrows(RejectedExecutionException::class) { executorService.submit(mockCallable) } + assertThrows() { executorService.submit(mockCallable) } } @Test @@ -271,7 +271,7 @@ class CoroutineExecutorServiceTest { testCoroutineDispatchers.runCurrent() assertThat(callableFuture.isDone).isTrue() - val exception = assertThrows(ExecutionException::class) { callableFuture.get() } + val exception = assertThrows() { callableFuture.get() } assertThat(exception).hasCauseThat().isInstanceOf(Exception::class.java) assertThat(exception).hasCauseThat().hasMessageThat().contains("Task failed") } @@ -420,7 +420,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() val nullRunnable: Runnable? = null - assertThrows(NullPointerException::class) { + assertThrows() { executorService.submit(nullRunnable, /* result= */ "Task") } } @@ -430,7 +430,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() executorService.shutdown() - assertThrows(RejectedExecutionException::class) { + assertThrows() { executorService.submit(mockRunnable, /* result= */ "Task") } } @@ -440,7 +440,7 @@ class CoroutineExecutorServiceTest { val executorService = createExecutorService() executorService.shutdownNow() - assertThrows(RejectedExecutionException::class) { + assertThrows() { executorService.submit(mockRunnable, /* result= */ "Task") } } @@ -645,7 +645,7 @@ class CoroutineExecutorServiceTest { // Note that this is not documented in the ExecutorService documentation, it seems necessary // since it doesn't make sense to return false (per the documentation) or block unless a // shutdown request was actually initiated. - assertThrows(IllegalStateException::class) { + assertThrows() { executorService.awaitTermination(/* timeout= */ 1, TimeUnit.SECONDS) } } @@ -746,7 +746,7 @@ class CoroutineExecutorServiceTest { fun testInvokeAll_nullTasks_throwsException() { val executorService = createExecutorService() - assertThrows(NullPointerException::class) { executorService.invokeAll(/* tasks= */ null) } + assertThrows() { executorService.invokeAll(/* tasks= */ null) } } @Test @@ -807,7 +807,7 @@ class CoroutineExecutorServiceTest { val (future1, future2) = deferred.getCompleted() assertThat(future1.isDone).isTrue() assertThat(future2.isDone).isTrue() - assertThrows(ExecutionException::class) { future1.get() } + assertThrows() { future1.get() } assertThat(future2.get()).isEqualTo("Task 2") } @@ -906,7 +906,7 @@ class CoroutineExecutorServiceTest { fun testInvokeAny_nullTasks_throwsException() { val executorService = createExecutorService() - assertThrows(NullPointerException::class) { executorService.invokeAny(/* tasks= */ null) } + assertThrows() { executorService.invokeAny(/* tasks= */ null) } } @Test diff --git a/testing/src/test/java/org/oppia/android/testing/time/FakeOppiaClockTest.kt b/testing/src/test/java/org/oppia/android/testing/time/FakeOppiaClockTest.kt index 5b534916126..aabaee20ebc 100644 --- a/testing/src/test/java/org/oppia/android/testing/time/FakeOppiaClockTest.kt +++ b/testing/src/test/java/org/oppia/android/testing/time/FakeOppiaClockTest.kt @@ -110,7 +110,7 @@ class FakeOppiaClockTest { fun testSetCurrentTimeMs_wallClockMode_throwsException() { fakeOppiaClock.setFakeTimeMode(MODE_WALL_CLOCK_TIME) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { fakeOppiaClock.setCurrentTimeMs(0) } assertThat(exception).hasMessageThat().contains("MODE_FIXED_FAKE_TIME") @@ -128,7 +128,7 @@ class FakeOppiaClockTest { fun testSetCurrentTimeMs_uptimeMillisMode_throwsException() { fakeOppiaClock.setFakeTimeMode(MODE_UPTIME_MILLIS) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { fakeOppiaClock.setCurrentTimeMs(0) } assertThat(exception).hasMessageThat().contains("MODE_FIXED_FAKE_TIME") @@ -226,7 +226,7 @@ class FakeOppiaClockTest { fun testSetCurrentTimeToSameDateTime_wallClockMode_throwsException() { fakeOppiaClock.setFakeTimeMode(MODE_UPTIME_MILLIS) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { fakeOppiaClock.setCurrentTimeToSameDateTime(0) } assertThat(exception).hasMessageThat().contains("MODE_FIXED_FAKE_TIME") @@ -258,7 +258,7 @@ class FakeOppiaClockTest { fun testSetCurrentTimeToSameDateTime_uptimeMillisMode_throwsException() { fakeOppiaClock.setFakeTimeMode(MODE_UPTIME_MILLIS) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { fakeOppiaClock.setCurrentTimeToSameDateTime(0) } assertThat(exception).hasMessageThat().contains("MODE_FIXED_FAKE_TIME") diff --git a/utility/src/test/java/org/oppia/android/util/caching/testing/TestNoOpAssetRepositoryTest.kt b/utility/src/test/java/org/oppia/android/util/caching/testing/TestNoOpAssetRepositoryTest.kt index 2cb1a10f433..ea5346c2490 100644 --- a/utility/src/test/java/org/oppia/android/util/caching/testing/TestNoOpAssetRepositoryTest.kt +++ b/utility/src/test/java/org/oppia/android/util/caching/testing/TestNoOpAssetRepositoryTest.kt @@ -38,7 +38,7 @@ class TestNoOpAssetRepositoryTest { @Test fun testLoadTextFileFromLocalAssets_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { assetRepository.loadTextFileFromLocalAssets("asset.json") } @@ -57,7 +57,7 @@ class TestNoOpAssetRepositoryTest { assetRepository.primeTextFileFromLocalAssets("asset.json") // Priming doesn't do anything, so the exception is still thrown. - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { assetRepository.loadTextFileFromLocalAssets("asset.json") } @@ -66,7 +66,7 @@ class TestNoOpAssetRepositoryTest { @Test fun testLoadProtoFromLocalAssets_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { assetRepository.loadProtoFromLocalAssets("test", TestMessage.getDefaultInstance()) } @@ -107,7 +107,7 @@ class TestNoOpAssetRepositoryTest { @Test fun testLoadRemoteBinaryAsset_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { assetRepository.loadRemoteBinaryAsset("https://example.com/test.pb") } @@ -117,7 +117,7 @@ class TestNoOpAssetRepositoryTest { @Test fun testLoadImageAssetFromLocalAssets_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { assetRepository.loadImageAssetFromLocalAssets("https://example.com/test.png") } @@ -137,7 +137,7 @@ class TestNoOpAssetRepositoryTest { assetRepository.primeRemoteBinaryAsset("https://example.com/test.pb") // Priming doesn't do anything, so the exception is still thrown. - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { assetRepository.loadRemoteBinaryAsset("https://example.com/test.pb") } diff --git a/utility/src/test/java/org/oppia/android/util/data/AsyncDataSubscriptionManagerTest.kt b/utility/src/test/java/org/oppia/android/util/data/AsyncDataSubscriptionManagerTest.kt index 8a9c0b627d9..0926b2fd323 100644 --- a/utility/src/test/java/org/oppia/android/util/data/AsyncDataSubscriptionManagerTest.kt +++ b/utility/src/test/java/org/oppia/android/util/data/AsyncDataSubscriptionManagerTest.kt @@ -258,7 +258,7 @@ class AsyncDataSubscriptionManagerTest { @Test fun testAssociateIds_sameId_throwsException() { - val error = assertThrows(IllegalStateException::class) { + val error = assertThrows() { asyncDataSubscriptionManager.associateIds("same_id", "same_id") } @@ -430,7 +430,7 @@ class AsyncDataSubscriptionManagerTest { asyncDataSubscriptionManager.subscribe("child_id", mockSubscriptionCallback2.toAsyncChange()) asyncDataSubscriptionManager.associateIds("child_id", "parent_id") - val error = assertThrows(IllegalStateException::class) { + val error = assertThrows() { asyncDataSubscriptionManager.associateIds("parent_id", "child_id") } @@ -446,7 +446,7 @@ class AsyncDataSubscriptionManagerTest { asyncDataSubscriptionManager.associateIds("child_id1", "parent_id") asyncDataSubscriptionManager.associateIds("child_id2", "child_id1") - val error = assertThrows(IllegalStateException::class) { + val error = assertThrows() { asyncDataSubscriptionManager.associateIds("parent_id", "child_id1") } diff --git a/utility/src/test/java/org/oppia/android/util/data/InMemoryBlockingCacheTest.kt b/utility/src/test/java/org/oppia/android/util/data/InMemoryBlockingCacheTest.kt index e5e2a69b59b..4dc2cc0fc5a 100644 --- a/utility/src/test/java/org/oppia/android/util/data/InMemoryBlockingCacheTest.kt +++ b/utility/src/test/java/org/oppia/android/util/data/InMemoryBlockingCacheTest.kt @@ -207,7 +207,7 @@ class InMemoryBlockingCacheTest { val deferredRead = cache.readIfPresentAsync() val exception = - assertThrows(IllegalStateException::class) { awaitCompletion(deferredRead) } + assertThrows() { awaitCompletion(deferredRead) } assertThat(exception).hasMessageThat() .contains("Expected to read the cache only after it's been created") } @@ -302,7 +302,7 @@ class InMemoryBlockingCacheTest { // The operation should fail since the method expects the cache to be initialized. val exception = - assertThrows(IllegalStateException::class) { awaitCompletion(deferredUpdate) } + assertThrows() { awaitCompletion(deferredUpdate) } assertThat(exception).hasMessageThat() .contains("Expected to update the cache only after it's been created") } @@ -422,7 +422,7 @@ class InMemoryBlockingCacheTest { // Deleting the cache should result in readIfPresent()'s expectations to fail. val exception = - assertThrows(IllegalStateException::class) { awaitCompletion(deferredRead) } + assertThrows() { awaitCompletion(deferredRead) } assertThat(exception).hasMessageThat() .contains("Expected to read the cache only after it's been created") } @@ -456,7 +456,7 @@ class InMemoryBlockingCacheTest { // The operation should fail since the method expects the cache to be initialized. val exception = - assertThrows(IllegalStateException::class) { awaitCompletion(deferredUpdate) } + assertThrows() { awaitCompletion(deferredUpdate) } assertThat(exception).hasMessageThat() .contains("Expected to update the cache only after it's been created") } diff --git a/utility/src/test/java/org/oppia/android/util/locale/AndroidLocaleFactoryTest.kt b/utility/src/test/java/org/oppia/android/util/locale/AndroidLocaleFactoryTest.kt index c0b45f7e9fd..c009baad4e0 100644 --- a/utility/src/test/java/org/oppia/android/util/locale/AndroidLocaleFactoryTest.kt +++ b/utility/src/test/java/org/oppia/android/util/locale/AndroidLocaleFactoryTest.kt @@ -51,7 +51,7 @@ class AndroidLocaleFactoryTest { @Test fun testCreateLocale_default_throwsException() { - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { androidLocaleFactory.createAndroidLocale(OppiaLocaleContext.getDefaultInstance()) } @@ -513,7 +513,7 @@ class AndroidLocaleFactoryTest { regionDefinition = REGION_INDIA ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { androidLocaleFactory.createAndroidLocale(context) } @@ -566,7 +566,7 @@ class AndroidLocaleFactoryTest { regionDefinition = REGION_INDIA ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { androidLocaleFactory.createAndroidLocale(context) } @@ -945,7 +945,7 @@ class AndroidLocaleFactoryTest { regionDefinition = REGION_INDIA ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { androidLocaleFactory.createAndroidLocale(context) } @@ -998,7 +998,7 @@ class AndroidLocaleFactoryTest { regionDefinition = REGION_INDIA ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { androidLocaleFactory.createAndroidLocale(context) } @@ -1377,7 +1377,7 @@ class AndroidLocaleFactoryTest { regionDefinition = REGION_INDIA ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { androidLocaleFactory.createAndroidLocale(context) } @@ -1430,7 +1430,7 @@ class AndroidLocaleFactoryTest { regionDefinition = REGION_INDIA ) - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { androidLocaleFactory.createAndroidLocale(context) } diff --git a/utility/src/test/java/org/oppia/android/util/locale/DisplayLocaleImplTest.kt b/utility/src/test/java/org/oppia/android/util/locale/DisplayLocaleImplTest.kt index 8786f31948b..e300a47d6fa 100644 --- a/utility/src/test/java/org/oppia/android/util/locale/DisplayLocaleImplTest.kt +++ b/utility/src/test/java/org/oppia/android/util/locale/DisplayLocaleImplTest.kt @@ -354,7 +354,7 @@ class DisplayLocaleImplTest { val impl = createDisplayLocaleImpl(US_ENGLISH_CONTEXT) val resources = context.resources - assertThrows(Resources.NotFoundException::class) { + assertThrows() { impl.run { resources.getStringInLocale(-1) } } } @@ -397,7 +397,7 @@ class DisplayLocaleImplTest { val impl = createDisplayLocaleImpl(US_ENGLISH_CONTEXT) val resources = context.resources - assertThrows(Resources.NotFoundException::class) { + assertThrows() { impl.run { resources.getStringInLocaleWithWrapping(-1) } } } @@ -440,7 +440,7 @@ class DisplayLocaleImplTest { val impl = createDisplayLocaleImpl(US_ENGLISH_CONTEXT) val resources = context.resources - assertThrows(Resources.NotFoundException::class) { + assertThrows() { impl.run { resources.getStringInLocaleWithoutWrapping(-1) } } } @@ -460,7 +460,7 @@ class DisplayLocaleImplTest { val impl = createDisplayLocaleImpl(US_ENGLISH_CONTEXT) val resources = context.resources - assertThrows(Resources.NotFoundException::class) { + assertThrows() { impl.run { resources.getStringArrayInLocale(-1) } } } @@ -496,7 +496,7 @@ class DisplayLocaleImplTest { val impl = createDisplayLocaleImpl(US_ENGLISH_CONTEXT) val resources = context.resources - assertThrows(Resources.NotFoundException::class) { + assertThrows() { impl.run { resources.getQuantityStringInLocale(-1, 0) } } } @@ -535,7 +535,7 @@ class DisplayLocaleImplTest { val impl = createDisplayLocaleImpl(US_ENGLISH_CONTEXT) val resources = context.resources - assertThrows(Resources.NotFoundException::class) { + assertThrows() { impl.run { resources.getQuantityStringInLocaleWithWrapping(-1, 0) } } } @@ -574,7 +574,7 @@ class DisplayLocaleImplTest { val impl = createDisplayLocaleImpl(US_ENGLISH_CONTEXT) val resources = context.resources - assertThrows(Resources.NotFoundException::class) { + assertThrows() { impl.run { resources.getQuantityStringInLocaleWithoutWrapping(-1, 0) } } } @@ -610,7 +610,7 @@ class DisplayLocaleImplTest { val impl = createDisplayLocaleImpl(US_ENGLISH_CONTEXT) val resources = context.resources - assertThrows(Resources.NotFoundException::class) { + assertThrows() { impl.run { resources.getQuantityTextInLocale(-1, 0) } } } diff --git a/utility/src/test/java/org/oppia/android/util/locale/testing/TestOppiaBidiFormatterTest.kt b/utility/src/test/java/org/oppia/android/util/locale/testing/TestOppiaBidiFormatterTest.kt index d56be1961ae..91eefeac704 100644 --- a/utility/src/test/java/org/oppia/android/util/locale/testing/TestOppiaBidiFormatterTest.kt +++ b/utility/src/test/java/org/oppia/android/util/locale/testing/TestOppiaBidiFormatterTest.kt @@ -92,7 +92,7 @@ class TestOppiaBidiFormatterTest { val wrappedStr = formatter.wrapText("test str") // Try to wrap the string again. - val exception = assertThrows(IllegalStateException::class) { formatter.wrapText(wrappedStr) } + val exception = assertThrows() { formatter.wrapText(wrappedStr) } assertThat(exception).hasMessageThat() .contains("Error: encountered string that's already been wrapped: test str") diff --git a/utility/src/test/java/org/oppia/android/util/logging/SyncStatusManagerTestBase.kt b/utility/src/test/java/org/oppia/android/util/logging/SyncStatusManagerTestBase.kt index c19dcfa6d3d..8690cc70ae8 100644 --- a/utility/src/test/java/org/oppia/android/util/logging/SyncStatusManagerTestBase.kt +++ b/utility/src/test/java/org/oppia/android/util/logging/SyncStatusManagerTestBase.kt @@ -56,7 +56,7 @@ abstract class SyncStatusManagerTestBase { fun testInitializeEventLogStore_twice_throwsException() { impl.initializeEventLogStore(logsCacheStore) - val error = assertThrows(IllegalStateException::class) { + val error = assertThrows() { impl.initializeEventLogStore(logsCacheStore) } diff --git a/utility/src/test/java/org/oppia/android/util/logging/firebase/DebugFirestoreEventLoggerImplTest.kt b/utility/src/test/java/org/oppia/android/util/logging/firebase/DebugFirestoreEventLoggerImplTest.kt index 011eb532a09..32d83a0d91c 100644 --- a/utility/src/test/java/org/oppia/android/util/logging/firebase/DebugFirestoreEventLoggerImplTest.kt +++ b/utility/src/test/java/org/oppia/android/util/logging/firebase/DebugFirestoreEventLoggerImplTest.kt @@ -79,7 +79,7 @@ class DebugFirestoreEventLoggerImplTest { @Test fun testDebugFirestoreEventLogger_logNothing_getMostRecent_returnsFailure() { - assertThrows(NoSuchElementException::class) { debugFirestoreLoggerImpl.getMostRecentEvent() } + assertThrows() { debugFirestoreLoggerImpl.getMostRecentEvent() } } @Test @@ -87,7 +87,7 @@ class DebugFirestoreEventLoggerImplTest { eventLogger.uploadEvent(eventLog1) debugFirestoreLoggerImpl.clearAllEvents() - val eventException = assertThrows(NoSuchElementException::class) { + val eventException = assertThrows() { debugFirestoreLoggerImpl.getMostRecentEvent() } diff --git a/utility/src/test/java/org/oppia/android/util/math/FractionExtensionsTest.kt b/utility/src/test/java/org/oppia/android/util/math/FractionExtensionsTest.kt index 3913e7b6dda..f44bc197f98 100644 --- a/utility/src/test/java/org/oppia/android/util/math/FractionExtensionsTest.kt +++ b/utility/src/test/java/org/oppia/android/util/math/FractionExtensionsTest.kt @@ -444,7 +444,7 @@ class FractionExtensionsTest { val zeroDenominatorFraction = Fraction.getDefaultInstance() // Converting to simplest form results in a divide by zero in this case. - assertThrows(ArithmeticException::class) { zeroDenominatorFraction.toSimplestForm() } + assertThrows() { zeroDenominatorFraction.toSimplestForm() } } @Test @@ -518,7 +518,7 @@ class FractionExtensionsTest { val zeroDenominatorFraction = Fraction.getDefaultInstance() // Converting to simplest form results in a divide by zero in this case. - assertThrows(ArithmeticException::class) { zeroDenominatorFraction.toProperForm() } + assertThrows() { zeroDenominatorFraction.toProperForm() } } @Test @@ -1062,7 +1062,7 @@ class FractionExtensionsTest { val lhsFraction = ZERO_FRACTION val rhsFraction = ZERO_FRACTION - assertThrows(Exception::class) { lhsFraction / rhsFraction } + assertThrows() { lhsFraction / rhsFraction } } @Test @@ -1070,7 +1070,7 @@ class FractionExtensionsTest { val lhsFraction = ONE_FRACTION val rhsFraction = ZERO_FRACTION - assertThrows(Exception::class) { lhsFraction / rhsFraction } + assertThrows() { lhsFraction / rhsFraction } } @Test @@ -1078,7 +1078,7 @@ class FractionExtensionsTest { val lhsFraction = TWO_FRACTION val rhsFraction = ZERO_FRACTION - assertThrows(Exception::class) { lhsFraction / rhsFraction } + assertThrows() { lhsFraction / rhsFraction } } @Test diff --git a/utility/src/test/java/org/oppia/android/util/math/FractionParserTest.kt b/utility/src/test/java/org/oppia/android/util/math/FractionParserTest.kt index 6079f7ec92c..81d07c867fa 100644 --- a/utility/src/test/java/org/oppia/android/util/math/FractionParserTest.kt +++ b/utility/src/test/java/org/oppia/android/util/math/FractionParserTest.kt @@ -173,7 +173,7 @@ class FractionParserTest { val parseFraction = fractionParser.parseFraction("7 1/2 4/5") assertThat(parseFraction).isEqualTo(null) - val exception = assertThrows(IllegalArgumentException::class) { + val exception = assertThrows() { fractionParser.parseFractionFromString("7 1/2 4/5") } assertThat(exception).hasMessageThat().contains("Incorrectly formatted fraction: 7 1/2 4/5") @@ -184,7 +184,7 @@ class FractionParserTest { val parseFraction = fractionParser.parseFraction("abc") assertThat(parseFraction).isEqualTo(null) - val exception = assertThrows(IllegalArgumentException::class) { + val exception = assertThrows() { fractionParser.parseFractionFromString("abc") } assertThat(exception).hasMessageThat().contains("Incorrectly formatted fraction: abc") diff --git a/utility/src/test/java/org/oppia/android/util/math/PeekableIteratorTest.kt b/utility/src/test/java/org/oppia/android/util/math/PeekableIteratorTest.kt index 0b6cddc7dbe..e342081aab0 100644 --- a/utility/src/test/java/org/oppia/android/util/math/PeekableIteratorTest.kt +++ b/utility/src/test/java/org/oppia/android/util/math/PeekableIteratorTest.kt @@ -55,7 +55,7 @@ class PeekableIteratorTest { val sequence = sequenceOf() val iterator = sequence.toPeekableIterator() - assertThrows(NoSuchElementException::class) { iterator.next() } + assertThrows() { iterator.next() } } @Test diff --git a/utility/src/test/java/org/oppia/android/util/math/RealExtensionsTest.kt b/utility/src/test/java/org/oppia/android/util/math/RealExtensionsTest.kt index fee8d4e00e7..bfcb4dba53d 100644 --- a/utility/src/test/java/org/oppia/android/util/math/RealExtensionsTest.kt +++ b/utility/src/test/java/org/oppia/android/util/math/RealExtensionsTest.kt @@ -252,7 +252,7 @@ class RealExtensionsTest { fun testIsNegative_default_throwsException() { val defaultReal = Real.getDefaultInstance() - val exception = assertThrows(IllegalStateException::class) { defaultReal.isNegative() } + val exception = assertThrows() { defaultReal.isNegative() } assertThat(exception).hasMessageThat().contains("Invalid real") } @@ -309,7 +309,7 @@ class RealExtensionsTest { val first = Real.getDefaultInstance() val second = TWO_REAL - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { first.isApproximatelyEqualTo(second) } @@ -321,7 +321,7 @@ class RealExtensionsTest { val first = TWO_REAL val second = Real.getDefaultInstance() - val exception = assertThrows(IllegalStateException::class) { + val exception = assertThrows() { first.isApproximatelyEqualTo(second) } @@ -659,7 +659,7 @@ class RealExtensionsTest { fun testIsApproximatelyZero_default_throwsException() { val defaultReal = Real.getDefaultInstance() - val exception = assertThrows(IllegalStateException::class) { defaultReal.isApproximatelyZero() } + val exception = assertThrows() { defaultReal.isApproximatelyZero() } assertThat(exception).hasMessageThat().contains("Invalid real") } @@ -732,7 +732,7 @@ class RealExtensionsTest { fun testToDouble_default_returnsZeroDouble() { val defaultReal = Real.getDefaultInstance() - val exception = assertThrows(IllegalStateException::class) { defaultReal.toDouble() } + val exception = assertThrows() { defaultReal.toDouble() } assertThat(exception).hasMessageThat().contains("Invalid real") } @@ -783,7 +783,7 @@ class RealExtensionsTest { fun testAsWholeNumber_default_throwsException() { val defaultReal = Real.getDefaultInstance() - val exception = assertThrows(IllegalStateException::class) { defaultReal.asWholeNumber() } + val exception = assertThrows() { defaultReal.asWholeNumber() } assertThat(exception).hasMessageThat().contains("Invalid real") } @@ -925,7 +925,7 @@ class RealExtensionsTest { fun testUnaryMinus_default_throwsException() { val defaultReal = Real.getDefaultInstance() - val exception = assertThrows(IllegalStateException::class) { -defaultReal } + val exception = assertThrows() { -defaultReal } assertThat(exception).hasMessageThat().contains("Invalid real") } @@ -1782,7 +1782,7 @@ class RealExtensionsTest { val lhsReal = createIntegerReal(2) val rhsReal = createIntegerReal(0) - assertThrows(ArithmeticException::class) { lhsReal / rhsReal } + assertThrows() { lhsReal / rhsReal } } @Test @@ -1790,7 +1790,7 @@ class RealExtensionsTest { val lhsReal = createIntegerReal(2) val rhsReal = createRationalReal(ZERO_FRACTION) - assertThrows(ArithmeticException::class) { lhsReal / rhsReal } + assertThrows() { lhsReal / rhsReal } } @Test @@ -1808,7 +1808,7 @@ class RealExtensionsTest { val lhsReal = ONE_AND_ONE_HALF_REAL val rhsReal = createIntegerReal(0) - assertThrows(ArithmeticException::class) { lhsReal / rhsReal } + assertThrows() { lhsReal / rhsReal } } @Test @@ -1816,7 +1816,7 @@ class RealExtensionsTest { val lhsReal = ONE_AND_ONE_HALF_REAL val rhsReal = createRationalReal(ZERO_FRACTION) - assertThrows(ArithmeticException::class) { lhsReal / rhsReal } + assertThrows() { lhsReal / rhsReal } } @Test @@ -2188,7 +2188,7 @@ class RealExtensionsTest { fun testSqrt_defaultReal_throwsException() { val real = Real.getDefaultInstance() - val exception = assertThrows(IllegalStateException::class) { sqrt(real) } + val exception = assertThrows() { sqrt(real) } assertThat(exception).hasMessageThat().contains("Invalid real") }