Skip to content

Commit 338304d

Browse files
committed
test: a failed Auto-send settings read is drawn as the setting being off (#3367)
1 parent bab1fe9 commit 338304d

1 file changed

Lines changed: 208 additions & 0 deletions

File tree

Lines changed: 208 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,208 @@
1+
// A friend Bot's settings card reads the pair's Auto-send setting once, on mount, through
2+
// `social/settings`. Its rejection branch was an empty function, so a read that failed left the
3+
// checkbox at its initial `false` — drawn exactly like a setting that is off — while the switch
4+
// stayed live; the person then reads "my Bots' replies to Eve go out without asking" as the state
5+
// they chose. The failure is the card's answer while it lasts (#3323/#3325/#3359 fixed the same gap
6+
// for the friends list, the paused card and the approval cards): one quiet status row, and the switch
7+
// is not offered until the value is known, because a value nobody read is not a value to flip. A
8+
// remount (reopen the card) retries; no button, no new copy.
9+
//
10+
// The harness is the one `poll-visibility.test.js` uses: the client is a classic script, react is the
11+
// tiny hook runner the other client tests use, and `setInterval` / `visibilitychange` are recorded
12+
// instead of waited on (no jsdom). `rerender()` reuses the hook table and does not re-run effects.
13+
import assert from 'node:assert/strict'
14+
import { readFileSync } from 'node:fs'
15+
import { test } from 'node:test'
16+
17+
const live = { inst: null, idx: 0 }
18+
const reactStub = {
19+
createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity) }),
20+
Fragment: 'F',
21+
useState(init) {
22+
const inst = live.inst
23+
const i = live.idx++
24+
if (!(i in inst.hooks)) inst.hooks[i] = { value: typeof init === 'function' ? init() : init }
25+
const slot = inst.hooks[i]
26+
return [slot.value, next => { slot.value = typeof next === 'function' ? next(slot.value) : next; inst.dirty = true }]
27+
},
28+
useEffect(fn, deps) {
29+
live.inst.effects.push([live.idx++, fn, deps])
30+
},
31+
useRef(value) {
32+
const inst = live.inst
33+
const i = live.idx++
34+
if (!(i in inst.hooks)) inst.hooks[i] = { current: value }
35+
return inst.hooks[i]
36+
},
37+
useMemo(fn) { live.idx++; return fn() },
38+
useCallback(fn) { live.idx++; return fn },
39+
}
40+
41+
// The browser bundle registers its factory under its package name; load it the way the other client
42+
// tests do and hand the factory the hook stub above.
43+
function loadApp() {
44+
const modules = new Map()
45+
const window = { __ModuleLoader__: { load: entry => modules.set(entry.id, entry.factory) } }
46+
new Function('window', readFileSync(new URL('../client.js', import.meta.url), 'utf8'))(window)
47+
return modules.get('@flybot/social')(name => (name === 'react' ? reactStub : {}))
48+
}
49+
50+
// A document whose `hidden` can change and whose `visibilitychange` listeners the test fires, and a
51+
// timer table the test advances — both installed as globals for the duration of a case.
52+
function makeDocument({ hidden = false } = {}) {
53+
const listeners = new Map()
54+
return {
55+
hidden,
56+
getElementById: () => null,
57+
createElement: () => ({}),
58+
head: { appendChild() {} },
59+
addEventListener(type, fn) {
60+
const set = listeners.get(type) ?? new Set()
61+
set.add(fn)
62+
listeners.set(type, set)
63+
},
64+
removeEventListener(type, fn) { listeners.get(type)?.delete(fn) },
65+
listening: type => (listeners.get(type) ?? new Set()).size,
66+
emit(type) { for (const fn of [...(listeners.get(type) ?? [])]) fn() },
67+
}
68+
}
69+
function makeTimers() {
70+
let next = 0
71+
const timers = new Map()
72+
return {
73+
setInterval(fn, ms) { const id = `t${++next}`; timers.set(id, { fn, ms }); return id },
74+
clearInterval(id) { timers.delete(id) },
75+
periods: () => [...timers.values()].map(timer => timer.ms),
76+
tick() { for (const timer of [...timers.values()]) timer.fn() },
77+
}
78+
}
79+
80+
// One case: a fresh document, timer table, answer queue and module instance. Each `call` takes the next
81+
// queued answer; an `Error` in the queue is a rejection. `settle()` lets the promise chain land before
82+
// the next render, so a case never reads a half-updated card.
83+
function scene({ hidden = false, answers = [] } = {}) {
84+
const doc = makeDocument({ hidden })
85+
const timers = makeTimers()
86+
const calls = []
87+
const app = loadApp()
88+
const saved = {
89+
document: globalThis.document,
90+
setInterval: globalThis.setInterval,
91+
clearInterval: globalThis.clearInterval,
92+
flybot: globalThis.__flybot__,
93+
}
94+
let queued = [...answers]
95+
globalThis.document = doc
96+
globalThis.setInterval = timers.setInterval
97+
globalThis.clearInterval = timers.clearInterval
98+
globalThis.__flybot__ = {
99+
call: (endpoint, payload) => {
100+
calls.push([endpoint, payload])
101+
const answer = queued.length > 0 ? queued.shift() : {}
102+
return answer instanceof Error ? Promise.reject(answer) : Promise.resolve(answer)
103+
},
104+
canRetry: () => true,
105+
}
106+
return {
107+
doc, timers, calls, app,
108+
restore() {
109+
globalThis.document = saved.document
110+
globalThis.setInterval = saved.setInterval
111+
globalThis.clearInterval = saved.clearInterval
112+
globalThis.__flybot__ = saved.flybot
113+
},
114+
}
115+
}
116+
const settle = () => new Promise(resolve => setTimeout(resolve, 0))
117+
const unmount = cleanups => { for (const off of cleanups.reverse()) off() }
118+
119+
// React would run the first-mount effects after drawing; here that is the call site's own immediate
120+
// read plus its timer, which is exactly what the cases below observe.
121+
function mount(app, name, props) {
122+
live.inst = { hooks: {}, effects: [], dirty: false }
123+
live.idx = 0
124+
const out = app[name](props)
125+
const cleanups = []
126+
for (const [, fn] of live.inst.effects) {
127+
const off = fn()
128+
if (typeof off === 'function') cleanups.push(off)
129+
}
130+
return { out, cleanups }
131+
}
132+
// A state update asks React for a new render; this reuses the hook table and runs no effect again.
133+
function rerender(app, name, props) {
134+
live.idx = 0
135+
return app[name](props)
136+
}
137+
// Every element in a drawn tree, depth first, for counting what a state shows.
138+
function nodes(node, out = []) {
139+
if (node == null || node === false || node === true) return out
140+
if (typeof node === 'string' || typeof node === 'number') return out
141+
if (Array.isArray(node)) { for (const child of node) nodes(child, out); return out }
142+
if (typeof node !== 'object') return out
143+
out.push(node)
144+
nodes(node.children ?? [], out)
145+
return out
146+
}
147+
const byMark = (tree, mark) => nodes(tree).filter(node => node?.props?.['data-flybot'] === mark)
148+
const textOf = node => (Array.isArray(node?.children) ? node.children : [node?.children]).join('')
149+
150+
const friendBot = { id: 'f1', name: 'Eve', remote: { home: '@eve.home', handle: '@eve.bot', homeName: 'Eve' } }
151+
const settingsCard = app => mount(app, 'FriendChatSettings', { bot: friendBot })
152+
const switchOf = tree => nodes(byMark(tree, 'friend-auto-send')[0] ?? {}).find(node => node?.type === 'input')
153+
154+
test('a settings read that fails is drawn as a failure, not as a setting', async () => {
155+
const s = scene({ answers: [new Error('offline')] })
156+
try {
157+
const { cleanups, out } = settingsCard(s.app)
158+
await settle()
159+
const tree = rerender(s.app, 'FriendChatSettings', { bot: friendBot }, out)
160+
assert.equal(byMark(tree, 'friend-auto-read-error').length, 1, 'the failed read is the card’s answer')
161+
unmount(cleanups)
162+
} finally { s.restore() }
163+
})
164+
165+
test('a NETWORK failure names the reason the users can act on', async () => {
166+
const s = scene({ answers: [Object.assign(new Error('offline'), { code: 'NETWORK' })] })
167+
try {
168+
const { cleanups, out } = settingsCard(s.app)
169+
await settle()
170+
const tree = rerender(s.app, 'FriendChatSettings', { bot: friendBot }, out)
171+
assert.equal(textOf(byMark(tree, 'friend-auto-read-error')[0]), 'Could not reach FlyBot. Check that it is still running.')
172+
unmount(cleanups)
173+
} finally { s.restore() }
174+
})
175+
176+
test('a setting nobody read is not offered as a switch to flip', async () => {
177+
const s = scene({ answers: [new Error('offline')] })
178+
try {
179+
const { cleanups, out } = settingsCard(s.app)
180+
await settle()
181+
const tree = rerender(s.app, 'FriendChatSettings', { bot: friendBot }, out)
182+
assert.equal(switchOf(tree).props.disabled, true, 'an unknown setting is not a checkbox')
183+
unmount(cleanups)
184+
} finally { s.restore() }
185+
})
186+
187+
test('a read that says the setting is on still draws a checked switch', async () => {
188+
const s = scene({ answers: [{ autoAccept: { '@eve.home': true } }] })
189+
try {
190+
const { cleanups, out } = settingsCard(s.app)
191+
await settle()
192+
const tree = rerender(s.app, 'FriendChatSettings', { bot: friendBot }, out)
193+
assert.equal(switchOf(tree).props.checked, true, 'on is drawn as on')
194+
assert.equal(byMark(tree, 'friend-auto-read-error').length, 0, 'a read that answered draws no failure')
195+
unmount(cleanups)
196+
} finally { s.restore() }
197+
})
198+
199+
test('a read that says the setting is off still draws an unchecked switch', async () => {
200+
const s = scene({ answers: [{ autoAccept: { '@eve.home': false } }] })
201+
try {
202+
const { cleanups, out } = settingsCard(s.app)
203+
await settle()
204+
const tree = rerender(s.app, 'FriendChatSettings', { bot: friendBot }, out)
205+
assert.equal(switchOf(tree).props.checked, false, 'off is drawn as off')
206+
unmount(cleanups)
207+
} finally { s.restore() }
208+
})

0 commit comments

Comments
 (0)