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
package social.grain
import android.net.Uri
import androidx.test.ext.junit.runners.AndroidJUnit4
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withTimeoutOrNull
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import social.grain.data.auth.SecureStore
import social.grain.data.local.Appearance
import social.grain.data.local.AppearanceStore
import social.grain.data.push.PushManager
import social.grain.data.upload.GalleryDraftStore
import social.grain.data.upload.GalleryUploadCenter
import social.grain.data.version.UpdateGate
import social.grain.feature.notifications.UnseenNotificationCount
import social.grain.navigation.DeepLink
import social.grain.support.callback
import social.grain.support.stubSignIn
import social.grain.support.Fixtures
import social.grain.support.Harness
import social.grain.support.MainDispatcherRule
import social.grain.support.appContext
import social.grain.support.awaitCall
import social.grain.support.awaitValue
import social.grain.support.json
import social.grain.support.settle
import social.grain.support.testJson
/**
* The pieces that outlive any one screen.
*
* The OAuth callback in particular can't live on the login screen — the
* redirect is delivered to the Activity, by which time that screen's view model
* may be gone — and a deep link tapped before sign-in has to survive it rather
* than being dropped.
*/
@RunWith(AndroidJUnit4::class)
class MainViewModelTest {
@get:Rule
val mainDispatcher = MainDispatcherRule()
private lateinit var harness: Harness
private lateinit var appearance: AppearanceStore
@Before
fun setUp() {
harness = Harness()
appearance = AppearanceStore(appContext)
appearance.set(Appearance.AUTOMATIC)
harness.server
.on(
"social.grain.actor.getProfile",
json(
Fixtures.profileDetailed(
did = harness.did,
handle = "renamed.grain.social",
),
),
)
.on("social.grain.notification.getUnreadCount", """{"count":3}""")
}
@After
fun tearDown() {
appearance.set(Appearance.AUTOMATIC)
harness.tearDown()
}
private fun viewModel(): MainViewModel {
val uploads = GalleryUploadCenter(appContext, GalleryDraftStore(appContext, testJson))
return MainViewModel(
auth = harness.auth,
client = harness.client,
uploadCenter = uploads,
feedCache = harness.feedCache,
unseenNotifications = UnseenNotificationCount(
appContext,
harness.client,
harness.auth,
),
recentSearches = harness.recentSearches,
push = PushManager(
appContext,
harness.client,
harness.auth,
SecureStore(appContext),
harness.scope,
),
storyStatusCache = harness.storyStatus,
viewedStories = harness.viewedStories,
appearanceStore = appearance,
updateGate = UpdateGate(
prefs = appContext.getSharedPreferences(UpdateGate.PREFS_NAME, android.content.Context.MODE_PRIVATE),
http = harness.server.client(),
json = testJson,
baseUrl = harness.client.baseUrl,
versionCode = 13,
),
)
}
@Test
fun signingInPullsTheOwnProfileSoSelfAvatarsAreNotPlaceholders() {
val model = viewModel()
harness.server.awaitCall("social.grain.actor.getProfile")
model.authState.awaitValue("the resolved handle") {
it.handle == "renamed.grain.social"
}
assertEquals(
"https://cdn.grain.test/avatar/renamed.grain.social.jpg",
harness.auth.state.value.avatar,
)
}
@Test
fun theProfileIsPulledOnceRatherThanOnEveryStateChange() {
viewModel()
harness.server.awaitCall("social.grain.actor.getProfile")
settle()
Thread.sleep(400)
assertEquals(
"Storing the avatar re-emits the auth state; that must not loop",
1,
harness.server.countOf("social.grain.actor.getProfile"),
)
}
@Test
fun theBadgeIsFilledInFromTheCheapPollOnLaunch() {
val model = viewModel()
model.unseenCount.awaitValue("the badge") { it == 3 }
}
@Test
fun theAppearanceChoiceIsPublishedForTheWholeApp() {
val model = viewModel()
assertEquals(Appearance.AUTOMATIC, model.appearance.value)
appearance.set(Appearance.DARK)
assertEquals(Appearance.DARK, model.appearance.value)
}
@Test
fun storyRingsAreAssembledFromWhoHasOneAndWhatHasBeenWatched() {
val model = viewModel()
harness.storyStatus.update(
listOf(Fixtures.storyAuthor(profile = Fixtures.profile(did = "did:plc:alice"))),
)
val presence = runBlocking {
withTimeoutOrNull(5_000) {
model.storyPresence.first { it.hasStory("did:plc:alice") }
}
}
assertTrue("Alice's ring lights up", presence!!.hasStory("did:plc:alice"))
assertFalse("Nothing watched yet, so it isn't grey", presence.isCaughtUp("did:plc:alice"))
}
@Test
fun aLinkIsHeldUntilSomethingNavigatesToIt() {
val model = viewModel()
val link = DeepLink.Profile("alice.grain.social")
model.onDeepLink(link)
assertEquals(link, model.pendingDeepLink.value)
model.consumeDeepLink()
assertNull("A consumed link must not replay", model.pendingDeepLink.value)
}
@Test
fun aDeniedSignInIsACancellationRatherThanAnErrorToShow() {
harness.server.stubSignIn()
val model = viewModel()
runBlocking { harness.auth.beginLogin("me.grain.social") }
model.handleOAuthCallback(harness.server.callback(code = null, extra = "error=access_denied"))
settle()
Thread.sleep(300)
assertNull(model.signInError.value)
}
@Test
fun aSignInSeedsTheProfileInTheBackgroundAndNeverFailsByIt() {
harness.server.stubSignIn()
.on(
"token",
"""{"access_token":"a1","refresh_token":"r1","expires_in":3600,"sub":"${harness.did}","scope":"atproto"}""",
)
.on("com.atproto.repo.getRecord", """{"error":"InternalServerError"}""", code = 500)
val model = viewModel()
runBlocking { harness.auth.beginLogin("me.grain.social") }
model.handleOAuthCallback(harness.server.callback())
val call = harness.server.awaitCall("com.atproto.repo.getRecord")
assertEquals("social.grain.actor.profile", call.params["collection"])
settle()
Thread.sleep(200)
assertNull("A failed seed is no sign-in error", model.signInError.value)
assertTrue(harness.auth.state.value.isAuthenticated)
assertEquals(0, harness.server.countOf("com.atproto.repo.createRecord"))
}
@Test
fun anyOtherCallbackFailureIsSurfacedAndCanBeDismissed() {
harness.server.stubSignIn()
val model = viewModel()
runBlocking { harness.auth.beginLogin("me.grain.social") }
model.handleOAuthCallback(
harness.server.callback(code = null, extra = "error=server_error&error_description=Boom"),
)
model.signInError.awaitValue("the error") { it != null }
assertEquals("Boom", model.signInError.value)
model.dismissSignInError()
assertNull(model.signInError.value)
}
@Test
fun comingBackToTheAppReReadsTheBadge() {
val model = viewModel()
model.unseenCount.awaitValue("the badge") { it == 3 }
val before = harness.server.countOf("social.grain.notification.getUnreadCount")
harness.server.on(
"social.grain.notification.getUnreadCount",
"""{"count":9}""",
)
model.onForeground()
model.unseenCount.awaitValue("the refreshed badge") { it == 9 }
assertTrue(harness.server.countOf("social.grain.notification.getUnreadCount") > before)
}
@Test
fun signingOutFromAnywhereClearsTheSession() {
val model = viewModel()
model.authState.awaitValue("the session") { it.isAuthenticated }
model.signOut()
model.authState.awaitValue("the sign-out") { !it.isAuthenticated }
}
@Test
fun theUploadStageIsPublishedForTheResumeBanner() {
assertEquals(
social.grain.data.upload.UploadStage.Idle,
viewModel().uploadStage.value,
)
}
}