From 9cb48bd8fe8ee1d7c728c0de54c3bd5e728b6a8c Mon Sep 17 00:00:00 2001 From: Casper Beyer Date: Wed, 14 Jul 2021 06:11:02 +0800 Subject: [PATCH] refactor(runtime): apply permissions as a hook during registration (#11347) --- runtime/js/40_testing.js | 53 +++++++++++++++++++++++----------------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/runtime/js/40_testing.js b/runtime/js/40_testing.js index 4ee863ee71..0d4c231209 100644 --- a/runtime/js/40_testing.js +++ b/runtime/js/40_testing.js @@ -105,6 +105,29 @@ finishing test case.`; }; } + function withPermissions(fn, permissions) { + function pledgePermissions(permissions) { + return core.opSync( + "op_pledge_test_permissions", + parsePermissions(permissions), + ); + } + + function restorePermissions(token) { + core.opSync("op_restore_test_permissions", token); + } + + return async function applyPermissions() { + const token = pledgePermissions(permissions); + + try { + await fn(); + } finally { + restorePermissions(token); + } + }; + } + const tests = []; // Main test function provided by Deno, as you can see it merely @@ -153,6 +176,13 @@ finishing test case.`; testDef.fn = assertExit(testDef.fn); } + if (testDef.permissions) { + testDef.fn = withPermissions( + testDef.fn, + parsePermissions(testDef.permissions), + ); + } + ArrayPrototypePush(tests, testDef); } @@ -180,37 +210,16 @@ finishing test case.`; }; } - function pledgeTestPermissions(permissions) { - return core.opSync( - "op_pledge_test_permissions", - parsePermissions(permissions), - ); - } - - function restoreTestPermissions(token) { - core.opSync("op_restore_test_permissions", token); - } - - async function runTest({ ignore, fn, permissions }) { + async function runTest({ ignore, fn }) { if (ignore) { return "ignored"; } - let token = null; - try { - if (permissions) { - token = pledgeTestPermissions(permissions); - } await fn(); - return "ok"; } catch (error) { return { "failed": inspectArgs([error]) }; - } finally { - if (token) { - restoreTestPermissions(token); - } } }