How to use Open class of test package

Best Mockito-kotlin code snippet using test.Open

NavigationDrawerActivityProdTest.kt

Source:NavigationDrawerActivityProdTest.kt Github

copy

Full Screen

...20import androidx.test.espresso.action.ViewActions.swipeUp21import androidx.test.espresso.assertion.ViewAssertions.matches22import androidx.test.espresso.contrib.DrawerActions.close23import androidx.test.espresso.contrib.DrawerMatchers.isClosed24import androidx.test.espresso.contrib.DrawerMatchers.isOpen25import androidx.test.espresso.intent.Intents26import androidx.test.espresso.intent.Intents.intended27import androidx.test.espresso.intent.matcher.IntentMatchers.hasComponent28import androidx.test.espresso.intent.matcher.IntentMatchers.hasExtra29import androidx.test.espresso.matcher.RootMatchers.isDialog30import androidx.test.espresso.matcher.ViewMatchers.hasTextColor31import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom32import androidx.test.espresso.matcher.ViewMatchers.isCompletelyDisplayed33import androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA34import androidx.test.espresso.matcher.ViewMatchers.isDisplayed35import androidx.test.espresso.matcher.ViewMatchers.isRoot36import androidx.test.espresso.matcher.ViewMatchers.withContentDescription37import androidx.test.espresso.matcher.ViewMatchers.withId38import androidx.test.espresso.matcher.ViewMatchers.withText39import androidx.test.espresso.util.HumanReadables40import androidx.test.ext.junit.runners.AndroidJUnit441import com.google.android.material.navigation.NavigationView42import dagger.Component43import org.hamcrest.Description44import org.hamcrest.Matchers.allOf45import org.hamcrest.Matchers.not46import org.hamcrest.TypeSafeMatcher47import org.junit.After48import org.junit.Before49import org.junit.Ignore50import org.junit.Rule51import org.junit.Test52import org.junit.runner.RunWith53import org.oppia.android.R54import org.oppia.android.app.activity.ActivityComponent55import org.oppia.android.app.activity.ActivityComponentFactory56import org.oppia.android.app.administratorcontrols.AdministratorControlsActivity57import org.oppia.android.app.application.ApplicationComponent58import org.oppia.android.app.application.ApplicationInjector59import org.oppia.android.app.application.ApplicationInjectorProvider60import org.oppia.android.app.application.ApplicationModule61import org.oppia.android.app.application.ApplicationStartupListenerModule62import org.oppia.android.app.devoptions.DeveloperOptionsModule63import org.oppia.android.app.drawer.NavigationDrawerItem64import org.oppia.android.app.help.HelpActivity65import org.oppia.android.app.model.ProfileId66import org.oppia.android.app.mydownloads.MyDownloadsActivity67import org.oppia.android.app.player.state.itemviewmodel.SplitScreenInteractionModule68import org.oppia.android.app.profile.ProfileChooserActivity69import org.oppia.android.app.profileprogress.ProfileProgressActivity70import org.oppia.android.app.shim.ViewBindingShimModule71import org.oppia.android.app.topic.PracticeTabModule72import org.oppia.android.app.translation.testing.ActivityRecreatorTestModule73import org.oppia.android.app.utility.OrientationChangeAction.Companion.orientationLandscape74import org.oppia.android.data.backends.gae.NetworkConfigProdModule75import org.oppia.android.data.backends.gae.NetworkModule76import org.oppia.android.domain.classify.InteractionsModule77import org.oppia.android.domain.classify.rules.algebraicexpressioninput.AlgebraicExpressionInputModule78import org.oppia.android.domain.classify.rules.continueinteraction.ContinueModule79import org.oppia.android.domain.classify.rules.dragAndDropSortInput.DragDropSortInputModule80import org.oppia.android.domain.classify.rules.fractioninput.FractionInputModule81import org.oppia.android.domain.classify.rules.imageClickInput.ImageClickInputModule82import org.oppia.android.domain.classify.rules.itemselectioninput.ItemSelectionInputModule83import org.oppia.android.domain.classify.rules.mathequationinput.MathEquationInputModule84import org.oppia.android.domain.classify.rules.multiplechoiceinput.MultipleChoiceInputModule85import org.oppia.android.domain.classify.rules.numberwithunits.NumberWithUnitsRuleModule86import org.oppia.android.domain.classify.rules.numericexpressioninput.NumericExpressionInputModule87import org.oppia.android.domain.classify.rules.numericinput.NumericInputRuleModule88import org.oppia.android.domain.classify.rules.ratioinput.RatioInputModule89import org.oppia.android.domain.classify.rules.textinput.TextInputRuleModule90import org.oppia.android.domain.exploration.lightweightcheckpointing.ExplorationStorageModule91import org.oppia.android.domain.hintsandsolution.HintsAndSolutionConfigModule92import org.oppia.android.domain.hintsandsolution.HintsAndSolutionProdModule93import org.oppia.android.domain.onboarding.ExpirationMetaDataRetrieverModule94import org.oppia.android.domain.oppialogger.LogStorageModule95import org.oppia.android.domain.oppialogger.LoggingIdentifierModule96import org.oppia.android.domain.oppialogger.analytics.ApplicationLifecycleModule97import org.oppia.android.domain.oppialogger.loguploader.LogUploadWorkerModule98import org.oppia.android.domain.platformparameter.PlatformParameterModule99import org.oppia.android.domain.platformparameter.PlatformParameterSingletonModule100import org.oppia.android.domain.question.QuestionModule101import org.oppia.android.domain.topic.PrimeTopicAssetsControllerModule102import org.oppia.android.domain.workmanager.WorkManagerConfigurationModule103import org.oppia.android.testing.OppiaTestRule104import org.oppia.android.testing.RunOn105import org.oppia.android.testing.TestLogReportingModule106import org.oppia.android.testing.TestPlatform107import org.oppia.android.testing.junit.InitializeDefaultLocaleRule108import org.oppia.android.testing.profile.ProfileTestHelper109import org.oppia.android.testing.robolectric.RobolectricModule110import org.oppia.android.testing.story.StoryProgressTestHelper111import org.oppia.android.testing.threading.TestCoroutineDispatchers112import org.oppia.android.testing.threading.TestDispatcherModule113import org.oppia.android.testing.time.FakeOppiaClock114import org.oppia.android.testing.time.FakeOppiaClockModule115import org.oppia.android.util.accessibility.AccessibilityTestModule116import org.oppia.android.util.caching.AssetModule117import org.oppia.android.util.caching.testing.CachingTestModule118import org.oppia.android.util.gcsresource.GcsResourceModule119import org.oppia.android.util.locale.LocaleProdModule120import org.oppia.android.util.logging.LoggerModule121import org.oppia.android.util.logging.SyncStatusModule122import org.oppia.android.util.logging.firebase.FirebaseLogUploaderModule123import org.oppia.android.util.networking.NetworkConnectionDebugUtilModule124import org.oppia.android.util.networking.NetworkConnectionUtilDebugModule125import org.oppia.android.util.parser.html.HtmlParserEntityTypeModule126import org.oppia.android.util.parser.image.GlideImageLoaderModule127import org.oppia.android.util.parser.image.ImageParsingModule128import org.robolectric.annotation.Config129import org.robolectric.annotation.LooperMode130import javax.inject.Inject131import javax.inject.Singleton132/** Tests for [NavigationDrawerTestActivity]. */133@RunWith(AndroidJUnit4::class)134@LooperMode(LooperMode.Mode.PAUSED)135@Config(136  application = NavigationDrawerActivityProdTest.TestApplication::class,137  qualifiers = "port-xxhdpi"138)139class NavigationDrawerActivityProdTest {140  @get:Rule141  val initializeDefaultLocaleRule = InitializeDefaultLocaleRule()142  @get:Rule143  val oppiaTestRule = OppiaTestRule()144  @Inject145  lateinit var profileTestHelper: ProfileTestHelper146  @Inject147  lateinit var storyProfileTestHelper: StoryProgressTestHelper148  @Inject149  lateinit var context: Context150  @Inject151  lateinit var testCoroutineDispatchers: TestCoroutineDispatchers152  @Inject153  lateinit var fakeOppiaClock: FakeOppiaClock154  private val internalProfileId = 0155  private val internalProfileId1 = 1156  @Before157  fun setUp() {158    Intents.init()159    setUpTestApplicationComponent()160    profileTestHelper.initializeProfiles()161    testCoroutineDispatchers.registerIdlingResource()162    fakeOppiaClock.setFakeTimeMode(FakeOppiaClock.FakeTimeMode.MODE_UPTIME_MILLIS)163    storyProfileTestHelper.markCompletedRatiosStory0(164      ProfileId.newBuilder().setInternalId(165        internalProfileId166      ).build(),167      timestampOlderThanOneWeek = false168    )169  }170  @After171  fun tearDown() {172    testCoroutineDispatchers.unregisterIdlingResource()173    Intents.release()174  }175  private fun createNavigationDrawerActivityIntent(internalProfileId: Int): Intent {176    return NavigationDrawerTestActivity.createNavigationDrawerTestActivity(177      context,178      internalProfileId179    )180  }181  private fun setUpTestApplicationComponent() {182    ApplicationProvider.getApplicationContext<TestApplication>().inject(this)183  }184  @Test185  fun testNavDrawer_openNavDrawer_navDrawerIsOpened() {186    launch<NavigationDrawerTestActivity>(187      createNavigationDrawerActivityIntent(internalProfileId)188    ).use {189      it.openNavigationDrawer()190      onView(withId(R.id.home_fragment_placeholder)).check(matches(isCompletelyDisplayed()))191      onView(withId(R.id.home_activity_drawer_layout)).check(matches(isOpen()))192    }193  }194  @Test195  fun testNavDrawer_openNavDrawer_configChange_navDrawerIsDisplayed() {196    launch<NavigationDrawerTestActivity>(197      createNavigationDrawerActivityIntent(internalProfileId)198    ).use {199      it.openNavigationDrawer()200      onView(isRoot()).perform(orientationLandscape())201      onView(withId(R.id.home_activity_drawer_layout)).check(matches(isOpen()))202    }203  }204  @Test205  fun testNavDrawer_withAdminProfile_openNavDrawer_profileNameIsDisplayed() {206    launch<NavigationDrawerTestActivity>(207      createNavigationDrawerActivityIntent(internalProfileId)208    ).use {209      testCoroutineDispatchers.runCurrent()210      it.openNavigationDrawer()211      onView(212        allOf(213          withId(R.id.nav_header_profile_name),214          isDescendantOfA(withId(R.id.header_linear_layout))215        )...

Full Screen

Full Screen

AnalyticsControllerTest.kt

Source:AnalyticsControllerTest.kt Github

copy

Full Screen

...72  @Test73  fun testController_logImportantEvent_withQuestionContext_checkLogsEvent() {74    analyticsController.logImportantEvent(75      TEST_TIMESTAMP,76      oppiaLogger.createOpenQuestionPlayerContext(77        TEST_QUESTION_ID,78        listOf(79          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID80        )81      )82    )83    val eventLog = fakeEventLogger.getMostRecentEvent()84    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)85    assertThat(eventLog).isEssentialPriority()86    assertThat(eventLog).hasOpenQuestionPlayerContext()87  }88  @Test89  fun testController_logImportantEvent_withExplorationContext_checkLogsEvent() {90    analyticsController.logImportantEvent(91      TEST_TIMESTAMP,92      oppiaLogger.createOpenExplorationActivityContext(93        TEST_TOPIC_ID,94        TEST_STORY_ID,95        TEST_EXPLORATION_ID96      )97    )98    val eventLog = fakeEventLogger.getMostRecentEvent()99    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)100    assertThat(eventLog).isEssentialPriority()101    assertThat(eventLog).hasOpenExplorationActivityContext()102  }103  @Test104  fun testController_logImportantEvent_withOpenInfoTabContext_checkLogsEvent() {105    analyticsController.logImportantEvent(106      TEST_TIMESTAMP, oppiaLogger.createOpenInfoTabContext(TEST_TOPIC_ID)107    )108    val eventLog = fakeEventLogger.getMostRecentEvent()109    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)110    assertThat(eventLog).isEssentialPriority()111    assertThat(eventLog).hasOpenInfoTabContext()112  }113  @Test114  fun testController_logImportantEvent_withOpenPracticeTabContext_checkLogsEvent() {115    analyticsController.logImportantEvent(116      TEST_TIMESTAMP, oppiaLogger.createOpenPracticeTabContext(TEST_TOPIC_ID)117    )118    val eventLog = fakeEventLogger.getMostRecentEvent()119    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)120    assertThat(eventLog).isEssentialPriority()121    assertThat(eventLog).hasOpenPracticeTabContext()122  }123  @Test124  fun testController_logImportantEvent_withOpenLessonsTabContext_checkLogsEvent() {125    analyticsController.logImportantEvent(126      TEST_TIMESTAMP, oppiaLogger.createOpenLessonsTabContext(TEST_TOPIC_ID)127    )128    val eventLog = fakeEventLogger.getMostRecentEvent()129    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)130    assertThat(eventLog).isEssentialPriority()131    assertThat(eventLog).hasOpenLessonsTabContext()132  }133  @Test134  fun testController_logImportantEvent_withOpenRevisionTabContext_checkLogsEvent() {135    analyticsController.logImportantEvent(136      TEST_TIMESTAMP, oppiaLogger.createOpenRevisionTabContext(TEST_TOPIC_ID)137    )138    val eventLog = fakeEventLogger.getMostRecentEvent()139    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)140    assertThat(eventLog).isEssentialPriority()141    assertThat(eventLog).hasOpenRevisionTabContext()142  }143  @Test144  fun testController_logImportantEvent_withStoryContext_checkLogsEvent() {145    analyticsController.logImportantEvent(146      TEST_TIMESTAMP, oppiaLogger.createOpenStoryActivityContext(TEST_TOPIC_ID, TEST_STORY_ID)147    )148    val eventLog = fakeEventLogger.getMostRecentEvent()149    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)150    assertThat(eventLog).isEssentialPriority()151    assertThat(eventLog).hasOpenStoryActivityContext()152  }153  @Test154  fun testController_logImportantEvent_withRevisionContext_checkLogsEvent() {155    analyticsController.logImportantEvent(156      TEST_TIMESTAMP, oppiaLogger.createOpenRevisionCardContext(TEST_TOPIC_ID, TEST_SUB_TOPIC_ID)157    )158    val eventLog = fakeEventLogger.getMostRecentEvent()159    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)160    assertThat(eventLog).isEssentialPriority()161    assertThat(eventLog).hasOpenRevisionCardContext()162  }163  @Test164  fun testController_logImportantEvent_withConceptCardContext_checkLogsEvent() {165    analyticsController.logImportantEvent(166      TEST_TIMESTAMP, oppiaLogger.createOpenConceptCardContext(TEST_SKILL_ID)167    )168    val eventLog = fakeEventLogger.getMostRecentEvent()169    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)170    assertThat(eventLog).isEssentialPriority()171    assertThat(eventLog).hasOpenConceptCardContext()172  }173  @Test174  fun testController_logLowPriorityEvent_withQuestionContext_checkLogsEvent() {175    analyticsController.logLowPriorityEvent(176      TEST_TIMESTAMP,177      oppiaLogger.createOpenQuestionPlayerContext(178        TEST_QUESTION_ID,179        listOf(180          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID181        )182      )183    )184    val eventLog = fakeEventLogger.getMostRecentEvent()185    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)186    assertThat(eventLog).isOptionalPriority()187    assertThat(eventLog).hasOpenQuestionPlayerContext()188  }189  @Test190  fun testController_logLowPriorityEvent_withExplorationContext_checkLogsEvent() {191    analyticsController.logLowPriorityEvent(192      TEST_TIMESTAMP,193      oppiaLogger.createOpenExplorationActivityContext(194        TEST_TOPIC_ID,195        TEST_STORY_ID,196        TEST_EXPLORATION_ID197      )198    )199    val eventLog = fakeEventLogger.getMostRecentEvent()200    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)201    assertThat(eventLog).isOptionalPriority()202    assertThat(eventLog).hasOpenExplorationActivityContext()203  }204  @Test205  fun testController_logLowPriorityEvent_withOpenInfoTabContext_checkLogsEvent() {206    analyticsController.logLowPriorityEvent(207      TEST_TIMESTAMP, oppiaLogger.createOpenInfoTabContext(TEST_TOPIC_ID)208    )209    val eventLog = fakeEventLogger.getMostRecentEvent()210    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)211    assertThat(eventLog).isOptionalPriority()212    assertThat(eventLog).hasOpenInfoTabContext()213  }214  @Test215  fun testController_logLowPriorityEvent_withOpenPracticeTabContext_checkLogsEvent() {216    analyticsController.logLowPriorityEvent(217      TEST_TIMESTAMP, oppiaLogger.createOpenPracticeTabContext(TEST_TOPIC_ID)218    )219    val eventLog = fakeEventLogger.getMostRecentEvent()220    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)221    assertThat(eventLog).isOptionalPriority()222    assertThat(eventLog).hasOpenPracticeTabContext()223  }224  @Test225  fun testController_logLowPriorityEvent_withOpenLessonsTabContext_checkLogsEvent() {226    analyticsController.logLowPriorityEvent(227      TEST_TIMESTAMP, oppiaLogger.createOpenLessonsTabContext(TEST_TOPIC_ID)228    )229    val eventLog = fakeEventLogger.getMostRecentEvent()230    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)231    assertThat(eventLog).isOptionalPriority()232    assertThat(eventLog).hasOpenLessonsTabContext()233  }234  @Test235  fun testController_logLowPriorityEvent_withOpenRevisionTabContext_checkLogsEvent() {236    analyticsController.logLowPriorityEvent(237      TEST_TIMESTAMP, oppiaLogger.createOpenRevisionTabContext(TEST_TOPIC_ID)238    )239    val eventLog = fakeEventLogger.getMostRecentEvent()240    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)241    assertThat(eventLog).isOptionalPriority()242    assertThat(eventLog).hasOpenRevisionTabContext()243  }244  @Test245  fun testController_logLowPriorityEvent_withStoryContext_checkLogsEvent() {246    analyticsController.logLowPriorityEvent(247      TEST_TIMESTAMP, oppiaLogger.createOpenStoryActivityContext(TEST_TOPIC_ID, TEST_STORY_ID)248    )249    val eventLog = fakeEventLogger.getMostRecentEvent()250    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)251    assertThat(eventLog).isOptionalPriority()252    assertThat(eventLog).hasOpenStoryActivityContext()253  }254  @Test255  fun testController_logLowPriorityEvent_withRevisionContext_checkLogsEvent() {256    analyticsController.logLowPriorityEvent(257      TEST_TIMESTAMP, oppiaLogger.createOpenRevisionCardContext(TEST_TOPIC_ID, TEST_SUB_TOPIC_ID)258    )259    val eventLog = fakeEventLogger.getMostRecentEvent()260    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)261    assertThat(eventLog).isOptionalPriority()262    assertThat(eventLog).hasOpenRevisionCardContext()263  }264  @Test265  fun testController_logLowPriorityEvent_withConceptCardContext_checkLogsEvent() {266    analyticsController.logLowPriorityEvent(267      TEST_TIMESTAMP, oppiaLogger.createOpenConceptCardContext(TEST_SKILL_ID)268    )269    val eventLog = fakeEventLogger.getMostRecentEvent()270    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)271    assertThat(eventLog).isOptionalPriority()272    assertThat(eventLog).hasOpenConceptCardContext()273  }274  // TODO(#3621): Addition of tests tracking behaviour of the controller after uploading of logs to275  //  the remote service.276  @Test277  fun testController_logImportantEvent_withNoNetwork_checkLogsEventToStore() {278    networkConnectionUtil.setCurrentConnectionStatus(NONE)279    analyticsController.logImportantEvent(280      TEST_TIMESTAMP,281      oppiaLogger.createOpenQuestionPlayerContext(282        TEST_QUESTION_ID,283        listOf(284          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID285        )286      )287    )288    val eventLogsProvider = analyticsController.getEventLogStore()289    val eventLog = monitorFactory.waitForNextSuccessfulResult(eventLogsProvider).getEventLog(0)290    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)291    assertThat(eventLog).isEssentialPriority()292    assertThat(eventLog).hasOpenQuestionPlayerContext()293  }294  @Test295  fun testController_logLowPriorityEvent_withNoNetwork_checkLogsEventToStore() {296    networkConnectionUtil.setCurrentConnectionStatus(NONE)297    analyticsController.logLowPriorityEvent(298      TEST_TIMESTAMP,299      oppiaLogger.createOpenQuestionPlayerContext(300        TEST_QUESTION_ID,301        listOf(302          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID303        )304      )305    )306    val eventLogsProvider = analyticsController.getEventLogStore()307    val eventLog = monitorFactory.waitForNextSuccessfulResult(eventLogsProvider).getEventLog(0)308    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)309    assertThat(eventLog).isOptionalPriority()310    assertThat(eventLog).hasOpenQuestionPlayerContext()311  }312  @Test313  fun testController_logImportantEvent_withNoNetwork_exceedLimit_checkEventLogStoreSize() {314    networkConnectionUtil.setCurrentConnectionStatus(NONE)315    logMultipleEvents()316    val eventLogsProvider = analyticsController.getEventLogStore()317    val eventLogs = monitorFactory.waitForNextSuccessfulResult(eventLogsProvider)318    assertThat(eventLogs.eventLogList).hasSize(2)319  }320  @Test321  fun testController_logImportantEvent_logLowPriorityEvent_withNoNetwork_checkOrderinCache() {322    networkConnectionUtil.setCurrentConnectionStatus(NONE)323    analyticsController.logLowPriorityEvent(324      TEST_TIMESTAMP,325      oppiaLogger.createOpenQuestionPlayerContext(326        TEST_QUESTION_ID,327        listOf(328          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID329        )330      )331    )332    analyticsController.logImportantEvent(333      TEST_TIMESTAMP,334      oppiaLogger.createOpenQuestionPlayerContext(335        TEST_QUESTION_ID,336        listOf(337          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID338        )339      )340    )341    val eventLogsProvider = analyticsController.getEventLogStore()342    val eventLogs = monitorFactory.waitForNextSuccessfulResult(eventLogsProvider)343    val firstEventLog = eventLogs.getEventLog(0)344    val secondEventLog = eventLogs.getEventLog(1)345    assertThat(firstEventLog).isOptionalPriority()346    assertThat(secondEventLog).isEssentialPriority()347  }348  @Test349  fun testController_logImportantEvent_switchToNoNetwork_logLowPriorityEvent_checkManagement() {350    analyticsController.logImportantEvent(351      TEST_TIMESTAMP,352      oppiaLogger.createOpenQuestionPlayerContext(353        TEST_QUESTION_ID,354        listOf(355          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID356        )357      )358    )359    networkConnectionUtil.setCurrentConnectionStatus(NONE)360    analyticsController.logLowPriorityEvent(361      TEST_TIMESTAMP,362      oppiaLogger.createOpenQuestionPlayerContext(363        TEST_QUESTION_ID,364        listOf(365          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID366        )367      )368    )369    val logsProvider = analyticsController.getEventLogStore()370    val uploadedEventLog = fakeEventLogger.getMostRecentEvent()371    val cachedEventLog = monitorFactory.waitForNextSuccessfulResult(logsProvider).getEventLog(0)372    assertThat(uploadedEventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)373    assertThat(uploadedEventLog).isEssentialPriority()374    assertThat(uploadedEventLog).hasOpenQuestionPlayerContext()375    assertThat(cachedEventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)376    assertThat(cachedEventLog).isOptionalPriority()377    assertThat(cachedEventLog).hasOpenQuestionPlayerContext()378  }379  @Test380  fun testController_logEvents_exceedLimit_withNoNetwork_checkCorrectEventIsEvicted() {381    networkConnectionUtil.setCurrentConnectionStatus(NONE)382    logMultipleEvents()383    val logsProvider = analyticsController.getEventLogStore()384    val eventLogs = monitorFactory.waitForNextSuccessfulResult(logsProvider)385    val firstEventLog = eventLogs.getEventLog(0)386    val secondEventLog = eventLogs.getEventLog(1)387    assertThat(eventLogs.eventLogList).hasSize(2)388    // In this case, 3 ESSENTIAL and 1 OPTIONAL event was logged. So while pruning, none of the389    // retained logs should have OPTIONAL priority.390    assertThat(firstEventLog).isEssentialPriority()391    assertThat(secondEventLog).isEssentialPriority()392    // If we analyse the implementation of logMultipleEvents(), we can see that record pruning will393    // begin from the logging of the third record. At first, the second event log will be removed as394    // it has OPTIONAL priority and the event logged at the third place will become the event record395    // at the second place in the store. When the forth event gets logged then the pruning will be396    // purely based on timestamp of the event as both event logs have ESSENTIAL priority. As the397    // third event's timestamp was lesser than that of the first event, it will be pruned from the398    // store and the forth event will become the second event in the store.399    assertThat(firstEventLog).hasTimestampThat().isEqualTo(1556094120000)400    assertThat(secondEventLog).hasTimestampThat().isEqualTo(1556094100000)401  }402  @Test403  fun testController_logEvent_withoutNetwork_verifySyncStatusIsUnchanged() {404    networkConnectionUtil.setCurrentConnectionStatus(NONE)405    analyticsController.logImportantEvent(406      1556094120000,407      oppiaLogger.createOpenQuestionPlayerContext(408        TEST_QUESTION_ID,409        listOf(410          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID411        )412      )413    )414    assertThat(fakeSyncStatusManager.getSyncStatuses()).containsExactly(NO_CONNECTIVITY)415  }416  @Test417  fun testController_logEvent_verifySyncStatusChangesToRepresentLoggedEvent() {418    analyticsController.logImportantEvent(419      1556094120000,420      oppiaLogger.createOpenQuestionPlayerContext(421        TEST_QUESTION_ID,422        listOf(423          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID424        )425      )426    )427    val syncStatuses = fakeSyncStatusManager.getSyncStatuses()428    assertThat(syncStatuses).containsExactly(DATA_UPLOADING, DATA_UPLOADED)429  }430  private fun setUpTestApplicationComponent() {431    ApplicationProvider.getApplicationContext<TestApplication>().inject(this)432  }433  private fun logMultipleEvents() {434    analyticsController.logImportantEvent(435      1556094120000,436      oppiaLogger.createOpenQuestionPlayerContext(437        TEST_QUESTION_ID,438        listOf(439          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID440        )441      )442    )443    analyticsController.logLowPriorityEvent(444      1556094110000,445      oppiaLogger.createOpenQuestionPlayerContext(446        TEST_QUESTION_ID,447        listOf(448          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID449        )450      )451    )452    analyticsController.logImportantEvent(453      1556093100000,454      oppiaLogger.createOpenQuestionPlayerContext(455        TEST_QUESTION_ID,456        listOf(457          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID458        )459      )460    )461    analyticsController.logImportantEvent(462      1556094100000,463      oppiaLogger.createOpenQuestionPlayerContext(464        TEST_QUESTION_ID,465        listOf(466          TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID467        )468      )469    )470  }471  // TODO(#89): Move this to a common test application component.472  @Module473  class TestModule {474    @Provides475    @Singleton476    fun provideContext(application: Application): Context {477      return application...

