summaryrefslogtreecommitdiff
path: root/google-login-plugin/testSrc/com/google/gct/login2/settings/GoogleLoginApplicationSettingsConfigurableUiTest.kt
blob: c99072bcca35ff837a49e4de7de822d0682bf76b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
/*
 * Copyright (C) 2023 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.gct.login2.settings

import com.android.flags.junit.FlagRule
import com.android.testutils.ImageDiffUtil
import com.android.testutils.MockitoKt.mock
import com.android.testutils.TestUtils
import com.android.testutils.waitForCondition
import com.android.tools.adtui.stdui.EmptyStatePanel
import com.android.tools.adtui.swing.HeadlessDialogRule
import com.android.tools.adtui.swing.createModalDialogAndInteractWithIt
import com.android.tools.adtui.swing.findDescendant
import com.android.tools.idea.flags.StudioFlags
import com.android.tools.idea.testing.ui.flatten
import com.google.common.truth.Truth.assertThat
import com.google.gct.login2.CredentialedUser
import com.google.gct.login2.FakeLoginFeature
import com.google.gct.login2.LoginFeature
import com.google.gct.login2.LoginFeatureRule
import com.google.gct.login2.LoginUsersRule
import com.intellij.ide.DataManager
import com.intellij.ide.impl.HeadlessDataManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.util.Disposer
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.EdtRule
import com.intellij.testFramework.RunsInEdt
import com.intellij.testFramework.TestActionEvent
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.ToolbarDecorator
import com.intellij.ui.components.AnActionLink
import com.intellij.ui.components.BrowserLink
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBList
import icons.GoogleLoginIcons
import java.awt.Color
import java.awt.GradientPaint
import java.awt.Graphics2D
import java.awt.image.BufferedImage
import java.util.concurrent.TimeUnit
import javax.swing.DefaultListModel
import javax.swing.JButton
import javax.swing.JComponent
import kotlin.time.Duration.Companion.seconds
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain

class GoogleLoginApplicationSettingsConfigurableUiTest {
  private val loginFeatureRule = LoginFeatureRule()
  private val disposableRule = DisposableRule()
  private val loginUsersRule = LoginUsersRule()

  @get:Rule
  val chain =
    RuleChain.outerRule(FlagRule(StudioFlags.ENABLE_SETTINGS_ACCOUNT_UI, true))
      .around(EdtRule())
      .around(ApplicationRule())
      .around(HeadlessDialogRule())
      .around(loginFeatureRule)
      .around(loginUsersRule)
      .around(disposableRule)!!

  private val TEST_DATA_ROOT =
    TestUtils.resolveWorkspacePath("tools/studio/google/cloud/tools/google-login-plugin/testData")

  @RunsInEdt
  @Test
  fun testEmptyState() {
    val panel =
      GoogleLoginApplicationSettingsConfigurableUi()
        .also { Disposer.register(disposableRule.disposable, it) }
        .component
        .findDescendant<EmptyStatePanel>()!!

    waitForCondition(1, TimeUnit.SECONDS) { panel.isVisible }
    assertThat(panel.reasonText)
      .isEqualTo(
        "No Google accounts added " +
          "Add a Google account to start using features like Studio Bot, Firebase Direct " +
          "Access, and App Quality Insights with Crashlytics."
      )
  }

  @RunsInEdt
  @Test
  fun testUserModel() {
    loginUsersRule.setActiveUser("user1")
    loginUsersRule.setActiveUser("user2")
    val list =
      GoogleLoginApplicationSettingsConfigurableUi()
        .also { Disposer.register(disposableRule.disposable, it) }
        .createUserListPanel()
        .findDescendant<JBList<CredentialedUser>>()!!

    executeInModalDialog(list) {
      val model = list.model as DefaultListModel
      assertThat(model.elements().toList().map { it.email }).containsExactly("user1", "user2")

      loginUsersRule.logOut("user2")
      loginUsersRule.setActiveUser("user3")

      waitForCondition(1, TimeUnit.SECONDS) {
        (list.model as DefaultListModel).elements().toList().map { it.email }.contains("user3")
      }
      assertThat((list.model as DefaultListModel).elements().toList().map { it.email })
        .containsExactly("user1", "user3")
    }
  }

  @Test
  fun testUserIcons() {
    val userImage = BufferedImage(220, 220, BufferedImage.TYPE_INT_ARGB)
    (userImage.graphics as Graphics2D).run {
      paint = GradientPaint(0f, 0f, Color.RED, 220f, 220f, Color.BLUE)
      fillRect(0, 0, 220, 220)
    }
    val configurable =
      GoogleLoginApplicationSettingsConfigurableUi().also {
        Disposer.register(disposableRule.disposable, it)
      }
    val icon = configurable.getOrCreateAvatar(userImage, mock())
    val image = BufferedImage(icon.iconWidth, icon.iconHeight, BufferedImage.TYPE_INT_ARGB)
    icon.paintIcon(mock(), image.createGraphics(), 0, 0)
    ImageDiffUtil.assertImageSimilar(TEST_DATA_ROOT.resolve("user.png"), image, 0.1)

    val icon2 = configurable.getOrCreateAvatar(userImage, mock())
    assertThat(icon2).isSameAs(icon)

    assertThat(configurable.getOrCreateAvatar(null, mock()))
      .isSameAs(GoogleLoginIcons.LOGGED_OUT_USER_AVATAR)
  }

  @RunsInEdt
  @Test
  fun testSwitchUser() {
    HeadlessDataManager.fallbackToProductionDataManager(disposableRule.disposable)
    loginUsersRule.setActiveUser("user1")
    loginUsersRule.setActiveUser("user3")
    loginUsersRule.setActiveUser("user2")

    val list: JBList<CredentialedUser> =
      GoogleLoginApplicationSettingsConfigurableUi()
        .also { Disposer.register(disposableRule.disposable, it) }
        .createUserListPanel()
        .findDescendant<JBList<CredentialedUser>> { true }!!

    executeInModalDialog(list) {
      // Expected list content: user2, user1, user3
      list.selectedIndex = 1 // select user1
      waitForCondition(1, TimeUnit.SECONDS) { list.selectedValue?.email == "user1" }
      val createEvent = {
        TestActionEvent.createTestEvent(DataManager.getInstance().getDataContext(list))
      }

      // Verify that the action is enabled if the inactive user is selected
      createEvent().also { event ->
        event.presentation.isEnabled = false
        SwitchUserAction.update(event)
        assertThat(event.presentation.isEnabled).isTrue()
      }

      // Verify that the action is disabled if the active user is selected
      list.selectedIndex = 0 // select user2
      createEvent().also { event ->
        SwitchUserAction.update(event)
        assertThat(event.presentation.isEnabled).isFalse()
      }

      // Check that the action switches the active user
      list.selectedIndex = 1 // select user1
      createEvent().also { event ->
        SwitchUserAction.actionPerformed(event)
        assertThat(loginUsersRule.loginService.activeUserFlow.value!!.email).isEqualTo("user1")
      }
    }
  }

  @RunsInEdt
  @Test
  fun testLogin() {
    HeadlessDataManager.fallbackToProductionDataManager(disposableRule.disposable)
    val panel =
      GoogleLoginApplicationSettingsConfigurableUi()
        .also { Disposer.register(disposableRule.disposable, it) }
        .createUserListPanel()
    executeInModalDialog(panel) {
      val addButton = ToolbarDecorator.findAddButton(panel)!!
      addButton.actionPerformed(
        TestActionEvent.createTestEvent(DataManager.getInstance().getDataContext(panel))
      )
      waitForCondition(1.seconds) { loginUsersRule.loginService.activeUserFlow.value != null }
    }
  }

  @RunsInEdt
  @Test
  fun testLogout() {
    HeadlessDataManager.fallbackToProductionDataManager(disposableRule.disposable)
    val list: JBList<CredentialedUser> =
      GoogleLoginApplicationSettingsConfigurableUi()
        .also { Disposer.register(disposableRule.disposable, it) }
        .createUserListPanel()
        .findDescendant<JBList<CredentialedUser>>()!!

    executeInModalDialog(list) {
      val createEvent = {
        TestActionEvent.createTestEvent(DataManager.getInstance().getDataContext(list))
      }

      // Verify that the action is disabled if there are no users logged in
      createEvent().also { event ->
        event.presentation.isEnabled = true
        LogoutAction.update(event)
        assertThat(event.presentation.isEnabled).isFalse()
      }

      var selectionCount = 0
      list.addListSelectionListener {
        // If we're getting in here more than once it's a sign that there might be more flakiness
        // coming
        assertThat(selectionCount++).isEqualTo(0)
      }

      loginUsersRule.setActiveUser("user1")
      loginUsersRule.setActiveUser("user2")

      waitForCondition(1, TimeUnit.SECONDS) { list.model.size == 2 }
      // Expected list content: user2, user1
      list.selectedIndex = 0 // select user2
      waitForCondition(1, TimeUnit.SECONDS) { list.selectedValue?.email == "user2" }

      // Verify that the action is enabled if there are users logged in
      createEvent().also { event ->
        LogoutAction.update(event)
        assertThat(event.presentation.isEnabled).isTrue()
      }

      // Check that the action calls logout
      createEvent().also { event ->
        LogoutAction.actionPerformed(event)
        waitForCondition(1.seconds) {
          "user2" !in loginUsersRule.loginService.allUsersFlow.value.keys
        }
      }
    }
  }

  @RunsInEdt
  @Test
  fun testFeaturePanel() {
    (LoginFeature.getExtensionByName("test_feature_1") as FakeLoginFeature).apply {
      description = "this is test feature 1"
      infoUrl = "http://example.com/feature1"
      infoUrlDisplayText = "Here's URL 1"
    }
    val feature2Action =
      object : AnAction("Feature 2 Action") {
        override fun actionPerformed(e: AnActionEvent) {}
      }
    (LoginFeature.getExtensionByName("test_feature_2") as FakeLoginFeature).apply {
      description = "this is test feature 2"
      settingsAction = feature2Action
    }

    val component =
      GoogleLoginApplicationSettingsConfigurableUi()
        .also { Disposer.register(disposableRule.disposable, it) }
        .component
    val feature1panel = component.flatten().single { it.name == "test_feature_1 panel" }
    val feature2panel = component.flatten().single { it.name == "test_feature_2 panel" }

    executeInModalDialog(component) {
      val title = feature1panel.flatten().filterIsInstance<SimpleColoredComponent>().first()
      assertThat(title.toString()).isEqualTo("test_feature_1")

      val description = feature1panel.flatten().filterIsInstance<JBLabel>().first()
      // description text isn't set until there's a resize event
      description.componentListeners.forEach { it.componentResized(null) }
      assertThat(description.text)
        .isEqualTo(
          "<html><body><div style='color:#808080;width:250px'>this is test feature 1</div></body></html>"
        )

      val enableButton1 = feature1panel.flatten().filterIsInstance<JButton>().first()
      assertThat(enableButton1.text).isEqualTo("Allow")

      val feature1Link = feature1panel.flatten().filterIsInstance<BrowserLink>().first()
      assertThat(feature1Link.text).isEqualTo("Here's URL 1")
      assertThat(feature1Link.url).isEqualTo("http://example.com/feature1")

      val title2 = feature2panel.flatten().filterIsInstance<SimpleColoredComponent>().first()
      assertThat(title2.toString()).isEqualTo("test_feature_2")

      val description2 = feature2panel.flatten().filterIsInstance<JBLabel>().first()
      // description text isn't set until there's a resize event
      description2.componentListeners.forEach { it.componentResized(null) }
      assertThat(description2.text)
        .isEqualTo(
          "<html><body><div style='color:#808080;width:250px'>this is test feature 2</div></body></html>"
        )

      val enableButton2 = feature2panel.flatten().filterIsInstance<JButton>().first()
      assertThat(enableButton2.text).isEqualTo("Allow")

      val feature2Link = feature2panel.flatten().filterIsInstance<AnActionLink>().first()
      assertThat(feature2Link.text).isEqualTo("Feature 2 Action")
    }
  }

  private fun executeInModalDialog(component: JComponent, body: () -> Unit) {
    // Create a dialog so the code is executed in a modal context
    val dialog =
      object : DialogWrapper(true) {
        override fun createCenterPanel() = component
      }
    createModalDialogAndInteractWithIt({ dialog.show() }) { body() }
  }
}