Best Mockito-kotlin code snippet using test.Open.string
TodoOpenCheckTest.kt
Source:TodoOpenCheckTest.kt
1package org.oppia.android.scripts.todo2import com.google.common.truth.Truth.assertThat3import org.junit.After4import 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):366 - TempFile1.kt:2367 Please remove them from scripts/assets/todo_exemptions.textproto368 369 TODOs not in correct format:370 - ${retrieveTestFilesDirectoryPath()}/TempFile2.kt:1371 372 TODOs not corresponding to open issues on GitHub:373 - ${retrieveTestFilesDirectoryPath()}/TempFile1.kt:3374 375 $wikiReferenceNote376 """.trimIndent()377 assertThat(outContent.toString().trim()).isEqualTo(failureMessage)378 }379 /** Retrieves the absolute path of testfiles directory. */380 private fun retrieveTestFilesDirectoryPath(): String {381 return "${tempFolder.root}/testfiles"382 }383 /** Runs the todo_open_check. */384 private fun runScript() {385 main(386 retrieveTestFilesDirectoryPath(),387 "${tempFolder.root}/$pathToProtoBinary",388 "open_issues.json"389 )390 }391}...
SearchTest.kt
Source:SearchTest.kt
1/* This Source Code Form is subject to the terms of the Mozilla Public2 * License, v. 2.0. If a copy of the MPL was not distributed with this3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */4package org.mozilla.fenix.ui5import androidx.compose.ui.test.junit4.AndroidComposeTestRule6import androidx.core.net.toUri7import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu8import mozilla.components.browser.icons.IconRequest9import mozilla.components.browser.icons.generator.DefaultIconGenerator10import mozilla.components.feature.search.ext.createSearchEngine11import okhttp3.mockwebserver.MockWebServer12import org.junit.After13import org.junit.Before14import org.junit.Ignore15import org.junit.Rule16import org.junit.Test17import org.mozilla.fenix.customannotations.SmokeTest18import org.mozilla.fenix.helpers.FeatureSettingsHelper19import org.mozilla.fenix.helpers.HomeActivityTestRule20import org.mozilla.fenix.helpers.SearchDispatcher21import org.mozilla.fenix.helpers.TestHelper.appContext22import org.mozilla.fenix.helpers.TestHelper.exitMenu23import org.mozilla.fenix.helpers.TestHelper.longTapSelectItem24import org.mozilla.fenix.helpers.TestHelper.setCustomSearchEngine25import org.mozilla.fenix.ui.robots.homeScreen26import org.mozilla.fenix.ui.robots.multipleSelectionToolbar27/**28 * Tests for verifying the search fragment29 *30 * Including:31 * - Verify the toolbar, awesomebar, and shortcut bar are displayed32 * - Select shortcut button33 * - Select scan button34 *35 */36class SearchTest {37 private val featureSettingsHelper = FeatureSettingsHelper()38 lateinit var searchMockServer: MockWebServer39 @get:Rule40 val activityTestRule = AndroidComposeTestRule(41 HomeActivityTestRule(),42 { it.activity }43 )44 @Before45 fun setUp() {46 searchMockServer = MockWebServer().apply {47 dispatcher = SearchDispatcher()48 start()49 }50 featureSettingsHelper.setJumpBackCFREnabled(false)51 featureSettingsHelper.setPocketEnabled(false)52 }53 @After54 fun tearDown() {55 searchMockServer.shutdown()56 featureSettingsHelper.resetAllFeatureFlags()57 }58 @Test59 fun searchScreenItemsTest() {60 homeScreen {61 }.openSearch {62 verifySearchView()63 verifyBrowserToolbar()64 verifyScanButton()65 verifySearchEngineButton()66 }67 }68 @SmokeTest69 @Ignore("This test cannot run on virtual devices due to camera permissions being required")70 @Test71 fun scanButtonTest() {72 homeScreen {73 }.openSearch {74 clickScanButton()75 clickDenyPermission()76 clickScanButton()77 clickAllowPermission()78 }79 }80 @Test81 @Ignore("Flaky. See https://github.com/mozilla-mobile/fenix/issues/20973")82 fun shortcutButtonTest() {83 homeScreen {84 }.openThreeDotMenu {85 }.openSettings {86 }.openSearchSubMenu {87 enableShowSearchShortcuts()88 }.goBack {89 }.goBack {90 }.openSearch {91 verifySearchBarEmpty()92 clickSearchEngineButton(activityTestRule, "DuckDuckGo")93 typeSearch("mozilla")94 verifySearchEngineResults(2)95 clickSearchEngineResult(activityTestRule, "DuckDuckGo")96 verifySearchEngineURL("DuckDuckGo")97 }98 }99 @Test100 fun shortcutSearchEngineSettingsTest() {101 homeScreen {102 }.openThreeDotMenu {103 }.openSettings {104 }.openSearchSubMenu {105 enableShowSearchShortcuts()106 }.goBack {107 }.goBack {108 }.openSearch {109 scrollToSearchEngineSettings(activityTestRule)110 clickSearchEngineSettings(activityTestRule)111 verifySearchSettings()112 }113 }114 @Test115 fun clearSearchTest() {116 homeScreen {117 }.openSearch {118 typeSearch("test")119 clickClearButton()120 verifySearchBarEmpty()121 }122 }123 @Ignore("Failure caused by bugs: https://github.com/mozilla-mobile/fenix/issues/23818")124 @SmokeTest125 @Test126 fun searchGroupShowsInRecentlyVisitedTest() {127 val firstPage = searchMockServer.url("generic1.html").toString()128 val secondPage = searchMockServer.url("generic2.html").toString()129 // setting our custom mockWebServer search URL130 val searchString = "http://localhost:${searchMockServer.port}/searchResults.html?search={searchTerms}"131 val customSearchEngine = createSearchEngine(132 name = "TestSearchEngine",133 url = searchString,134 icon = DefaultIconGenerator().generate(appContext, IconRequest(searchString)).bitmap135 )136 setCustomSearchEngine(customSearchEngine)137 // Performs a search and opens 2 dummy search results links to create a search group138 homeScreen {139 }.openSearch {140 }.submitQuery("test search") {141 longClickMatchingText("Link 1")142 clickContextOpenLinkInNewTab()143 longClickMatchingText("Link 2")144 clickContextOpenLinkInNewTab()145 }.goToHomescreen {146 verifyJumpBackInSectionIsDisplayed()147 verifyCurrentSearchGroupIsDisplayed(true, "test search", 3)148 verifyRecentlyVisitedSearchGroupDisplayed(false, "test search", 3)149 }.openTabDrawer {150 }.openTabFromGroup(firstPage) {151 }.openTabDrawer {152 }.openTabFromGroup(secondPage) {153 }.openTabDrawer {154 }.openTabsListThreeDotMenu {155 }.closeAllTabs {156 verifyRecentlyVisitedSearchGroupDisplayed(true, "test search", 3)157 }158 }159 @SmokeTest160 @Test161 fun noCurrentSearchGroupFromPrivateBrowsingTest() {162 // setting our custom mockWebServer search URL163 val searchString = "http://localhost:${searchMockServer.port}/searchResults.html?search={searchTerms}"164 val customSearchEngine = createSearchEngine(165 name = "TestSearchEngine",166 url = searchString,167 icon = DefaultIconGenerator().generate(appContext, IconRequest(searchString)).bitmap168 )169 setCustomSearchEngine(customSearchEngine)170 // Performs a search and opens 2 dummy search results links to create a search group171 homeScreen {172 }.openSearch {173 }.submitQuery("test search") {174 longClickMatchingText("Link 1")175 clickContextOpenLinkInPrivateTab()176 longClickMatchingText("Link 2")177 clickContextOpenLinkInPrivateTab()178 }.goToHomescreen {179 verifyCurrentSearchGroupIsDisplayed(false, "test search", 3)180 }.openThreeDotMenu {181 }.openHistory {182 verifyHistoryItemExists(false, "3 sites")183 }184 }185 @SmokeTest186 @Test187 fun noRecentlyVisitedSearchGroupInPrivateBrowsingTest() {188 val firstPage = searchMockServer.url("generic1.html").toString()189 val secondPage = searchMockServer.url("generic2.html").toString()190 // setting our custom mockWebServer search URL191 val searchString = "http://localhost:${searchMockServer.port}/searchResults.html?search={searchTerms}"192 val customSearchEngine = createSearchEngine(193 name = "TestSearchEngine",194 url = searchString,195 icon = DefaultIconGenerator().generate(appContext, IconRequest(searchString)).bitmap196 )197 setCustomSearchEngine(customSearchEngine)198 // Performs a search and opens 2 dummy search results links to create a search group199 homeScreen {200 }.togglePrivateBrowsingMode()201 homeScreen {202 }.openSearch {203 }.submitQuery("test search") {204 longClickMatchingText("Link 1")205 clickContextOpenLinkInPrivateTab()206 longClickMatchingText("Link 2")207 clickContextOpenLinkInPrivateTab()208 }.openTabDrawer {209 }.openTab(firstPage) {210 }.openTabDrawer {211 }.openTab(secondPage) {212 }.openTabDrawer {213 }.openTabsListThreeDotMenu {214 }.closeAllTabs {215 homeScreen {216 }.togglePrivateBrowsingMode()217 verifyRecentlyVisitedSearchGroupDisplayed(false, "test search", 3)218 }219 }220 @Ignore("Failure caused by bugs: https://github.com/mozilla-mobile/fenix/issues/23818")221 @SmokeTest222 @Test223 fun deleteItemsFromSearchGroupsHistoryTest() {224 val firstPage = searchMockServer.url("generic1.html").toString()225 val secondPage = searchMockServer.url("generic2.html").toString()226 // setting our custom mockWebServer search URL227 val searchString = "http://localhost:${searchMockServer.port}/searchResults.html?search={searchTerms}"228 val customSearchEngine = createSearchEngine(229 name = "TestSearchEngine",230 url = searchString,231 icon = DefaultIconGenerator().generate(appContext, IconRequest(searchString)).bitmap232 )233 setCustomSearchEngine(customSearchEngine)234 // Performs a search and opens 2 dummy search results links to create a search group235 homeScreen {236 }.openSearch {237 }.submitQuery("test search") {238 longClickMatchingText("Link 1")239 clickContextOpenLinkInNewTab()240 longClickMatchingText("Link 2")241 clickContextOpenLinkInNewTab()242 }.openTabDrawer {243 }.openTabFromGroup(firstPage) {244 }.openTabDrawer {245 }.openTabFromGroup(secondPage) {246 }.openTabDrawer {247 }.openTabsListThreeDotMenu {248 }.closeAllTabs {249 verifyRecentlyVisitedSearchGroupDisplayed(true, "test search", 3)250 }.openRecentlyVisitedSearchGroupHistoryList("test search") {251 clickDeleteHistoryButton(firstPage)252 longTapSelectItem(secondPage.toUri())253 multipleSelectionToolbar {254 openActionBarOverflowOrOptionsMenu(activityTestRule.activity)255 clickMultiSelectionDelete()256 }257 exitMenu()258 }259 homeScreen {260 // checking that the group is removed when only 1 item is left261 verifyRecentlyVisitedSearchGroupDisplayed(false, "test search", 1)262 }263 }264}...
answer.kt
Source:answer.kt
1package ru.smarty.testme.model2import com.fasterxml.jackson.annotation.JsonGetter3import com.fasterxml.jackson.annotation.JsonIgnore4import com.fasterxml.jackson.annotation.JsonView5import com.fasterxml.jackson.databind.ObjectMapper6import com.fasterxml.jackson.module.kotlin.KotlinModule7import org.hibernate.annotations.BatchSize8import org.hibernate.annotations.Type9import java.util.*10import javax.persistence.*11import javax.validation.constraints.Size12@Suppress("unused")13@Entity14@Table(schema = "tm", name = "test_pass")15open class TestPass() {16 @get:Id17 @get:GeneratedValue(strategy = GenerationType.IDENTITY)18 open var id: Int = 019 @get:Size(min = 1)20 open var testCode: String = ""21 @get:Size(min = 1)22 open var testTitle: String = ""23 @get:Size(min = 1)24 open var testDescription: String = ""25 open var testDefaultTime: Int = 026 @get:Size(min = 1)27 open var code: String = ""28 open var shuffleAnswers = false29 @get:ManyToOne30 open lateinit var appUser: AppUser31 @get:JsonView(Views.FullAdmin::class)32 @get:OneToMany(orphanRemoval = true, cascade = arrayOf(CascadeType.ALL), targetEntity = QuestionAnswer::class, mappedBy = "testPass")33 @get:OrderBy("num")34 @get:BatchSize(size = 100)35 open var questionsWithAnswer: List<QuestionAnswer> = ArrayList()36 @get:JsonView(Views.Admin::class)37 open var currentQuestionNum = -138 open var created: Date = Date()39 constructor(testCode: String, code: String, user: AppUser, test: Test) : this() {40 questionsWithAnswer = test.questions.mapIndexed { i, question ->41 QuestionAnswer(this, i, question)42 }.toMutableList()43 if (test.shuffleQuestions) {44 Collections.shuffle(questionsWithAnswer)45 }46 questionsWithAnswer.forEachIndexed { i, questionAnswer -> questionAnswer.num = i }47 this.testCode = testCode48 this.testTitle = test.title49 this.testDescription = test.description50 this.testDefaultTime = test.defaultTime51 this.shuffleAnswers = test.shuffleAnswers52 this.code = code53 this.appUser = user54 }55 fun answer(answers: List<Int>, comment: String? = null, textAnswer: String? = null, now: Long = System.currentTimeMillis()) {56 require(!isDone())57 this.questionsWithAnswer[currentQuestionNum].answer(answers, comment, textAnswer, now)58 }59 fun currentQuestionData(now: Long = System.currentTimeMillis()): QuestionData {60 require(!isDone())61 val answer = questionsWithAnswer[currentQuestionNum]62 val answers = answer.question.answers.map { it.text }.withIndex().toMutableList()63 if (shuffleAnswers) {64 Collections.shuffle(answers)65 }66 val time = answer.time67 return QuestionData(68 question = answer.question.question,69 time = time,70 answers = answers,71 isMultiAnswer = answer.question.isMultiAnswer(),72 isOpenQuestion = answer.question.isOpenQuestion(),73 msLeft = (answer.started!!.time + time * 1000 - now).toInt(),74 index = currentQuestionNum + 1,75 total = questionsWithAnswer.size76 )77 }78 fun startNext(now: Long = System.currentTimeMillis()) {79 require(!isDone()) { "Already done!" }80 currentQuestionNum += 181 if (!isDone()) {82 questionsWithAnswer[currentQuestionNum].start(now)83 }84 }85 @Transient86 fun isDone() = currentQuestionNum >= questionsWithAnswer.size87 data class QuestionData(88 val question: String,89 val time: Int,90 val isMultiAnswer: Boolean,91 val isOpenQuestion: Boolean,92 val answers: List<IndexedValue<String>>,93 val msLeft: Int,94 val index: Int,95 val total: Int)96 @JsonView(Views.Admin::class, Views.Public::class)97 @JsonGetter("score")98 fun score(): ScoreData {99 val categoryToScore = HashMap<String, Pair<Double, Double>>()100 var totalGood = 0.0101 var totalMax = 0.0102 var toBeGraded = 0103 for (qa in questionsWithAnswer) {104 if (qa.question.isOpenQuestion() && qa.mark == null) {105 toBeGraded += 1106 continue107 }108 val score = qa.score()109 totalGood += score110 totalMax += qa.question.weight111 val existing = categoryToScore[qa.question.category]112 categoryToScore[qa.question.category] = Pair((existing?.first ?: 0.0) + score, (existing?.second ?: 0.0) + qa.question.weight)113 }114 val categoryScore = categoryToScore.map {115 val (category, pair) = it;116 CategoryScore(category, 5.0 * pair.first / Math.max(1.0, pair.second))117 }.toMutableList()118 Collections.sort(categoryScore, { a, b -> a.category.compareTo(b.category) })119 return ScoreData(5.0 * totalGood / totalMax, categoryScore, toBeGraded)120 }121 data class ScoreData(122 val totalScore: Double,123 val perCategoryScore: List<CategoryScore>,124 val questionsToBeGraded: Int125 )126 data class CategoryScore(val category: String, val score: Double)127}128@Suppress("unused")129@Entity130@Table(schema = "tm", name = "question_answer")131open class QuestionAnswer() {132 @get:Id133 @get:GeneratedValue(strategy = GenerationType.IDENTITY)134 open var id: Int = 0135 open var started: Date? = null136 open var answered: Date? = null137 @get:JsonIgnore138 @get:ManyToOne139 @get:BatchSize(size = 100)140 open var testPass: TestPass? = null141 @get:Type(type = "ru.smarty.testme.utils.IntArrayUserType")142 open var answers: List<Int> = emptyList()143 @get:Type(type = "ru.smarty.testme.utils.IntArrayUserType")144 open var criteriasMet: List<Int> = emptyList()145 open var originalIndex: Int = 0146 open var num: Int = 0147 @get:Transient148 open var question: Question = Question.Null149 open var comment: String? = null150 open var textAnswer: String? = null151 open var mark: Double? = null152 @get:ManyToOne153 @get:BatchSize(size = 100)154 open var markedBy: AppUser? = null155 /**156 * This field is for hibernate. The full json copy of question is stored.157 * It has drawbacks: it'll be hard to compare answers for different questions.158 * Still it wouldn't complicate schema. Because there might be different versions159 * of question, you need to store them all and point to specific version.160 */161 @Suppress("unused")162 open var questionJson: String163 @JsonIgnore get() = mapper.writeValueAsString(question)164 set(value: String) {165 question = mapper.readValue(value, Question::class.java)166 }167 open val time: Int168 @Transient get() = question.timeOverride ?: testPass!!.testDefaultTime169 constructor(testPass: TestPass, originalIndex: Int, question: Question) : this() {170 this.originalIndex = originalIndex171 this.question = question172 this.testPass = testPass173 }174 fun start(now: Long = System.currentTimeMillis()) {175 started = Date(now)176 }177 fun answer(answers: List<Int>, comment: String? = null, textAnswer: String? = null, now: Long = System.currentTimeMillis()) {178 require(started != null, { "Must be started before it's answered" })179 require(answers.all { it >= 0 && it < question.answers.size }, { "incorrect answer index" })180 this.answered = Date(now)181 this.answers = answers182 this.comment = comment183 this.textAnswer = textAnswer184 }185 @JsonView(Views.FullAdmin::class)186 @JsonGetter("duration")187 fun duration() = if (answered != null) answered!!.time - started!!.time else null188 @JsonGetter189 fun timeout() = answered != null && duration()!! > (time + 10) * 1000190 @JsonView(Views.FullAdmin::class)191 @JsonGetter("score")192 fun score(): Double {193 // A more clever logic for multianswers might be implemented194 if (question.answers.size == 0) {195 return mark ?: 0.0196 } else if (answered != null && !timeout()) {197 if (question.advancedWeight) {198 val correctIndexes = question.answers.withIndex().filter { it.value.correct }.map { it.index }199 val answersSum = answers.map { if (it in correctIndexes) 1 else -1 }.sum()200 val missedSum = correctIndexes.filter { it !in answers }.size201 return Math.max(0.0, (answersSum - missedSum) * 1.0 / correctIndexes.size) * question.weight202 } else if (question.answers.withIndex().filter { it.value.correct }.map { it.index }.toSet() == answers.toSet()) {203 return question.weight204 } else {205 return 0.0206 }207 } else {208 return 0.0209 }210 }211 companion object {212 val mapper = ObjectMapper()213 init {214 mapper.registerModule(KotlinModule())215 // mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION)216 // mapper.setConfig(mapper.serializationConfig.withView(Views.Serialize::class.java))217 }218 }219}...
MenuScreenShotTest.kt
Source:MenuScreenShotTest.kt
...171 Screengrab.screenshot("save-login-prompt")172 }173 }174}175fun openHistoryThreeDotMenu() = onView(withText(R.string.library_history)).click()176fun openBookmarksThreeDotMenu() = onView(withText(R.string.library_bookmarks)).click()177fun editBookmarkFolder() = onView(withText(R.string.bookmark_menu_edit_button)).click()178fun deleteBookmarkFolder() = onView(withText(R.string.bookmark_menu_delete_button)).click()179fun tapOnTabCounter() = onView(withId(R.id.counter_text)).click()180fun settingsAccountPreferences() = onView(withText(R.string.preferences_sync)).click()181fun settingsSearch() = onView(withText(R.string.preferences_search)).click()182fun settingsTheme() = onView(withText(R.string.preferences_customize)).click()183fun settingsAccessibility() = onView(withText(R.string.preferences_accessibility)).click()184fun settingDefaultBrowser() = onView(withText(R.string.preferences_set_as_default_browser)).click()185fun settingsToolbar() = onView(withText(R.string.preferences_toolbar)).click()186fun settingsTP() = onView(withText(R.string.preference_enhanced_tracking_protection)).click()187fun settingsAddToHomeScreen() = onView(withText(R.string.preferences_add_private_browsing_shortcut)).click()188fun settingsRemoveData() = onView(withText(R.string.preferences_delete_browsing_data)).click()189fun settingsTelemetry() = onView(withText(R.string.preferences_data_collection)).click()190fun loginsAndPassword() = onView(withText(R.string.preferences_passwords_logins_and_passwords)).click()191fun addOns() = onView(withText(R.string.preferences_addons)).click()192fun settingsLanguage() = onView(withText(R.string.preferences_language)).click()193fun verifySaveLoginPromptIsShownNotSave() {194 mDevice.waitNotNull(Until.findObjects(By.text("test@example.com")), TestAssetHelper.waitingTime)195 val submitButton = mDevice.findObject(By.res("submit"))196 submitButton.clickAndWait(Until.newWindow(), TestAssetHelper.waitingTime)197}198fun clickAddFolderButtonUsingId() = onView(withId(R.id.add_bookmark_folder)).click()...
ServerLauncherCodeGeneratorTest.kt
Source:ServerLauncherCodeGeneratorTest.kt
1package com.wutsi.codegen.kotlin.server2import com.wutsi.codegen.Context3import com.wutsi.codegen.kotlin.sdk.SdkCodeGenerator4import io.swagger.v3.oas.models.OpenAPI5import io.swagger.v3.oas.models.info.Info6import io.swagger.v3.parser.OpenAPIV3Parser7import org.apache.commons.io.IOUtils8import org.junit.jupiter.api.BeforeEach9import org.junit.jupiter.api.Test10import org.springframework.util.FileSystemUtils11import java.io.File12import java.nio.file.Files13import kotlin.test.Ignore14import kotlin.test.assertEquals15import kotlin.test.assertTrue16internal class ServerLauncherCodeGeneratorTest {17 val context = Context(18 apiName = "Test",19 outputDirectory = "./target/wutsi/codegen/server",20 basePackage = "com.wutsi.test",21 jdkVersion = "1.8",22 githubUser = null23 )24 val codegen = ServerLauncherCodeGenerator()25 @BeforeEach26 fun setUp() {27 FileSystemUtils.deleteRecursively(File(context.outputDirectory))28 }29 @Test30 fun `generate`() {31 val openAPI = createOpenAPI()32 codegen.generate(openAPI, context)33 // Launcher34 val file = File("${context.outputDirectory}/src/main/kotlin/com/wutsi/test/Application.kt")35 assertTrue(file.exists())36 val text = file.readText()37 assertEquals(38 """39 package com.wutsi.test40 import com.wutsi.platform.core.WutsiApplication41 import kotlin.String42 import kotlin.Unit43 import org.springframework.boot.autoconfigure.SpringBootApplication44 import org.springframework.scheduling.`annotation`.EnableAsync45 import org.springframework.scheduling.`annotation`.EnableScheduling46 @WutsiApplication47 @SpringBootApplication48 @EnableAsync49 @EnableScheduling50 public class Application51 public fun main(vararg args: String): Unit {52 org.springframework.boot.runApplication<Application>(*args)53 }54 """.trimIndent(),55 text.trimIndent()56 )57 }58 @Test59 fun `generate with security`() {60 val openAPI = createOpenAPI(true)61 codegen.generate(openAPI, context)62 // Launcher63 val file = File("${context.outputDirectory}/src/main/kotlin/com/wutsi/test/Application.kt")64 assertTrue(file.exists())65 val text = file.readText()66 assertEquals(67 """68 package com.wutsi.test69 import com.wutsi.platform.core.WutsiApplication70 import kotlin.String71 import kotlin.Unit72 import org.springframework.boot.autoconfigure.SpringBootApplication73 import org.springframework.scheduling.`annotation`.EnableAsync74 import org.springframework.scheduling.`annotation`.EnableScheduling75 @WutsiApplication76 @SpringBootApplication77 @EnableAsync78 @EnableScheduling79 public class Application80 public fun main(vararg args: String): Unit {81 org.springframework.boot.runApplication<Application>(*args)82 }83 """.trimIndent(),84 text.trimIndent()85 )86 }87 @Test88 fun `generate with database`() {89 val openAPI = createOpenAPI()90 context.addService(Context.SERVICE_DATABASE)91 codegen.generate(openAPI, context)92 // Launcher93 val file = File("${context.outputDirectory}/src/main/kotlin/com/wutsi/test/Application.kt")94 assertTrue(file.exists())95 val text = file.readText()96 assertEquals(97 """98 package com.wutsi.test99 import com.wutsi.platform.core.WutsiApplication100 import kotlin.String101 import kotlin.Unit102 import org.springframework.boot.autoconfigure.SpringBootApplication103 import org.springframework.scheduling.`annotation`.EnableAsync104 import org.springframework.scheduling.`annotation`.EnableScheduling105 import org.springframework.transaction.`annotation`.EnableTransactionManagement106 @WutsiApplication107 @SpringBootApplication108 @EnableAsync109 @EnableScheduling110 @EnableTransactionManagement111 public class Application112 public fun main(vararg args: String): Unit {113 org.springframework.boot.runApplication<Application>(*args)114 }115 """.trimIndent(),116 text.trimIndent()117 )118 }119 @Test120 fun `generate with cache`() {121 val openAPI = createOpenAPI()122 context.addService(Context.SERVICE_CACHE)123 codegen.generate(openAPI, context)124 // Launcher125 val file = File("${context.outputDirectory}/src/main/kotlin/com/wutsi/test/Application.kt")126 assertTrue(file.exists())127 val text = file.readText()128 assertEquals(129 """130 package com.wutsi.test131 import com.wutsi.platform.core.WutsiApplication132 import kotlin.String133 import kotlin.Unit134 import org.springframework.boot.autoconfigure.SpringBootApplication135 import org.springframework.scheduling.`annotation`.EnableAsync136 import org.springframework.scheduling.`annotation`.EnableScheduling137 @WutsiApplication138 @SpringBootApplication139 @EnableAsync140 @EnableScheduling141 public class Application142 public fun main(vararg args: String): Unit {143 org.springframework.boot.runApplication<Application>(*args)144 }145 """.trimIndent(),146 text.trimIndent()147 )148 }149 @Test150 fun `generate with mqueue`() {151 val openAPI = createOpenAPI()152 context.addService(Context.SERVICE_MQUEUE)153 codegen.generate(openAPI, context)154 // Launcher155 val file = File("${context.outputDirectory}/src/main/kotlin/com/wutsi/test/Application.kt")156 assertTrue(file.exists())157 val text = file.readText()158 assertEquals(159 """160 package com.wutsi.test161 import com.wutsi.platform.core.WutsiApplication162 import kotlin.String163 import kotlin.Unit164 import org.springframework.boot.autoconfigure.SpringBootApplication165 import org.springframework.scheduling.`annotation`.EnableAsync166 import org.springframework.scheduling.`annotation`.EnableScheduling167 @WutsiApplication168 @SpringBootApplication169 @EnableAsync170 @EnableScheduling171 public class Application172 public fun main(vararg args: String): Unit {173 org.springframework.boot.runApplication<Application>(*args)174 }175 """.trimIndent(),176 text.trimIndent()177 )178 }179 @Test180 @Ignore181 fun `generate - do not overwrite`() {182 val openAPI = createOpenAPI()183 var path = "${context.outputDirectory}/src/main/kotlin/com/wutsi/test/Application.kt"184 File(path).parentFile.mkdirs()185 Files.write(186 File(path).toPath(),187 "xxx".toByteArray()188 )189 val delay = 5000L190 Thread.sleep(delay)191 codegen.generate(openAPI, context)192 val file = File(path)193 assertTrue(System.currentTimeMillis() - file.lastModified() >= delay)194 }195 private fun createOpenAPI(withSecurity: Boolean = false): OpenAPI {196 if (withSecurity) {197 val yaml = IOUtils.toString(SdkCodeGenerator::class.java.getResourceAsStream("/api.yaml"), "utf-8")198 return OpenAPIV3Parser().readContents(yaml).openAPI199 } else {200 val openAPI = OpenAPI()201 openAPI.info = Info()202 openAPI.info.version = "1.3.7"203 return openAPI204 }205 }206}...
mangling.kt
Source:mangling.kt
1// IGNORE_BACKEND: JS_IR2// KJS_WITH_FULL_RUNTIME3// SKIP_MINIFICATION4// This test uses eval to access root package, therefore DCE can't infer usage of corresponding functions5package foo6private var log = ""7public fun public_baz(i: Int) {8 log = "public_baz"9}10external public fun public_baz(a: String) {11 definedExternally12}13internal fun internal_baz(i: Int) {14}15internal external fun internal_baz(a: String) {16 definedExternally17}18private fun getCurrentPackage(): dynamic = eval("_").foo19private fun private_baz(i: Int) {20}21private external fun private_baz(a: String) {22 definedExternally23}24public class PublicClass {25 public fun public_baz(i: Int) {26 }27 @JsName("public_baz")28 public fun public_baz(a: String) {29 }30 internal fun internal_baz(i: Int) {31 }32 @JsName("internal_baz")33 internal fun internal_baz(a: String) {34 }35 private fun private_baz(i: Int) {36 }37 @JsName("private_baz")38 private fun private_baz(a: String) {39 }40 val call_private_baz = { private_baz(0) }41 val call_private_native_baz = { private_baz("native") }42}43internal class InternalClass {44 public fun public_baz(i: Int) {45 }46 @JsName("public_baz")47 public fun public_baz(a: String) {48 }49 internal fun internal_baz(i: Int) {50 }51 @JsName("internal_baz")52 internal fun internal_baz(a: String) {53 }54 private fun private_baz(i: Int) {55 }56 @JsName("private_baz")57 private fun private_baz(a: String) {58 }59 val call_private_baz = { private_baz(0) }60 val call_private_native_baz = { private_baz("native") }61}62private class PrivateClass {63 public fun public_baz(i: Int) {64 }65 @JsName("public_baz")66 public fun public_baz(a: String) {67 }68 internal fun internal_baz(i: Int) {69 }70 @JsName("internal_baz")71 internal fun internal_baz(a: String) {72 }73 private fun private_baz(i: Int) {74 }75 @JsName("private_baz")76 private fun private_baz(a: String) {77 }78 val call_private_baz = { private_baz(0) }79 val call_private_native_baz = { private_baz("native") }80}81open public class OpenPublicClass {82 public fun public_baz(i: Int) {83 }84 @JsName("public_baz")85 public fun public_baz(a: String) {86 }87 internal fun internal_baz(i: Int) {88 }89 @JsName("internal_baz")90 internal fun internal_baz(a: String) {91 }92 private fun private_baz(i: Int) {93 }94 @JsName("private_baz")95 private fun private_baz(a: String) {96 }97 val call_private_baz = { private_baz(0) }98 val call_private_native_baz = { private_baz("native") }99}100internal open class OpenInternalClass {101 public fun public_baz(i: Int) {102 }103 @JsName("public_baz")104 public fun public_baz(a: String) {105 }106 internal fun internal_baz(i: Int) {107 }108 @JsName("internal_baz")109 internal fun internal_baz(a: String) {110 }111 private fun private_baz(i: Int) {112 }113 @JsName("private_baz")114 private fun private_baz(a: String) {115 }116 val call_private_baz = { private_baz(0) }117 val call_private_native_baz = { private_baz("native") }118}119open private class OpenPrivateClass {120 public fun public_baz(i: Int) {121 }122 @JsName("public_baz")123 public fun public_baz(a: String) {124 }125 internal fun internal_baz(i: Int) {126 }127 @JsName("internal_baz")128 internal fun internal_baz(a: String) {129 }130 private fun private_baz(i: Int) {131 }132 @JsName("private_baz")133 private fun private_baz(a: String) {134 }135 val call_private_baz = { private_baz(0) }136 val call_private_native_baz = { private_baz("native") }137}138// Helpers139val CALEE_NAME = RegExp("""\b\w*(baz[^(]*)""")140fun Function0<Unit>.extractNames(): Array<String> {141 val names = CALEE_NAME.exec(this.toString())142 if (names == null || names.size != 2) {143 throw Exception("Cannot extract function name, $names for actual = \"$this\"")144 }145 return names146}147// Testing148var testGroup = ""149fun test(expected: String, f: () -> Unit) {150 val actual = f.extractNames()151 if (expected != actual[1]) {152 fail("Failed on '$testGroup' group: expected = \"$expected\", actual[1] = \"${actual[1]}\"\n actual = $actual")153 }154}155val privateMangledRegex = Regex("baz_[0-9a-zA-Z]+\\\$_0")156fun testMangledPrivate(f: () -> Unit) {157 val actual = f.extractNames()158 if (!privateMangledRegex.matches(actual[1])) {159 fail("Failed on '$testGroup' group: actual[1] = \"${actual[1]}\"\n actual = $actual, should look like 'baz_<hash>_0'")160 }161 if ("_za3lpa\$" in actual[1]) {162 fail("Failed on '$testGroup' group: actual[1] = \"${actual[1]}\"\n actual = $actual, should not contains 'za3lpa\$'")163 }164}165class Dummy {166 public fun stable_mangled_baz(i: Int) { }167}168val SIMPLE = "baz"169val SIMPLE0 = "${SIMPLE}_0"170val NATIVE = SIMPLE171val STABLE = "baz_za3lpa$"172val INTERNAL = "baz_kcn2v3$"173fun box(): String {174 testGroup = "Top Level"175 getCurrentPackage().`public_baz_za3lpa$`(0)176 assertEquals("public_baz", log)177 test(NATIVE) { public_baz("native") }178 testGroup = "Public Class"179 test(STABLE) { PublicClass().public_baz(0) }180 test(NATIVE) { PublicClass().public_baz("native") }181 test(INTERNAL) { PublicClass().internal_baz(0) }182 test(NATIVE) { PublicClass().internal_baz("native") }183 test(SIMPLE0, PublicClass().call_private_baz)184 test(NATIVE, PublicClass().call_private_native_baz)185 testGroup = "Internal Class"186 test(STABLE) { InternalClass().public_baz(0) }187 test(NATIVE) { InternalClass().public_baz("native") }188 test(INTERNAL) { InternalClass().internal_baz(0) }189 test(NATIVE) { InternalClass().internal_baz("native") }190 test(SIMPLE0, InternalClass().call_private_baz)191 test(NATIVE, InternalClass().call_private_native_baz)192 testGroup = "Private Class"193 test(STABLE) { PrivateClass().public_baz(0) }194 test(NATIVE) { PrivateClass().public_baz("native") }195 test(INTERNAL) { PrivateClass().internal_baz(0) }196 test(NATIVE) { PrivateClass().internal_baz("native") }197 test(SIMPLE0, PrivateClass().call_private_baz)198 test(NATIVE, PrivateClass().call_private_native_baz)199 testGroup = "Open Public Class"200 test(STABLE) { OpenPublicClass().public_baz(0) }201 test(NATIVE) { OpenPublicClass().public_baz("native") }202 test(INTERNAL) { OpenPublicClass().internal_baz(0) }203 test(NATIVE) { OpenPublicClass().internal_baz("native") }204 testMangledPrivate(OpenPublicClass().call_private_baz)205 test(NATIVE, OpenPublicClass().call_private_native_baz)206 testGroup = "Open Internal Class"207 test(STABLE) { OpenInternalClass().public_baz(0) }208 test(NATIVE) { OpenInternalClass().public_baz("native") }209 test(INTERNAL) { OpenInternalClass().internal_baz(0) }210 test(NATIVE) { OpenInternalClass().internal_baz("native") }211 test(SIMPLE0, OpenInternalClass().call_private_baz)212 test(NATIVE, OpenInternalClass().call_private_native_baz)213 testGroup = "Open Private Class"214 test(STABLE) { OpenPrivateClass().public_baz(0) }215 test(NATIVE) { OpenPrivateClass().public_baz("native") }216 test(INTERNAL) { OpenPrivateClass().internal_baz(0) }217 test(NATIVE) { OpenPrivateClass().internal_baz("native") }218 test(SIMPLE0, OpenPrivateClass().call_private_baz)219 test(NATIVE, OpenPrivateClass().call_private_native_baz)220 return "OK"221}...
SQLiteOpenHelperWriterTest.kt
Source:SQLiteOpenHelperWriterTest.kt
1/*2 * Copyright (C) 2016 The Android Open Source Project3 *4 * Licensed under the Apache License, Version 2.0 (the "License");5 * you may not use this file except in compliance with the License.6 * You may obtain a copy of the License at7 *8 * http://www.apache.org/licenses/LICENSE-2.09 *10 * Unless required by applicable law or agreed to in writing, software11 * distributed under the License is distributed on an "AS IS" BASIS,12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13 * See the License for the specific language governing permissions and14 * limitations under the License.15 */16package androidx.room.writer17import androidx.annotation.NonNull18import androidx.room.processor.DatabaseProcessor19import androidx.room.testing.TestInvocation20import androidx.room.testing.TestProcessor21import androidx.room.vo.Database22import com.google.auto.common.MoreElements23import com.google.common.truth.Truth24import com.google.testing.compile.CompileTester25import com.google.testing.compile.JavaFileObjects26import com.google.testing.compile.JavaSourcesSubjectFactory27import org.hamcrest.CoreMatchers.`is`28import org.hamcrest.MatcherAssert.assertThat29import org.junit.Test30import org.junit.runner.RunWith31import org.junit.runners.JUnit432@RunWith(JUnit4::class)33class SQLiteOpenHelperWriterTest {34 companion object {35 const val ENTITY_PREFIX = """36 package foo.bar;37 import androidx.annotation.NonNull;38 import androidx.room.*;39 @Entity%s40 public class MyEntity {41 """42 const val ENTITY_SUFFIX = "}"43 const val DATABASE_CODE = """44 package foo.bar;45 import androidx.room.*;46 @Database(entities = {MyEntity.class}, version = 3)47 abstract public class MyDatabase extends RoomDatabase {48 }49 """50 }51 @Test52 fun createSimpleEntity() {53 singleEntity(54 """55 @PrimaryKey56 @NonNull57 String uuid;58 String name;59 int age;60 """.trimIndent()61 ) { database, _ ->62 val query = SQLiteOpenHelperWriter(database)63 .createQuery(database.entities.first())64 assertThat(query, `is`("CREATE TABLE IF NOT EXISTS" +65 " `MyEntity` (`uuid` TEXT NOT NULL, `name` TEXT, `age` INTEGER NOT NULL," +66 " PRIMARY KEY(`uuid`))"))67 }.compilesWithoutError()68 }69 @Test70 fun multiplePrimaryKeys() {71 singleEntity(72 """73 @NonNull74 String uuid;75 @NonNull76 String name;77 int age;78 """.trimIndent(), attributes = mapOf("primaryKeys" to "{\"uuid\", \"name\"}")79 ) { database, _ ->80 val query = SQLiteOpenHelperWriter(database)81 .createQuery(database.entities.first())82 assertThat(query, `is`("CREATE TABLE IF NOT EXISTS" +83 " `MyEntity` (`uuid` TEXT NOT NULL, `name` TEXT NOT NULL, " +84 "`age` INTEGER NOT NULL, PRIMARY KEY(`uuid`, `name`))"))85 }.compilesWithoutError()86 }87 @Test88 fun autoIncrementObject() {89 listOf("Long", "Integer").forEach { type ->90 singleEntity(91 """92 @PrimaryKey(autoGenerate = true)93 $type uuid;94 String name;95 int age;96 """.trimIndent()97 ) { database, _ ->98 val query = SQLiteOpenHelperWriter(database)99 .createQuery(database.entities.first())100 assertThat(query, `is`("CREATE TABLE IF NOT EXISTS" +101 " `MyEntity` (`uuid` INTEGER PRIMARY KEY AUTOINCREMENT," +102 " `name` TEXT, `age` INTEGER NOT NULL)"))103 }.compilesWithoutError()104 }105 }106 @Test107 fun autoIncrementPrimitives() {108 listOf("long", "int").forEach { type ->109 singleEntity(110 """111 @PrimaryKey(autoGenerate = true)112 $type uuid;113 String name;114 int age;115 """.trimIndent()116 ) { database, _ ->117 val query = SQLiteOpenHelperWriter(database)118 .createQuery(database.entities.first())119 assertThat(query, `is`("CREATE TABLE IF NOT EXISTS" +120 " `MyEntity` (`uuid` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," +121 " `name` TEXT, `age` INTEGER NOT NULL)"))122 }.compilesWithoutError()123 }124 }125 fun singleEntity(input: String, attributes: Map<String, String> = mapOf(),126 handler: (Database, TestInvocation) -> Unit): CompileTester {127 val attributesReplacement: String128 if (attributes.isEmpty()) {129 attributesReplacement = ""130 } else {131 attributesReplacement = "(" +132 attributes.entries.joinToString(",") { "${it.key} = ${it.value}" } +133 ")".trimIndent()134 }135 return Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())136 .that(listOf(JavaFileObjects.forSourceString("foo.bar.MyEntity",137 ENTITY_PREFIX.format(attributesReplacement) + input + ENTITY_SUFFIX138 ), JavaFileObjects.forSourceString("foo.bar.MyDatabase",139 DATABASE_CODE)))140 .processedWith(TestProcessor.builder()141 .forAnnotations(androidx.room.Database::class,142 NonNull::class)143 .nextRunHandler { invocation ->144 val db = MoreElements.asType(invocation.roundEnv145 .getElementsAnnotatedWith(146 androidx.room.Database::class.java)147 .first())148 handler(DatabaseProcessor(invocation.context, db).process(), invocation)149 true150 }151 .build())152 }153}...
BottomNavigationTest.kt
Source:BottomNavigationTest.kt
...61 @Test62 fun bottomNavView_backstackMaintained() {63 // The back stack of any screen is maintained when returning to it64 openThirdScreen()65 onView(withContentDescription(R.string.sign_up))66 .perform(click())67 assertDeeperThirdScreen()68 openFirstScreen()69 // Return to 3rd70 openThirdScreen()71 // Assert it maintained the back stack72 assertDeeperThirdScreen()73 }74 @Test75 fun bottomNavView_registerBackRegister() {76 openThirdScreen()77 pressBack() // This is handled in a especial way in code.78 openThirdScreen()79 onView(withContentDescription(R.string.sign_up))80 .perform(click())81 // Assert it maintained the back stack82 assertDeeperThirdScreen()83 }84 @Test85 fun bottomNavView_itemReselected_goesBackToStart() {86 openThirdScreen()87 assertThirdScreen()88 onView(withContentDescription(R.string.sign_up))89 .perform(click())90 assertDeeperThirdScreen()91 // Reselect the current item92 openThirdScreen()93 // Verify that it popped the back stack until the start destination.94 assertThirdScreen()95 }96 private fun assertSecondScreen() {97 onView(allOf(withText(R.string.title_list), isDescendantOfA(withId(R.id.action_bar))))98 .check(matches(isDisplayed()))99 }100 private fun openSecondScreen() {101 onView(allOf(withContentDescription(R.string.title_list), isDisplayed()))102 .perform(click())103 }104 private fun assertDeeperThirdScreen() {105 onView(withText(R.string.done))106 .check(matches(isDisplayed()))107 }108 private fun openFirstScreen() {109 onView(allOf(withContentDescription(R.string.title_home), isDisplayed()))110 .perform(click())111 }112 private fun assertFirstScreen() {113 onView(withText(R.string.welcome))114 .check(matches(isDisplayed()))115 }116 private fun openThirdScreen() {117 onView(allOf(withContentDescription(R.string.title_register), isDisplayed()))118 .perform(click())119 }120 private fun assertThirdScreen() {121 onView(withText(R.string.select_an_avatar))122 .check(matches(isDisplayed()))123 }124}...
string
Using AI Code Generation
1 String s1 = "Hello";2 String s2 = "Hello";3 String s3 = new String("Hello");4 String s4 = new String("Hello");5 String s5 = "Hello";6 String s6 = "Hello";7 String s7 = new String("Hello");8 String s8 = new String("Hello");9 String s9 = "Hello";10 String s10 = "Hello";11 String s11 = new String("Hello");12 String s12 = new String("Hello");13 String s13 = "Hello";14 String s14 = "Hello";15 String s15 = new String("Hello");16 String s16 = new String("Hello");17 test.Open.open(s1, s2);18 test.Open.open(s3, s4);19 test.Open.open(s5, s6);20 test.Open.open(s7, s8);21 test.Open.open(s9, s10);22 test.Open.open(s11, s12);23 test.Open.open(s13, s14);24 test.Open.open(s15, s16);25 int i1 = 10;26 int i2 = 10;27 int i3 = 10;28 int i4 = 10;29 int i5 = 10;30 int i6 = 10;31 int i7 = 10;32 int i8 = 10;33 int i9 = 10;34 int i10 = 10;35 int i11 = 10;36 int i12 = 10;37 int i13 = 10;38 int i14 = 10;39 int i15 = 10;40 int i16 = 10;41 test.Open.open(i1, i2);42 test.Open.open(i3, i4);43 test.Open.open(i5, i6);44 test.Open.open(i7, i8);45 test.Open.open(i9, i10);46 test.Open.open(i11, i12);47 test.Open.open(i13, i14);48 test.Open.open(i15, i16);49 double d1 = 10.0;50 double d2 = 10.0;51 double d3 = 10.0;
string
Using AI Code Generation
1 String s1="Java";2 String s2="java";3 System.out.println(s1.equals(s2));4 System.out.println(s1.equalsIgnoreCase(s2));5 System.out.println(s1.contains("a"));6 System.out.println(s1.startsWith("J"));7 System.out.println(s1.endsWith("a"));8 System.out.println(s1.indexOf('a'));9 System.out.println(s1.lastIndexOf('a'));10 System.out.println(s1.length());11 System.out.println(s1.replace('a', 'A'));12 System.out.println(s1.substring(1));13 System.out.println(s1.substring(1,3));14 System.out.println(s1.toLowerCase());15 System.out.println(s1.toUpperCase());16 System.out.println(s1.trim());17 System.out.println(s1.isEmpty());18 String s3="Java";19 String s4="java";20 System.out.println(s3.equals(s4));21 System.out.println(s3.equalsIgnoreCase(s4));22 System.out.println(s3.contains("a"));23 System.out.println(s3.startsWith("J"));24 System.out.println(s3.endsWith("a"));25 System.out.println(s3.indexOf('a'));26 System.out.println(s3.lastIndexOf('a'));27 System.out.println(s3.length());28 System.out.println(s3.replace('a', 'A'));29 System.out.println(s3.substring(1));30 System.out.println(s3.substring(1,3));31 System.out.println(s3.toLowerCase());32 System.out.println(s3.toUpperCase());33 System.out.println(s3.trim());34 System.out.println(s3.isEmpty());35 String s5="Java";36 String s6="java";37 System.out.println(s5.equals(s6));38 System.out.println(s5.equalsIgnoreCase(s6));39 System.out.println(s5.contains("a"));40 System.out.println(s5.startsWith("J"));41 System.out.println(s5.endsWith("a"));42 System.out.println(s5.indexOf('a'));43 System.out.println(s5.lastIndexOf('a'));44 System.out.println(s5.length());45 System.out.println(s5.replace('a', 'A'));46 System.out.println(s5.substring(1));47 System.out.println(s5.substring(1,3));48 System.out.println(s5.toLowerCase());49 System.out.println(s5.toUpperCase());50 System.out.println(s5.trim());
string
Using AI Code Generation
1String text = test.Open.getText();2test.Open.setText(text);3String text = test.Open.getText();4test.Open.setText(text);5String text = test.Open.getText();6test.Open.setText(text);7String text = test.Open.getText();8test.Open.setText(text);9String text = test.Open.getText();10test.Open.setText(text);11String text = test.Open.getText();12test.Open.setText(text);13String text = test.Open.getText();14test.Open.setText(text);15String text = test.Open.getText();16test.Open.setText(text);17String text = test.Open.getText();18test.Open.setText(text);19String text = test.Open.getText();20test.Open.setText(text);
string
Using AI Code Generation
1 System.out.println("Enter the string to be checked for palindrome");2 String str=sc.nextLine();3 System.out.println(test.Open.palindrome(str));4 }5 catch(Exception e)6 {7 System.out.println("Exception occured");8 }9 }10}
string
Using AI Code Generation
1 String data = test.Open.getData("C:\\Users\\Nikhil\\Desktop\\TestData.xlsx", "Sheet1", 1, 2);2 System.out.println(data);3 test.Open.setData("C:\\Users\\Nikhil\\Desktop\\TestData.xlsx", "Sheet1", 1, 2, "Hello");4 String data1 = test.Open.getData("C:\\Users\\Nikhil\\Desktop\\TestData.xlsx", "Sheet1", 1, 2);5 System.out.println(data1);6 }7 catch (Exception e)8 {9 System.out.println(e);10 }11 }12}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!