Revision bbc9fae4
Added by koszko over 1 year ago
test/haketilo_test/unit/utils.py | ||
---|---|---|
246 | 246 |
'Object.keys(broadcast).forEach(k => broadcast[k] = () => {});' |
247 | 247 |
) |
248 | 248 |
|
249 |
def mock_cacher(execute_in_page): |
|
250 |
""" |
|
251 |
Some parts of code depend on content/repo_query_cacher.js and |
|
252 |
background/CORS_bypass_server.js running in their appropriate contexts. This |
|
253 |
function modifies the relevant browser.runtime.sendMessage function to |
|
254 |
perform fetch(), bypassing the cacher. |
|
255 |
""" |
|
256 |
execute_in_page( |
|
257 |
'''{ |
|
258 |
const old_sendMessage = browser.tabs.sendMessage, old_fetch = fetch; |
|
259 |
async function new_sendMessage(tab_id, msg) { |
|
260 |
if (msg[0] !== "repo_query") |
|
261 |
return old_sendMessage(tab_id, msg); |
|
249 |
""" |
|
250 |
Some parts of code depend on content/repo_query_cacher.js and |
|
251 |
background/CORS_bypass_server.js running in their appropriate contexts. This |
|
252 |
snippet modifies the relevant browser.runtime.sendMessage function to perform |
|
253 |
fetch(), bypassing the cacher. |
|
254 |
""" |
|
255 |
mock_cacher_code = '''{ |
|
256 |
const uint8_to_hex = |
|
257 |
array => [...array].map(b => ("0" + b.toString(16)).slice(-2)).join(""); |
|
262 | 258 |
|
263 |
/* Use snapshotted fetch(), allow other test code to override it. */ |
|
264 |
const response = await old_fetch(msg[1]); |
|
265 |
if (!response) |
|
266 |
return {error: "Something happened :o"}; |
|
259 |
const old_sendMessage = browser.tabs.sendMessage; |
|
260 |
window.mock_cacher_fetch = fetch; |
|
261 |
browser.tabs.sendMessage = async function(tab_id, msg) { |
|
262 |
if (msg[0] !== "repo_query") |
|
263 |
return old_sendMessage(tab_id, msg); |
|
267 | 264 |
|
268 |
const result = {ok: response.ok, status: response.status}; |
|
269 |
try { |
|
270 |
result.json = await response.json(); |
|
271 |
} catch(e) { |
|
272 |
result.error_json = "" + e; |
|
273 |
} |
|
274 |
return result; |
|
265 |
/* |
|
266 |
* Use snapshotted fetch() under the name window.mock_cacher_fetch, |
|
267 |
* allow other test code to override it. |
|
268 |
*/ |
|
269 |
try { |
|
270 |
const response = await window.mock_cacher_fetch(msg[1]); |
|
271 |
const buf = await response.arrayBuffer(); |
|
272 |
return { |
|
273 |
status: response.status, |
|
274 |
statusText: response.statusText, |
|
275 |
headers: [...response.headers.entries()], |
|
276 |
body: uint8_to_hex(new Uint8Array(buf)) |
|
275 | 277 |
} |
276 |
|
|
277 |
browser.tabs.sendMessage = new_sendMessage; |
|
278 |
}''') |
|
278 |
} catch(e) { |
|
279 |
return {error: {name: e.name, message: e.message}}; |
|
280 |
} |
|
281 |
} |
|
282 |
}''' |
|
279 | 283 |
|
280 | 284 |
""" |
281 | 285 |
Convenience snippet of code to retrieve a copy of given object with only those |
Also available in: Unified diff
serialize and deserialize entire Response object when relaying fetch() calls to other contexts using sendMessage