Full Screen

Full Screen

SessionLifecycleTest.kt

Source:SessionLifecycleTest.kt Github

copy

Full Screen

...37    companion object {38        val LOGTAG = "SessionLifecycleTest"39    }40    @Test fun open_interleaved() {41        val session1 = sessionRule.createOpenSession()42        val session2 = sessionRule.createOpenSession()43        session1.close()44        val session3 = sessionRule.createOpenSession()45        session2.close()46        session3.close()47        sessionRule.session.reload()48        sessionRule.session.waitForPageStop()49    }50    @Test fun open_repeated() {51        for (i in 1..5) {52            sessionRule.session.close()53            sessionRule.session.open()54        }55        sessionRule.session.reload()56        sessionRule.session.waitForPageStop()57    }58    @Test fun open_allowCallsWhileClosed() {59        sessionRule.session.close()60        sessionRule.session.loadTestPath(HELLO_HTML_PATH)61        sessionRule.session.reload()62        sessionRule.session.open()63        sessionRule.session.waitForPageStops(2)64    }65    @Test(expected = IllegalStateException::class)66    fun open_throwOnAlreadyOpen() {67        // Throw exception if retrying to open again; otherwise we would leak the old open window.68        sessionRule.session.open()69    }70    @Test fun readFromParcel() {71        val session = sessionRule.createOpenSession()72        session.toParcel { parcel ->73            val newSession = sessionRule.createClosedSession()74            newSession.readFromParcel(parcel)75            assertThat("New session has same settings",76                       newSession.settings, equalTo(session.settings))77            assertThat("New session is open", newSession.isOpen, equalTo(true))78            newSession.close()79            assertThat("New session can be closed", newSession.isOpen, equalTo(false))80        }81        sessionRule.session.reload()82        sessionRule.session.waitForPageStop()83    }84    @Test(expected = IllegalStateException::class)85    fun readFromParcel_throwOnAlreadyOpen() {86        //disable readFromParcel_throwOnAlreadyOpen for frequent failures Bug 153218687        assumeThat(sessionRule.env.isDebugBuild, equalTo(true))88        // Throw exception if retrying to open again; otherwise we would leak the old open window.89        sessionRule.session.toParcel { parcel ->90            sessionRule.createOpenSession().readFromParcel(parcel)91        }92    }93    @Test fun readFromParcel_canLoadPageAfterRead() {94        val newSession = sessionRule.createClosedSession()95        sessionRule.session.toParcel { parcel ->96            newSession.readFromParcel(parcel)97        }98        newSession.reload()99        newSession.waitForPageStop()100    }101    @Test fun readFromParcel_closedSession() {102        val session = sessionRule.createClosedSession()103        session.toParcel { parcel ->104            val newSession = sessionRule.createClosedSession()105            newSession.readFromParcel(parcel)106            assertThat("New session should not be open",107                       newSession.isOpen, equalTo(false))108        }109        sessionRule.session.reload()110        sessionRule.session.waitForPageStop()111    }112    @Test fun readFromParcel_closedSessionAfterParceling() {113        val session = sessionRule.createOpenSession()114        session.toParcel { parcel ->115            assertThat("Session is still open", session.isOpen, equalTo(true))116            session.close()117            val newSession = sessionRule.createClosedSession()118            newSession.readFromParcel(parcel)119            assertThat("New session should not be open",120                       newSession.isOpen, equalTo(false))121        }122        sessionRule.session.reload()123        sessionRule.session.waitForPageStop()124    }125    @Test fun readFromParcel_closedSessionAfterReadParcel() {126        // disable test on opt for frequently failing Bug 1519591127        assumeThat(sessionRule.env.isDebugBuild, equalTo(true))128        val session = sessionRule.createOpenSession()129        session.toParcel { parcel ->130            assertThat("Session is still open", session.isOpen, equalTo(true))131            val newSession = sessionRule.createClosedSession()132            newSession.readFromParcel(parcel)133            assertThat("New session should be open",134                    newSession.isOpen, equalTo(true))135            assertThat("Old session should be closed",136                    session.isOpen, equalTo(false))137        }138        sessionRule.session.reload()139        sessionRule.session.waitForPageStop()140    }141    @Test fun readFromParcel_closeOpenAndLoad() {142        val newSession = sessionRule.createClosedSession()143        sessionRule.session.toParcel { parcel ->144            newSession.readFromParcel(parcel)145        }146        newSession.close()147        newSession.open()148        newSession.reload()149        newSession.waitForPageStop()150    }151    @Test fun readFromParcel_allowCallsBeforeUnparceling() {152        val newSession = sessionRule.createClosedSession()153        newSession.loadTestPath(HELLO_HTML_PATH)154        newSession.reload()155        sessionRule.session.toParcel { parcel ->156            newSession.readFromParcel(parcel)157        }158        newSession.waitForPageStops(2)159    }160    @Test fun readFromParcel_chained() {161        val session1 = sessionRule.createClosedSession()162        val session2 = sessionRule.createClosedSession()163        val session3 = sessionRule.createClosedSession()164        sessionRule.session.toParcel { parcel ->165            session1.readFromParcel(parcel)166        }167        session1.toParcel { parcel ->168            session2.readFromParcel(parcel)169        }170        session2.toParcel { parcel ->171            session3.readFromParcel(parcel)172        }173        session3.reload()174        session3.waitForPageStop()175    }176    @NullDelegate(GeckoSession.NavigationDelegate::class)177    @ClosedSessionAtStart178    @Test fun readFromParcel_moduleUpdated() {179        val session = sessionRule.createOpenSession()180        // Disable navigation notifications on the old, open session.181        assertThat("Old session navigation delegate should be null",182                   session.navigationDelegate, nullValue())183        // Enable navigation notifications on the new, closed session.184        var onLocationCount = 0185        sessionRule.session.navigationDelegate = object : Callbacks.NavigationDelegate {186            override fun onLocationChange(session: GeckoSession, url: String?) {187                onLocationCount++188            }189        }190        // Transferring the old session to the new session should191        // automatically re-enable navigation notifications.192        session.toParcel { parcel ->193            sessionRule.session.readFromParcel(parcel)194        }195        sessionRule.session.reload()196        sessionRule.session.waitForPageStop()197        assertThat("New session should receive navigation notifications",198                   onLocationCount, equalTo(1))199    }200    @WithDevToolsAPI201    @Test fun readFromParcel_focusedInput() {202        // When an input is focused, make sure SessionTextInput is still active after transferring.203        mainSession.loadTestPath(INPUTS_PATH)204        mainSession.waitForPageStop()205        mainSession.evaluateJS("$('#input').focus()")206        mainSession.waitUntilCalled(object : Callbacks.TextInputDelegate {207            @AssertCalled(count = 1)208            override fun restartInput(session: GeckoSession, reason: Int) {209                assertThat("Reason should be correct",210                           reason, equalTo(GeckoSession.TextInputDelegate.RESTART_REASON_FOCUS))211            }212        })213        val newSession = sessionRule.createClosedSession()214        mainSession.toParcel { parcel ->215            newSession.readFromParcel(parcel)216        }217        // We generate an extra focus event during transfer.218        newSession.waitUntilCalled(object : Callbacks.TextInputDelegate {219            @AssertCalled(count = 1)220            override fun restartInput(session: GeckoSession, reason: Int) {221                assertThat("Reason should be correct",222                           reason, equalTo(GeckoSession.TextInputDelegate.RESTART_REASON_FOCUS))223            }224        })225        newSession.evaluateJS("$('#input').blur()")226        newSession.waitUntilCalled(object : Callbacks.TextInputDelegate {227            @AssertCalled(count = 1)228            override fun restartInput(session: GeckoSession, reason: Int) {229                // We generate an extra focus event during transfer.230                assertThat("Reason should be correct",231                           reason, equalTo(GeckoSession.TextInputDelegate.RESTART_REASON_BLUR))232            }233        })234    }235    private fun testRestoreInstanceState(fromSession: GeckoSession?,236                                         ontoSession: GeckoSession?) =237            GeckoView(InstrumentationRegistry.getTargetContext()).apply {238                id = 0239                if (fromSession != null) {240                    setSession(fromSession, sessionRule.runtime)241                }242                val state = SparseArray<Parcelable>()243                saveHierarchyState(state)244                if (ontoSession !== fromSession) {245                    releaseSession()246                    if (ontoSession != null) {247                        setSession(ontoSession, sessionRule.runtime)248                    }249                }250                restoreHierarchyState(state)251            }252    @ClosedSessionAtStart253    @Test fun restoreRuntimeSettings_noSession() {254        val extrasSetting = Bundle(2)255        extrasSetting.putInt("test1", 10)256        extrasSetting.putBoolean("test2", true)257        val settings = GeckoRuntimeSettings.Builder()258                       .javaScriptEnabled(false)259                       .extras(extrasSetting)260                       .build()261        settings.toParcel { parcel ->262            val newSettings = GeckoRuntimeSettings.Builder().build()263            newSettings.readFromParcel(parcel)264            assertThat("Parceled settings must match",265                       newSettings.javaScriptEnabled,266                       equalTo(settings.javaScriptEnabled))267            assertThat("Parceled settings must match",268                       newSettings.extras.getInt("test1"),269                       equalTo(settings.extras.getInt("test1")))270            assertThat("Parceled settings must match",271                       newSettings.extras.getBoolean("test2"),272                       equalTo(settings.extras.getBoolean("test2")))273        }274    }275    @ClosedSessionAtStart276    @Test fun restoreInstanceState_noSessionOntoNoSession() {277        val view = testRestoreInstanceState(null, null)278        assertThat("View session is restored", view.session, nullValue())279    }280    @ClosedSessionAtStart281    @Test fun restoreInstanceState_closedSessionOntoNoSession() {282        val view = testRestoreInstanceState(mainSession, null)283        assertThat("View session is restored", view.session, equalTo(mainSession))284        assertThat("View session is closed", view.session?.isOpen, equalTo(false))285    }286    @Test fun restoreInstanceState_openSessionOntoNoSession() {287        val view = testRestoreInstanceState(mainSession, null)288        assertThat("View session is restored", view.session, equalTo(mainSession))289        assertThat("View session is open", view.session?.isOpen, equalTo(true))290        view.session?.reload()291        sessionRule.waitForPageStop()292    }293    @ClosedSessionAtStart294    @Test fun restoreInstanceState_noSessionOntoClosedSession() {295        val view = testRestoreInstanceState(null, sessionRule.createClosedSession())296        assertThat("View session is not restored", view.session, notNullValue())297        assertThat("View session is closed", view.session?.isOpen, equalTo(false))298    }299    @ClosedSessionAtStart300    @Test fun restoreInstanceState_closedSessionOntoClosedSession() {301        val view = testRestoreInstanceState(mainSession, sessionRule.createClosedSession())302        assertThat("View session is restored", view.session, equalTo(mainSession))303        assertThat("View session is closed", view.session?.isOpen, equalTo(false))304    }305    @Test fun restoreInstanceState_openSessionOntoClosedSession() {306        val view = testRestoreInstanceState(mainSession, sessionRule.createClosedSession())307        assertThat("View session is restored", view.session, equalTo(mainSession))308        assertThat("View session is open", view.session?.isOpen, equalTo(true))309        view.session?.reload()310        sessionRule.waitForPageStop()311    }312    @ClosedSessionAtStart313    @Test fun restoreInstanceState_noSessionOntoOpenSession() {314        val view = testRestoreInstanceState(null, sessionRule.createOpenSession())315        assertThat("View session is not restored", view.session, notNullValue())316        assertThat("View session is open", view.session?.isOpen, equalTo(true))317        view.session?.reload()318        sessionRule.waitForPageStop()319    }320    @ClosedSessionAtStart321    @Test fun restoreInstanceState_closedSessionOntoOpenSession() {322        val view = testRestoreInstanceState(mainSession, sessionRule.createOpenSession())323        assertThat("View session is not restored", view.session, not(equalTo(mainSession)))324        assertThat("View session is open", view.session?.isOpen, equalTo(true))325        view.session?.reload()326        sessionRule.waitForPageStop()327    }328    @Test fun restoreInstanceState_openSessionOntoOpenSession() {329        val view = testRestoreInstanceState(mainSession, sessionRule.createOpenSession())330        assertThat("View session is restored", view.session, equalTo(mainSession))331        assertThat("View session is open", view.session?.isOpen, equalTo(true))332        view.session?.reload()333        sessionRule.waitForPageStop()334    }335    @ClosedSessionAtStart336    @Test fun restoreInstanceState_sameClosedSession() {337        val view = testRestoreInstanceState(mainSession, mainSession)338        assertThat("View session is unchanged", view.session, equalTo(mainSession))339        assertThat("View session is closed", view.session!!.isOpen, equalTo(false))340    }341    @Test fun restoreInstanceState_sameOpenSession() {342        // We should keep the session open when restoring the same open session.343        val view = testRestoreInstanceState(mainSession, mainSession)344        assertThat("View session is unchanged", view.session, equalTo(mainSession))345        assertThat("View session is open", view.session!!.isOpen, equalTo(true))346        view.session!!.reload()347        sessionRule.waitForPageStop()348    }349    @Test fun createFromParcel() {350        val session = sessionRule.createOpenSession()351        session.toParcel { parcel ->352            val newSession = sessionRule.wrapSession(353                    GeckoSession.CREATOR.createFromParcel(parcel))354            assertThat("New session has same settings",355                       newSession.settings, equalTo(session.settings))356            assertThat("New session is open", newSession.isOpen, equalTo(true))357            newSession.close()358            assertThat("New session can be closed", newSession.isOpen, equalTo(false))359        }360        sessionRule.session.reload()361        sessionRule.session.waitForPageStop()362    }363    @Test fun collectClosed() {364        // We can't use a normal scoped function like `run` because365        // those are inlined, which leaves a local reference.366        fun createSession(): QueuedWeakReference<GeckoSession> {367            return QueuedWeakReference<GeckoSession>(GeckoSession())368        }369        waitUntilCollected(createSession())370    }371    @Test fun collectAfterClose() {372        fun createSession(): QueuedWeakReference<GeckoSession> {373            val s = GeckoSession()374            s.open(sessionRule.runtime)375            s.close()376            return QueuedWeakReference<GeckoSession>(s)377        }378        waitUntilCollected(createSession())379    }380    @Test fun collectOpen() {381        fun createSession(): QueuedWeakReference<GeckoSession> {382            val s = GeckoSession()383            s.open(sessionRule.runtime)384            return QueuedWeakReference<GeckoSession>(s)385        }386        waitUntilCollected(createSession())387    }388    private fun dumpHprof() {389        try {390            val dest = File(InstrumentationRegistry.getTargetContext()391                    .filesDir.parent, "dump.hprof").absolutePath392            Debug.dumpHprofData(dest)393            Log.d(LOGTAG, "Dumped hprof to $dest")394        } catch (e: IOException) {...

Full Screen

Full Screen

OppiaLoggerTest.kt

Source:OppiaLoggerTest.kt Github

copy

Full Screen

...97    setUpTestApplicationComponent()98    ShadowLog.reset()99  }100  @Test101  fun testLogImportantEvent_forOpenHomeEvent_logsEssentialEventWithCurrentTime() {102    fakeOppiaClock.setFakeTimeMode(FakeOppiaClock.FakeTimeMode.MODE_FIXED_FAKE_TIME)103    fakeOppiaClock.setCurrentTimeMs(TEST_TIMESTAMP)104    val openHomeEventContext = oppiaLogger.createOpenHomeContext()105    oppiaLogger.logImportantEvent(openHomeEventContext)106    val eventLog = fakeEventLogger.getMostRecentEvent()107    assertThat(eventLog).isEssentialPriority()108    assertThat(eventLog).hasTimestampThat().isEqualTo(TEST_TIMESTAMP)109  }110  @Test111  fun testConsoleLogger_logVerboseMessage_checkLoggedMessageIsCorrect() {112    oppiaLogger.v(TEST_VERBOSE_LOG_TAG, TEST_VERBOSE_LOG_MSG)113    val log = ShadowLog.getLogs().last()114    assertThat(log.tag).isEqualTo(TEST_VERBOSE_LOG_TAG)115    assertThat(log.msg).isEqualTo(TEST_VERBOSE_LOG_MSG)116    assertThat(log.type).isEqualTo(Log.VERBOSE)117  }118  @Test119  fun testConsoleLogger_logVerboseMessageWithException_checkLoggedMessageIsCorrect() {120    oppiaLogger.v(TEST_VERBOSE_LOG_TAG, TEST_VERBOSE_LOG_MSG, TEST_VERBOSE_EXCEPTION)121    val log = ShadowLog.getLogs().last()122    assertThat(log.tag).isEqualTo(TEST_VERBOSE_LOG_TAG)123    assertThat(log.msg).contains(TEST_VERBOSE_LOG_MSG)124    assertThat(log.msg).contains(Log.getStackTraceString(TEST_VERBOSE_EXCEPTION))125    assertThat(log.type).isEqualTo(Log.VERBOSE)126  }127  @Test128  fun testConsoleLogger_logDebugMessage_checkLoggedMessageIsCorrect() {129    oppiaLogger.d(TEST_DEBUG_LOG_TAG, TEST_DEBUG_LOG_MSG)130    val log = ShadowLog.getLogs().last()131    assertThat(log.tag).isEqualTo(TEST_DEBUG_LOG_TAG)132    assertThat(log.msg).isEqualTo(TEST_DEBUG_LOG_MSG)133    assertThat(log.type).isEqualTo(Log.DEBUG)134  }135  @Test136  fun testConsoleLogger_logDebugMessageWithException_checkLoggedMessageIsCorrect() {137    oppiaLogger.d(TEST_DEBUG_LOG_TAG, TEST_DEBUG_LOG_MSG, TEST_DEBUG_EXCEPTION)138    val log = ShadowLog.getLogs().last()139    assertThat(log.tag).isEqualTo(TEST_DEBUG_LOG_TAG)140    assertThat(log.msg).contains(TEST_DEBUG_LOG_MSG)141    assertThat(log.msg).contains(Log.getStackTraceString(TEST_DEBUG_EXCEPTION))142    assertThat(log.type).isEqualTo(Log.DEBUG)143  }144  @Test145  fun testConsoleLogger_logInfoMessage_checkLoggedMessageIsCorrect() {146    oppiaLogger.i(TEST_INFO_LOG_TAG, TEST_INFO_LOG_MSG)147    val log = ShadowLog.getLogs().last()148    assertThat(log.tag).isEqualTo(TEST_INFO_LOG_TAG)149    assertThat(log.msg).isEqualTo(TEST_INFO_LOG_MSG)150    assertThat(log.type).isEqualTo(Log.INFO)151  }152  @Test153  fun testConsoleLogger_logInfoMessageWithException_checkLoggedMessageIsCorrect() {154    oppiaLogger.i(TEST_INFO_LOG_TAG, TEST_INFO_LOG_MSG, TEST_INFO_EXCEPTION)155    val log = ShadowLog.getLogs().last()156    assertThat(log.tag).isEqualTo(TEST_INFO_LOG_TAG)157    assertThat(log.msg).contains(TEST_INFO_LOG_MSG)158    assertThat(log.msg).contains(Log.getStackTraceString(TEST_INFO_EXCEPTION))159    assertThat(log.type).isEqualTo(Log.INFO)160  }161  @Test162  fun testConsoleLogger_logWarnMessage_checkLoggedMessageIsCorrect() {163    oppiaLogger.w(TEST_WARN_LOG_TAG, TEST_WARN_LOG_MSG)164    val log = ShadowLog.getLogs().last()165    assertThat(log.tag).isEqualTo(TEST_WARN_LOG_TAG)166    assertThat(log.msg).isEqualTo(TEST_WARN_LOG_MSG)167    assertThat(log.type).isEqualTo(Log.WARN)168  }169  @Test170  fun testConsoleLogger_logWarnMessageWithException_checkLoggedMessageIsCorrect() {171    oppiaLogger.w(TEST_WARN_LOG_TAG, TEST_WARN_LOG_MSG, TEST_WARN_EXCEPTION)172    val log = ShadowLog.getLogs().last()173    assertThat(log.tag).isEqualTo(TEST_WARN_LOG_TAG)174    assertThat(log.msg).contains(TEST_WARN_LOG_MSG)175    assertThat(log.msg).contains(Log.getStackTraceString(TEST_WARN_EXCEPTION))176    assertThat(log.type).isEqualTo(Log.WARN)177  }178  @Test179  fun testConsoleLogger_logErrorMessage_checkLoggedMessageIsCorrect() {180    oppiaLogger.e(TEST_ERROR_LOG_TAG, TEST_ERROR_LOG_MSG)181    val log = ShadowLog.getLogs().last()182    assertThat(log.tag).isEqualTo(TEST_ERROR_LOG_TAG)183    assertThat(log.msg).isEqualTo(TEST_ERROR_LOG_MSG)184    assertThat(log.type).isEqualTo(Log.ERROR)185  }186  @Test187  fun testConsoleLogger_logErrorMessageWithException_checkLoggedMessageIsCorrect() {188    oppiaLogger.e(TEST_ERROR_LOG_TAG, TEST_ERROR_LOG_MSG, TEST_ERROR_EXCEPTION)189    val log = ShadowLog.getLogs().last()190    assertThat(log.tag).isEqualTo(TEST_ERROR_LOG_TAG)191    assertThat(log.msg).contains(TEST_ERROR_LOG_MSG)192    assertThat(log.msg).contains(Log.getStackTraceString(TEST_ERROR_EXCEPTION))193    assertThat(log.type).isEqualTo(Log.ERROR)194  }195  @Test196  fun testController_createOpenExplorationActivityContext_returnsCorrectExplorationContext() {197    val eventContext = oppiaLogger.createOpenExplorationActivityContext(198      TEST_TOPIC_ID,199      TEST_STORY_ID,200      TEST_EXPLORATION_ID201    )202    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_EXPLORATION_ACTIVITY)203    assertThat(eventContext.openExplorationActivity.topicId).matches(TEST_TOPIC_ID)204    assertThat(eventContext.openExplorationActivity.storyId).matches(TEST_STORY_ID)205    assertThat(eventContext.openExplorationActivity.explorationId).matches(TEST_EXPLORATION_ID)206  }207  @Test208  fun testController_createOpenHomeContext_returnsCorrectExplorationContext() {209    val eventContext = oppiaLogger.createOpenHomeContext()210    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_HOME)211  }212  @Test213  fun testController_createOpenProfileChooserContext_returnsCorrectExplorationContext() {214    val eventContext = oppiaLogger.createOpenProfileChooserContext()215    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_PROFILE_CHOOSER)216  }217  @Test218  fun testController_createQuestionContext_returnsCorrectQuestionContext() {219    val eventContext = oppiaLogger.createOpenQuestionPlayerContext(220      TEST_QUESTION_ID,221      listOf(TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID)222    )223    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_QUESTION_PLAYER)224    assertThat(eventContext.openQuestionPlayer.questionId).matches(TEST_QUESTION_ID)225    assertThat(eventContext.openQuestionPlayer.skillIdList)226      .containsAtLeastElementsIn(arrayOf(TEST_SKILL_LIST_ID, TEST_SKILL_LIST_ID))227  }228  @Test229  fun testController_createStoryContext_returnsCorrectStoryContext() {230    val eventContext = oppiaLogger.createOpenStoryActivityContext(231      TEST_TOPIC_ID,232      TEST_STORY_ID233    )234    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_STORY_ACTIVITY)235    assertThat(eventContext.openStoryActivity.topicId).matches(TEST_TOPIC_ID)236    assertThat(eventContext.openStoryActivity.storyId).matches(TEST_STORY_ID)237  }238  @Test239  fun testController_createOpenInfoTabContext_returnsCorrectTopicContext() {240    val eventContext = oppiaLogger.createOpenInfoTabContext(TEST_TOPIC_ID)241    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_INFO_TAB)242    assertThat(eventContext.openInfoTab.topicId).matches(TEST_TOPIC_ID)243  }244  @Test245  fun testController_createOpenLessonsTabContext_returnsCorrectTopicContext() {246    val eventContext = oppiaLogger.createOpenLessonsTabContext(TEST_TOPIC_ID)247    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_LESSONS_TAB)248    assertThat(eventContext.openLessonsTab.topicId).matches(TEST_TOPIC_ID)249  }250  @Test251  fun testController_createOpenPracticeTabContext_returnsCorrectTopicContext() {252    val eventContext = oppiaLogger.createOpenPracticeTabContext(TEST_TOPIC_ID)253    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_PRACTICE_TAB)254    assertThat(eventContext.openPracticeTab.topicId).matches(TEST_TOPIC_ID)255  }256  @Test257  fun testController_createOpenRevisionTabContext_returnsCorrectTopicContext() {258    val eventContext = oppiaLogger.createOpenRevisionTabContext(TEST_TOPIC_ID)259    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_REVISION_TAB)260    assertThat(eventContext.openRevisionTab.topicId).matches(TEST_TOPIC_ID)261  }262  @Test263  fun testController_createOpenConceptCardContext_returnsCorrectConceptCardContext() {264    val eventContext = oppiaLogger.createOpenConceptCardContext(TEST_SKILL_ID)265    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_CONCEPT_CARD)266    assertThat(eventContext.openConceptCard.skillId).matches(TEST_SKILL_ID)267  }268  @Test269  fun testController_createOpenRevisionCardContext_returnsCorrectRevisionCardContext() {270    val eventContext =271      oppiaLogger.createOpenRevisionCardContext(TEST_TOPIC_ID, TEST_SUB_TOPIC_ID)272    assertThat(eventContext.activityContextCase).isEqualTo(OPEN_REVISION_CARD)273    assertThat(eventContext.openRevisionCard.topicId).matches(TEST_TOPIC_ID)274    assertThat(eventContext.openRevisionCard.subTopicId).isEqualTo(TEST_SUB_TOPIC_ID)275  }276  private fun setUpTestApplicationComponent() {277    DaggerOppiaLoggerTest_TestApplicationComponent.builder()278      .setApplication(ApplicationProvider.getApplicationContext())279      .build()280      .inject(this)281  }282  // TODO(#89): Move this to a common test application component.283  @Module284  class TestModule {285    @Provides...

