Bug 1885123 - Add logs to DataGenerationHelper
[gecko.git] / mobile / android / fenix / app / src / androidTest / java / org / mozilla / fenix / helpers / DataGenerationHelper.kt
blob44e46b1355075969d05913fda7fd885d08f44751
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 package org.mozilla.fenix.helpers
7 import android.app.PendingIntent
8 import android.content.ClipData
9 import android.content.ClipboardManager
10 import android.content.Context
11 import android.content.Intent
12 import android.graphics.Bitmap
13 import android.graphics.Canvas
14 import android.graphics.Color
15 import android.net.Uri
16 import android.util.Log
17 import androidx.browser.customtabs.CustomTabsIntent
18 import androidx.test.platform.app.InstrumentationRegistry
19 import androidx.test.uiautomator.UiSelector
20 import mozilla.components.browser.state.search.SearchEngine
21 import mozilla.components.browser.state.state.availableSearchEngines
22 import org.junit.Assert
23 import org.mozilla.fenix.ext.components
24 import org.mozilla.fenix.helpers.Constants.TAG
25 import org.mozilla.fenix.helpers.TestHelper.mDevice
26 import org.mozilla.fenix.utils.IntentUtils
27 import java.time.LocalDate
28 import java.time.LocalTime
30 object DataGenerationHelper {
31     val appContext: Context = InstrumentationRegistry.getInstrumentation().targetContext
33     fun createCustomTabIntent(
34         pageUrl: String,
35         customMenuItemLabel: String = "",
36         customActionButtonDescription: String = "",
37     ): Intent {
38         Log.i(TAG, "createCustomTabIntent: Trying to create custom tab intent with url: $pageUrl")
39         val appContext = InstrumentationRegistry.getInstrumentation()
40             .targetContext
41             .applicationContext
42         val pendingIntent = PendingIntent.getActivity(appContext, 0, Intent(), IntentUtils.defaultIntentPendingFlags)
43         val customTabsIntent = CustomTabsIntent.Builder()
44             .addMenuItem(customMenuItemLabel, pendingIntent)
45             .setShareState(CustomTabsIntent.SHARE_STATE_ON)
46             .setActionButton(
47                 createTestBitmap(),
48                 customActionButtonDescription,
49                 pendingIntent,
50                 true,
51             )
52             .build()
53         customTabsIntent.intent.data = Uri.parse(pageUrl)
54         Log.i(TAG, "createCustomTabIntent: Created custom tab intent with url: $pageUrl")
55         return customTabsIntent.intent
56     }
58     private fun createTestBitmap(): Bitmap {
59         Log.i(TAG, "createTestBitmap: Trying to create a test bitmap")
60         val bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888)
61         val canvas = Canvas(bitmap)
62         canvas.drawColor(Color.GREEN)
63         Log.i(TAG, "createTestBitmap: Created a test bitmap")
64         return bitmap
65     }
67     fun getStringResource(id: Int, argument: String = TestHelper.appName) = TestHelper.appContext.resources.getString(id, argument)
69     private val charPool: List<Char> = ('a'..'z') + ('A'..'Z') + ('0'..'9')
70     fun generateRandomString(stringLength: Int): String {
71         Log.i(TAG, "generateRandomString: Trying to generate a random string with $stringLength characters")
72         val randomString =
73             (1..stringLength)
74                 .map { kotlin.random.Random.nextInt(0, charPool.size) }
75                 .map(charPool::get)
76                 .joinToString("")
77         Log.i(TAG, "generateRandomString: Generated random string: $randomString")
79         return randomString
80     }
82     /**
83      * Creates clipboard data.
84      */
85     fun setTextToClipBoard(context: Context, message: String) {
86         Log.i(TAG, "setTextToClipBoard: Trying to set clipboard text to: $message")
87         val clipBoard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
88         val clipData = ClipData.newPlainText("label", message)
90         clipBoard.setPrimaryClip(clipData)
91         Log.i(TAG, "setTextToClipBoard: Clipboard text was set to: $message")
92     }
94     /**
95      * Constructs a date and time placeholder string for sponsored Fx suggest links.
96      * The format of the datetime is YYYYMMDDHH, where YYYY is the four-digit year,
97      * MM is the two-digit month, DD is the two-digit day, and HH is the two-digit hour.
98      * Single-digit months, days, and hours are padded with a leading zero to ensure
99      * the correct format. For example, a date and time of January 10, 2024, at 3 PM
100      * would be represented as "2024011015".
101      *
102      * @return A string representing the current date and time in the specified format.
103      */
104     fun getSponsoredFxSuggestPlaceHolder(): String {
105         Log.i(TAG, "getSponsoredFxSuggestPlaceHolder: Trying to get the sponsored search suggestion placeholder")
106         val currentDate = LocalDate.now()
107         val currentTime = LocalTime.now()
109         val currentDay = currentDate.dayOfMonth.toString().padStart(2, '0')
110         val currentMonth = currentDate.monthValue.toString().padStart(2, '0')
111         val currentYear = currentDate.year.toString()
112         val currentHour = currentTime.hour.toString().padStart(2, '0')
114         Log.i(TAG, "getSponsoredFxSuggestPlaceHolder: Got: ${currentYear + currentMonth + currentDay + currentHour} as the sponsored search suggestion placeholder")
116         return currentYear + currentMonth + currentDay + currentHour
117     }
119     /**
120      * Returns sponsored shortcut title based on the index.
121      */
122     fun getSponsoredShortcutTitle(position: Int): String {
123         Log.i(TAG, "getSponsoredShortcutTitle: Trying to get the title of the sponsored shortcut at position: ${position - 1}")
124         val sponsoredShortcut = mDevice.findObject(
125             UiSelector()
126                 .resourceId("${TestHelper.packageName}:id/top_site_item")
127                 .index(position - 1),
128         ).getChild(
129             UiSelector()
130                 .resourceId("${TestHelper.packageName}:id/top_site_title"),
131         ).text
132         Log.i(TAG, "getSponsoredShortcutTitle: The sponsored shortcut at position: ${position - 1} has title: $sponsoredShortcut")
133         return sponsoredShortcut
134     }
136     /**
137      * The list of Search engines for the "home" region of the user.
138      * For en-us it will return the 6 engines selected by default: Google, Bing, DuckDuckGo, Amazon, Ebay, Wikipedia.
139      */
140     fun getRegionSearchEnginesList(): List<SearchEngine> {
141         Log.i(TAG, "getRegionSearchEnginesList: Trying to get the search engines based on the region of the user")
142         val searchEnginesList = appContext.components.core.store.state.search.regionSearchEngines
143         Assert.assertTrue("$TAG: Search engines list returned nothing", searchEnginesList.isNotEmpty())
144         Log.i(TAG, "getRegionSearchEnginesList: Got $searchEnginesList based on the region of the user")
145         return searchEnginesList
146     }
148     /**
149      * The list of Search engines available to be added by user choice.
150      * For en-us it will return the 2 engines: Reddit, Youtube.
151      */
152     fun getAvailableSearchEngines(): List<SearchEngine> {
153         Log.i(TAG, "getAvailableSearchEngines: Trying to get the alternative search engines based on the region of the user")
154         val searchEnginesList = TestHelper.appContext.components.core.store.state.search.availableSearchEngines
155         Assert.assertTrue("$TAG: Search engines list returned nothing", searchEnginesList.isNotEmpty())
156         Log.i(TAG, "getAvailableSearchEngines: Got $searchEnginesList based on the region of the user")
157         return searchEnginesList
158     }