Full Screen

Full Screen

TodoOpenCheckTest.kt

Source:TodoOpenCheckTest.kt Github

copy

Full Screen

...4import org.junit.Before5import org.junit.Rule6import org.junit.Test7import org.junit.rules.TemporaryFolder8import org.oppia.android.scripts.proto.TodoOpenExemption9import org.oppia.android.scripts.proto.TodoOpenExemptions10import org.oppia.android.testing.assertThrows11import java.io.ByteArrayOutputStream12import java.io.File13import java.io.PrintStream14/** Tests for [TodoOpenCheck]. */15class TodoOpenCheckTest {16  private val outContent: ByteArrayOutputStream = ByteArrayOutputStream()17  private val originalOut: PrintStream = System.out18  private val TODO_CHECK_PASSED_OUTPUT_INDICATOR: String = "TODO CHECK PASSED"19  private val TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR: String = "TODO CHECK FAILED"20  private val pathToProtoBinary = "scripts/assets/todo_exemptions.pb"21  private val wikiReferenceNote =22    "Refer to https://github.com/oppia/oppia-android/wiki/Static-Analysis-Checks" +23      "#todo-open-checks for more details on how to fix this."24  @Rule25  @JvmField26  var tempFolder = TemporaryFolder()27  @Before28  fun setUp() {29    tempFolder.newFolder("testfiles")30    tempFolder.newFolder("scripts", "assets")31    tempFolder.newFile(pathToProtoBinary)32    System.setOut(PrintStream(outContent))33  }34  @After35  fun restoreStreams() {36    System.setOut(originalOut)37  }38  @Test39  fun testTodoCheck_noJsonFilePresent_checkShouldFail() {40    val exception = assertThrows(Exception::class) {41      runScript()42    }43    assertThat(exception).hasMessageThat().contains(44      "${retrieveTestFilesDirectoryPath()}/open_issues.json: No such file exists"45    )46  }47  @Test48  fun testTodoCheck_multipleTodosPresent_allAreValid_checkShouldPass() {49    val testJSONContent =50      """51      [{"number":11004},{"number":11003},{"number":11002},{"number":11001}]52      """.trimIndent()53    val testJSONFile = tempFolder.newFile("testfiles/open_issues.json")54    testJSONFile.writeText(testJSONContent)55    val tempFile1 = tempFolder.newFile("testfiles/TempFile1.kt")56    val tempFile2 = tempFolder.newFile("testfiles/TempFile2.kt")57    val testContent1 =58      """59      // TODO(#11002): test summary 1.60      # TODO(#11004): test summary 2.61      test Todo62      test TODO63      """.trimIndent()64    val testContent2 =65      """66      // TODO(#11001): test summary 3.67      todo68      <!-- TODO(#11003): test summary 4-->69      """.trimIndent()70    tempFile1.writeText(testContent1)71    tempFile2.writeText(testContent2)72    runScript()73    assertThat(outContent.toString().trim()).isEqualTo(TODO_CHECK_PASSED_OUTPUT_INDICATOR)74  }75  @Test76  fun testTodoCheck_onlyPoorlyFormattedTodosPresent_checkShouldFail() {77    val testJSONContent =78      """79      []80      """.trimIndent()81    val testJSONFile = tempFolder.newFile("testfiles/open_issues.json")82    testJSONFile.writeText(testJSONContent)83    val tempFile = tempFolder.newFile("testfiles/TempFile.txt")84    val testContent =85      """86      // TODO (#1044): test87      # TODO(102)88      <!-- TODO(#   101)-->89      // some test conent TODO(#1020000): test description.90      some test content TODO(#100002): some description.91      """.trimIndent()92    tempFile.writeText(testContent)93    val exception = assertThrows(Exception::class) {94      runScript()95    }96    assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR)97    val failureMessage =98      """99      TODOs not in correct format:100      - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:1101      - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:2102      - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:3103      - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:4104      - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:5105      106      $wikiReferenceNote107      """.trimIndent()108    assertThat(outContent.toString().trim()).isEqualTo(failureMessage)109  }110  @Test111  fun testTodoCheck_onlyOpenIssueFailureTodosPresent_checkShouldFail() {112    val testJSONContent =113      """114      [{"number":10000000},{"number":100000004}]115      """.trimIndent()116    val testJSONFile = tempFolder.newFile("testfiles/open_issues.json")117    testJSONFile.writeText(testJSONContent)118    val tempFile = tempFolder.newFile("testfiles/TempFile.txt")119    val testContent =120      """121      // TODO(#104444444): test summary 1.122      # TODO(#10210110): test summary 2.123      test todo124      some test content Todo125      <!-- TODO(#101000000): test summary 3-->126      """.trimIndent()127    tempFile.writeText(testContent)128    val exception = assertThrows(Exception::class) {129      runScript()130    }131    assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR)132    val failureMessage =133      """134      TODOs not corresponding to open issues on GitHub:135      - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:1136      - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:2137      - ${retrieveTestFilesDirectoryPath()}/TempFile.txt:5138      139      $wikiReferenceNote140      """.trimIndent()141    assertThat(outContent.toString().trim()).isEqualTo(failureMessage)142  }143  @Test144  fun testTodoCheck_multipleFailuresPresent_allFailuresShouldBeReported() {145    val testJSONContent =146      """147      [{"number":349888},{"number":349777}]148      """.trimIndent()149    val testJSONFile = tempFolder.newFile("testfiles/open_issues.json")150    testJSONFile.writeText(testJSONContent)151    val tempFile1 = tempFolder.newFile("testfiles/TempFile1.kt")152    val tempFile2 = tempFolder.newFile("testfiles/TempFile2.kt")153    val testContent1 =154      """155      // TODO(#10444444): test summary 1.156      #Todo(#102): test summary 2.157      <!-- TODO(#349888): test summary 3-->158      """.trimIndent()159    val testContent2 =160      """161      // TODO (#349777): test summary 1.162      todo163      <!-- TODO(#10000000): test summary 3-->164      """.trimIndent()165    tempFile1.writeText(testContent1)166    tempFile2.writeText(testContent2)167    val exception = assertThrows(Exception::class) {168      runScript()169    }170    assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR)171    val failureMessage =172      """173      TODOs not in correct format:174      - ${retrieveTestFilesDirectoryPath()}/TempFile1.kt:2175      - ${retrieveTestFilesDirectoryPath()}/TempFile2.kt:1176      177      TODOs not corresponding to open issues on GitHub:178      - ${retrieveTestFilesDirectoryPath()}/TempFile1.kt:1179      - ${retrieveTestFilesDirectoryPath()}/TempFile2.kt:3180      181      $wikiReferenceNote182      """.trimIndent()183    assertThat(outContent.toString().trim()).isEqualTo(failureMessage)184  }185  @Test186  fun testTodoCheck_multipleFailuresPresent_loggingShouldBeAsPerLexicographicalOrder() {187    val testJSONContent =188      """189      [{"number":349888},{"number":349777}]190      """.trimIndent()191    val testJSONFile = tempFolder.newFile("testfiles/open_issues.json")192    testJSONFile.writeText(testJSONContent)193    val tempFile1 = tempFolder.newFile("testfiles/Presenter.kt")194    val tempFile2 = tempFolder.newFile("testfiles/Fragment.kt")195    val tempFile3 = tempFolder.newFile("testfiles/Activity.kt")196    val testContent1 =197      """198      // TODO(#104444444444): test summary 1.199      #TODO (#102): test summary 2.200      <!-- TODO(#349888): test summary 3-->201      """.trimIndent()202    val testContent2 =203      """204      // TODO (#349777): test summary 1.205      some line todo test content206      <!-- TODO(#100000000): test summary 3-->207      """.trimIndent()208    val testContent3 =209      """210      test content211      // TODO (#3497): test summary 1.212      """.trimIndent()213    tempFile1.writeText(testContent1)214    tempFile2.writeText(testContent2)215    tempFile3.writeText(testContent3)216    val exception = assertThrows(Exception::class) {217      runScript()218    }219    assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR)220    val failureMessage =221      """222      TODOs not in correct format:223      - ${retrieveTestFilesDirectoryPath()}/Activity.kt:2224      - ${retrieveTestFilesDirectoryPath()}/Fragment.kt:1225      - ${retrieveTestFilesDirectoryPath()}/Presenter.kt:2226      227      TODOs not corresponding to open issues on GitHub:228      - ${retrieveTestFilesDirectoryPath()}/Fragment.kt:3229      - ${retrieveTestFilesDirectoryPath()}/Presenter.kt:1230      231      $wikiReferenceNote232      """.trimIndent()233    assertThat(outContent.toString().trim()).isEqualTo(failureMessage)234  }235  @Test236  fun testTodoCheck_addExemptions_exemptedTodosAreInvalid_checkShouldPass() {237    val testJSONContent =238      """239      [{"number":11004},{"number":11003},{"number":11002},{"number":11001}]240      """.trimIndent()241    val testJSONFile = tempFolder.newFile("testfiles/open_issues.json")242    testJSONFile.writeText(testJSONContent)243    val tempFile1 = tempFolder.newFile("testfiles/TempFile1.kt")244    val tempFile2 = tempFolder.newFile("testfiles/TempFile2.kt")245    val testContent1 =246      """247      // TODO (152440222): test description 1248      """.trimIndent()249    val testContent2 =250      """251      # TODO(#1000000): test description 2252      """.trimIndent()253    tempFile1.writeText(testContent1)254    tempFile2.writeText(testContent2)255    val exemptionFile = File("${tempFolder.root}/$pathToProtoBinary")256    val exemptions = TodoOpenExemptions.newBuilder().apply {257      this.addAllTodoOpenExemption(258        listOf(259          TodoOpenExemption.newBuilder().apply {260            this.exemptedFilePath = "TempFile1.kt"261            this.addAllLineNumber(listOf(1)).build()262          }.build(),263          TodoOpenExemption.newBuilder().apply {264            this.exemptedFilePath = "TempFile2.kt"265            this.addAllLineNumber(listOf(1)).build()266          }.build()267        )268      )269    }.build()270    exemptions.writeTo(exemptionFile.outputStream())271    runScript()272    assertThat(outContent.toString().trim()).isEqualTo(TODO_CHECK_PASSED_OUTPUT_INDICATOR)273  }274  @Test275  fun testTodoCheck_allTodosAreValid_redundantExemption_checkShouldFail() {276    val testJSONContent =277      """278      [{"number":1000000},{"number":152440222},{"number":152440223},{"number":11001}]279      """.trimIndent()280    val testJSONFile = tempFolder.newFile("testfiles/open_issues.json")281    testJSONFile.writeText(testJSONContent)282    val tempFile1 = tempFolder.newFile("testfiles/TempFile1.kt")283    val tempFile2 = tempFolder.newFile("testfiles/TempFile2.kt")284    val testContent1 =285      """286      // TODO(#152440222): test description 1287      // TODO(#152440223): test description 1288      """.trimIndent()289    val testContent2 =290      """291      # TODO(#1000000): test description 2292      """.trimIndent()293    tempFile1.writeText(testContent1)294    tempFile2.writeText(testContent2)295    val exemptionFile = File("${tempFolder.root}/$pathToProtoBinary")296    val exemptions = TodoOpenExemptions.newBuilder().apply {297      this.addAllTodoOpenExemption(298        listOf(299          TodoOpenExemption.newBuilder().apply {300            this.exemptedFilePath = "TempFile1.kt"301            this.addAllLineNumber(listOf(1, 2)).build()302          }.build(),303          TodoOpenExemption.newBuilder().apply {304            this.exemptedFilePath = "TempFile2.kt"305            this.addAllLineNumber(listOf(1)).build()306          }.build()307        )308      )309    }.build()310    exemptions.writeTo(exemptionFile.outputStream())311    val exception = assertThrows(Exception::class) {312      runScript()313    }314    assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR)315    val failureMessage =316      """317      Redundant exemptions (there are no TODOs corresponding to these lines):318      - TempFile1.kt:1319      - TempFile1.kt:2320      - TempFile2.kt:1321      Please remove them from scripts/assets/todo_exemptions.textproto322      """.trimIndent()323    assertThat(outContent.toString().trim()).isEqualTo(failureMessage)324  }325  @Test326  fun testTodoCheck_combineMultipleFailures_checkShouldFailWithAllErrorsLogged() {327    val testJSONContent =328      """329      [{"number":1000000},{"number":152440222},{"number":152440223},{"number":11001}]330      """.trimIndent()331    val testJSONFile = tempFolder.newFile("testfiles/open_issues.json")332    testJSONFile.writeText(testJSONContent)333    val tempFile1 = tempFolder.newFile("testfiles/TempFile1.kt")334    val tempFile2 = tempFolder.newFile("testfiles/TempFile2.kt")335    val testContent1 =336      """337      // TODO(#15244): test content 1338      // TODO(#152440223): test description 1339      // TODO(#10000000000000): test description 2340      """.trimIndent()341    val testContent2 =342      """343      # test content TODO(#11001): test description 2344      """.trimIndent()345    tempFile1.writeText(testContent1)346    tempFile2.writeText(testContent2)347    val exemptionFile = File("${tempFolder.root}/$pathToProtoBinary")348    val exemptions = TodoOpenExemptions.newBuilder().apply {349      this.addAllTodoOpenExemption(350        listOf(351          TodoOpenExemption.newBuilder().apply {352            this.exemptedFilePath = "TempFile1.kt"353            this.addAllLineNumber(listOf(1, 2)).build()354          }.build()355        )356      )357    }.build()358    exemptions.writeTo(exemptionFile.outputStream())359    val exception = assertThrows(Exception::class) {360      runScript()361    }362    assertThat(exception).hasMessageThat().contains(TODO_SYNTAX_CHECK_FAILED_OUTPUT_INDICATOR)363    val failureMessage =364      """365      Redundant exemptions (there are no TODOs corresponding to these lines):...

Full Screen

Full Screen

RetryingConnectionTest.kt

Source:RetryingConnectionTest.kt Github

copy

Full Screen

1package com.blockchain.network.websocket2import com.blockchain.testutils.rxInit3import com.nhaarman.mockito_kotlin.mock4import com.nhaarman.mockito_kotlin.times5import com.nhaarman.mockito_kotlin.verify6import io.reactivex.Observable7import io.reactivex.schedulers.TestScheduler8import io.reactivex.subjects.PublishSubject9import io.reactivex.subjects.Subject10import org.junit.Rule11import org.junit.Test12import java.util.concurrent.TimeUnit13class RetryingConnectionTest {14    private val testScheduler = TestScheduler()15    @get:Rule16    val rx = rxInit {17        computation(testScheduler)18    }19    @Test20    fun `passes on open to inner`() {21        val connection = MockConnection()22        connection.autoRetry().open()23        verify(connection.mock).open()24    }25    @Test26    fun `passes on close to inner`() {27        val connection = MockConnection()28        connection.autoRetry().close()29        verify(connection.mock).close()30    }31    @Test32    fun `if the underlying socket closes, we reopen after 1 second delay`() {33        val connection = MockConnection()34        connection.autoRetry().open()35        connection.simulateDisconnect()36        testScheduler.advanceTimeBy(999, TimeUnit.MILLISECONDS)37        verify(connection.mock, times(1)).open()38        testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS)39        verify(connection.mock, times(2)).open()40    }41    @Test42    fun `if the underlying socket closes twice, we reopen twice, each after 1 second delay`() {43        val connection = MockConnection()44        connection.autoRetry().open()45        connection.simulateDisconnect()46        testScheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS)47        verify(connection.mock, times(2)).open()48        connection.simulateDisconnect()49        testScheduler.advanceTimeBy(999, TimeUnit.MILLISECONDS)50        verify(connection.mock, times(2)).open()51        testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS)52        verify(connection.mock, times(3)).open()53    }54    @Test55    fun `if we close the connection, and the underlying socket closes, we do not reopen`() {56        val connection = MockConnection()57        connection.autoRetry()58            .also {59                it.open()60                it.close()61            }62        connection.simulateDisconnect()63        verify(connection.mock).open()64        testScheduler.advanceTimeBy(10, TimeUnit.SECONDS)65        verify(connection.mock).open()66    }67    @Test68    fun `WebSocket autoRetry, if the underlying socket closes, we reopen`() {69        val connection = MockConnection()70        val webSocket: WebSocket<String, String> = mock<WebSocketSendReceive<String, String>>() + connection71        webSocket.autoRetry().open()72        connection.simulateDisconnect()73        testScheduler.advanceTimeBy(1, TimeUnit.SECONDS)74        verify(connection.mock, times(2)).open()75    }76    @Test77    fun `multiple disconnect events do not cause multiple connections`() {78        val connection = MockConnection()79        connection.autoRetry().open()80        connection.simulateDisconnect()81        connection.simulateDisconnect()82        connection.simulateDisconnect()83        testScheduler.advanceTimeBy(10, TimeUnit.SECONDS)84        verify(connection.mock, times(2)).open()85    }86    @Test87    fun `if the connection is opened and closed many times, will still recover`() {88        val connection = MockConnection()89        connection.autoRetry().apply {90            open()91            close()92            open()93            close()94            open()95        }96        connection.simulateDisconnect()97        testScheduler.advanceTimeBy(10, TimeUnit.SECONDS)98        verify(connection.mock, times(4)).open()99    }100}101class RetryingConnectionFailingConnectionDelayTest {102    private val testScheduler = TestScheduler()103    @get:Rule104    val rx = rxInit {105        computation(testScheduler)106    }107    @Test108    fun `if the underlying socket fails, we retry after 1 second delay`() {109        val connection = MockConnection()110        connection.autoRetry().open()111        connection.simulateFailure()112        testScheduler.advanceTimeBy(999, TimeUnit.MILLISECONDS)113        verify(connection.mock, times(1)).open()114        testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS)115        verify(connection.mock, times(2)).open()116    }117    @Test118    fun `if the underlying socket fails twice, we retry after a 2 second delay`() {119        val connection = MockConnection()120        connection.autoRetry().open()121        connection.simulateFailure()122        testScheduler.advanceTimeBy(1000, TimeUnit.MILLISECONDS)123        verify(connection.mock, times(2)).open()124        connection.simulateFailure()125        testScheduler.advanceTimeBy(1999, TimeUnit.MILLISECONDS)126        verify(connection.mock, times(2)).open()127        testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS)128        verify(connection.mock, times(3)).open()129    }130    @Test131    fun `if the underlying socket fails 3 times, we retry after a 4 second delay`() {132        val connection = MockConnection()133        connection.autoRetry().open()134        connection.simulateFailure()135        testScheduler.advanceTimeBy(1, TimeUnit.SECONDS)136        connection.simulateFailure()137        testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)138        verify(connection.mock, times(3)).open()139        connection.simulateFailure()140        testScheduler.advanceTimeBy(3999, TimeUnit.MILLISECONDS)141        verify(connection.mock, times(3)).open()142        testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS)143        verify(connection.mock, times(4)).open()144    }145    @Test146    fun `if the underlying socket fails 4 times, we remain on a 4 second delay`() {147        val connection = MockConnection()148        connection.autoRetry().open()149        connection.simulateFailure()150        testScheduler.advanceTimeBy(1, TimeUnit.SECONDS)151        connection.simulateFailure()152        testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)153        connection.simulateFailure()154        testScheduler.advanceTimeBy(4, TimeUnit.SECONDS)155        verify(connection.mock, times(4)).open()156        connection.simulateFailure()157        testScheduler.advanceTimeBy(4, TimeUnit.SECONDS)158        verify(connection.mock, times(5)).open()159    }160    @Test161    fun `after a successful connection, the timer resets`() {162        val connection = MockConnection()163        connection.autoRetry().open()164        connection.simulateFailure()165        testScheduler.advanceTimeBy(1, TimeUnit.SECONDS)166        connection.simulateFailure()167        testScheduler.advanceTimeBy(2, TimeUnit.SECONDS)168        connection.simulateFailure()169        testScheduler.advanceTimeBy(4, TimeUnit.SECONDS)170        verify(connection.mock, times(4)).open()171        connection.simulateSuccess()172        testScheduler.advanceTimeBy(10, TimeUnit.SECONDS)173        connection.simulateFailure()174        testScheduler.advanceTimeBy(999, TimeUnit.MILLISECONDS)175        verify(connection.mock, times(4)).open()176        testScheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS)177        verify(connection.mock, times(5)).open()178    }179}180class MockConnection(val mock: WebSocketConnection = mock()) : WebSocketConnection by mock {181    private val subject: Subject<ConnectionEvent> = PublishSubject.create<ConnectionEvent>()182    override val connectionEvents: Observable<ConnectionEvent>183        get() = subject184    fun simulateDisconnect() {185        subject.onNext(ConnectionEvent.ClientDisconnect)186    }187    fun simulateFailure() {188        subject.onNext(ConnectionEvent.Failure(Exception()))189    }190    fun simulateSuccess() {191        subject.onNext(ConnectionEvent.Connected)192    }193    fun simulateAuthenticated() {194        subject.onNext(ConnectionEvent.Authenticated)195    }196}...

Full Screen

Full Screen

StoreNavigationDualScreenTest.kt

Source:StoreNavigationDualScreenTest.kt Github

copy

Full Screen

1/*2 *3 * Copyright (c) Microsoft Corporation. All rights reserved.4 * Licensed under the MIT License.5 *6 */7package com.microsoft.device.samples.dualscreenexperience.presentation.store8import androidx.test.platform.app.InstrumentationRegistry9import androidx.test.rule.ActivityTestRule10import androidx.test.uiautomator.UiDevice11import com.microsoft.device.dualscreen.testing.resetOrientation12import com.microsoft.device.dualscreen.testing.spanFromStart13import com.microsoft.device.samples.dualscreenexperience.R14import com.microsoft.device.samples.dualscreenexperience.presentation.MainActivity15import com.microsoft.device.samples.dualscreenexperience.presentation.about.checkAboutInDualScreenMode16import com.microsoft.device.samples.dualscreenexperience.presentation.about.checkToolbarAbout17import com.microsoft.device.samples.dualscreenexperience.presentation.about.openAbout18import com.microsoft.device.samples.dualscreenexperience.presentation.devmode.checkToolbarDevItem19import com.microsoft.device.samples.dualscreenexperience.presentation.devmode.checkToolbarUserItem20import com.microsoft.device.samples.dualscreenexperience.presentation.devmode.navigateUp21import com.microsoft.device.samples.dualscreenexperience.presentation.devmode.openDevModeInDualMode22import com.microsoft.device.samples.dualscreenexperience.presentation.devmode.openUserMode23import com.microsoft.device.samples.dualscreenexperience.presentation.launch.goBack24import dagger.hilt.android.testing.HiltAndroidRule25import dagger.hilt.android.testing.HiltAndroidTest26import org.junit.After27import org.junit.Rule28import org.junit.Test29import org.junit.rules.RuleChain30@HiltAndroidTest31class StoreNavigationDualScreenTest : BaseStoreNavigationTest() {32    private val activityRule = ActivityTestRule(MainActivity::class.java)33    private val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())34    @get:Rule35    var ruleChain: RuleChain =36        RuleChain.outerRule(HiltAndroidRule(this)).around(activityRule)37    @After38    fun resetOrientation() {39        device.resetOrientation()40    }41    @Test42    fun openMapInDualLandscapeMode() {43        device.spanFromStart()44        openMapInSingleMode()45    }46    @Test47    fun openMapInDualPortraitMode() {48        device.spanFromStart()49        device.setOrientationRight()50        openMapInSingleMode()51        checkToolbarDevItem()52    }53    @Test54    fun openAboutInDualPortraitMode() {55        device.spanFromStart()56        openMapInSingleMode()57        checkToolbarAbout()58        openAbout()59        checkAboutInDualScreenMode()60        goBack()61        checkMapFragment()62        checkToolbar(R.string.app_name)63        checkToolbarAbout()64    }65    @Test66    fun openAboutInDualLandscapeMode() {67        device.spanFromStart()68        device.setOrientationRight()69        openMapInSingleMode()70        checkToolbarAbout()71        openAbout()72        checkAboutInDualScreenMode()73        goBack()74        checkMapFragment()75        checkToolbar(R.string.app_name)76        checkToolbarAbout()77    }78    @Test79    fun openDevModeInDualPortraitMode() {80        device.spanFromStart()81        openMapInSingleMode()82        openDevModeInDualMode()83        checkToolbarUserItem()84        openUserMode()85        checkMapFragment()86        checkToolbar(R.string.app_name)87        checkToolbarDevItem()88    }89    @Test90    fun openDevModeInDualLandscapeMode() {91        device.spanFromStart()92        device.setOrientationRight()93        openMapInSingleMode()94        openDevModeInDualMode()95        checkToolbarUserItem()96        openUserMode()97        checkMapFragment()98        checkToolbar(R.string.app_name)99        checkToolbarDevItem()100    }101    @Test102    fun openDetailsFromMapInDualLandscapeMode() {103        openDetailsFromMapInDualMode()104        checkToolbarDevItem()105    }106    @Test107    fun openDetailsFromMapInDualPortraitMode() {108        device.setOrientationRight()109        openDetailsFromMapInDualMode()110        checkToolbarDevItem()111    }112    @Test113    fun openListFromDetailsInDualLandscapeMode() {114        openListFromDetailsInDualMode()115        checkToolbarDevItem()116    }117    @Test118    fun openListFromDetailsInDualPortraitMode() {119        device.setOrientationRight()120        openListFromDetailsInDualMode()121        checkToolbarDevItem()122    }123    @Test124    fun spanDetailsFromMap() {125        clickOnMapMarker(storeWithoutCity.name)126        device.spanFromStart()127        checkMapFragment()128        checkDetailsFragment(storeWithoutCity)129        navigateUp()130        checkMapFragment()131        checkToolbar(R.string.app_name)132        checkToolbarDevItem()133    }134    @Test135    fun openListFromMapInDualLandscapeMode() {136        openListFromMapInDualMode()137        checkToolbarDevItem()138    }139    @Test140    fun openListFromMapInDualPortraitMode() {141        device.setOrientationRight()142        openListFromMapInDualMode()143        checkToolbarDevItem()144    }145    @Test146    fun spanListFromMap() {147        clickOnMapMarker(cityRedmond.name)148        device.spanFromStart()149        checkMapFragment()150        checkListFragment(cityRedmond.name, STORE_FIRST_POSITION, firstStore)151        checkListFragmentInEmptyState(device)152        navigateUp()153        checkMapFragment()154        checkToolbar(R.string.app_name)155        checkToolbarDevItem()156    }157    @Test158    fun openDetailsFromListInDualLandscapeMode() {159        openDetailsFromListInDualMode()160        checkToolbarDevItem()161    }162    @Test163    fun openDetailsFromListInDualPortraitMode() {164        device.setOrientationRight()165        openDetailsFromListInDualMode()166        checkToolbarDevItem()167    }168    @Test169    fun spanDetailsFromList() {170        clickOnMapMarker(cityRedmond.name)171        clickOnListItemAtPosition(STORE_FIRST_POSITION)172        device.spanFromStart()173        checkMapFragment()174        checkDetailsFragment(firstStore)175        navigateUp()176        checkMapFragment()177        checkListFragment(cityRedmond.name, STORE_FIRST_POSITION, firstStore)178        navigateUp()179        checkMapFragment()180        checkToolbar(R.string.app_name)181        checkToolbarDevItem()182    }183}...

Full Screen

Full Screen

StoreNavigationSingleScreenTest.kt

Source:StoreNavigationSingleScreenTest.kt Github

copy

Full Screen

1/*2 *3 * Copyright (c) Microsoft Corporation. All rights reserved.4 * Licensed under the MIT License.5 *6 */7package com.microsoft.device.samples.dualscreenexperience.presentation.store8import androidx.test.platform.app.InstrumentationRegistry9import androidx.test.rule.ActivityTestRule10import androidx.test.uiautomator.UiDevice11import com.microsoft.device.dualscreen.testing.resetOrientation12import com.microsoft.device.samples.dualscreenexperience.R13import com.microsoft.device.samples.dualscreenexperience.presentation.MainActivity14import com.microsoft.device.samples.dualscreenexperience.presentation.about.checkAboutInSingleScreenMode15import com.microsoft.device.samples.dualscreenexperience.presentation.about.checkToolbarAbout16import com.microsoft.device.samples.dualscreenexperience.presentation.about.openAbout17import com.microsoft.device.samples.dualscreenexperience.presentation.launch.goBack18import dagger.hilt.android.testing.HiltAndroidRule19import dagger.hilt.android.testing.HiltAndroidTest20import org.junit.After21import org.junit.Rule22import org.junit.Test23import org.junit.rules.RuleChain24@HiltAndroidTest25class StoreNavigationSingleScreenTest : BaseStoreNavigationTest() {26    private val activityRule = ActivityTestRule(MainActivity::class.java)27    private val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())28    @get:Rule29    var ruleChain: RuleChain =30        RuleChain.outerRule(HiltAndroidRule(this)).around(activityRule)31    @After32    fun resetOrientation() {33        device.resetOrientation()34    }35    @Test36    fun openMapInPortraitMode() {37        openMapInSingleMode()38    }39    @Test40    fun openMapInLandscapeMode() {41        device.setOrientationRight()42        openMapInSingleMode()43    }44    @Test45    fun openAboutInPortraitMode() {46        openMapInSingleMode()47        checkToolbarAbout()48        openAbout()49        checkAboutInSingleScreenMode()50        goBack()51        checkMapFragment()52        checkToolbar(R.string.app_name)53        checkToolbarAbout()54    }55    @Test56    fun openAboutInLandscapeMode() {57        device.setOrientationRight()58        openMapInSingleMode()59        checkToolbarAbout()60        openAbout()61        checkAboutInSingleScreenMode()62        goBack()63        checkMapFragment()64        checkToolbar(R.string.app_name)65        checkToolbarAbout()66    }67    @Test68    fun openDetailsFromMapInPortraitMode() {69        openDetailsFromMapInSingleMode()70    }71    @Test72    fun openDetailsFromMapInLandscapeMode() {73        device.setOrientationRight()74        openDetailsFromMapInSingleMode()75    }76    @Test77    fun openListFromMapInPortraitMode() {78        openListFromMapInSingleMode()79    }80    @Test81    fun openListFromMapInLandscapeMode() {82        device.setOrientationRight()83        openListFromMapInSingleMode()84    }85    @Test86    fun openDetailsFromListInPortraitMode() {87        openDetailsFromListInSingleMode()88    }89    @Test90    fun openDetailsFromListInLandscapeMode() {91        device.setOrientationRight()92        openDetailsFromListInSingleMode()93    }94}...

Full Screen

Full Screen

Open

Using AI Code Generation

copy

Full Screen

1		Open o = new Open();2		o.msg();3		Close c = new Close();4		c.msg();5		Protected p = new Protected();6		p.msg();7	}8}

Full Screen

Full Screen

Open

Using AI Code Generation

copy

Full Screen

1import test.Open;2public class Closed extends Open{3	public static void main(String[] args) {4		Closed obj = new Closed();5		obj.display();6	}7}

Full Screen

Full Screen

Open

Using AI Code Generation

copy

Full Screen

1	}2}3{4	void open()5	{6		System.out.println("Open class");7	}8}9package test;10{11	public void open()12	{13		System.out.println("Open class");14	}15}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful