Fake Context Wrapper for vRO actions
A possible method how to run vRO actions requiring System Context
We have some vRO actions using System.getContext()
to collect current running parameters ie. tenant, request id etc. They are mostly used on vRA custom forms to provide context sensitive dropdowns. The following cases are some examples when context is not available and the actions fail to run correctly:
- XaaS forms
- Running actions from vRO workflows directly, without vRA
- automated testing
Possible solutions
Duplicate
You can copy the action, add the required context parameters as inputs and bind the input parameters. This will lead to code duplication and double maintain effort.
Refactor
You can move the code to another action with input parameters. Your original action will still fetch the context and call the new action providing the input via parameters. You can use the new action when no context is available directly.
Action wrapper code
The third method, that I want to demonstrate, is about writing some wrapper code to create a fake context for the original action. This is useful when you do not want or cannot change the original action, but want to use it without duplication.
Sample action
For demonstation purposes let's have a getOptions action with the output of sting array:
1var tenant = System.getContext().getParameter('__asd_tenantRef');
2System.log(tenant);
3
4if (!tenant) return [];
5if ("prod" == tenant) return ["PR1", "PR2"];
6return ["D1", "D2"];
This can be used as an external source of a custom form dropdown: will provide different values for prod and non-prod tenants:
The same code fails to get tenant name on an XaaS blueprint:
The wrapper code
This is the wrapper action getOptionsWrapper with an input parameter tenant
:
1// define context values
2var params = {
3 __asd_tenantRef: tenant,
4}
5
6// define object and functions
7var fakeContext = {
8 getParameter: function (param) {
9 return params[param];
10 },
11 parameterNames: function () {
12 return Object.keys(params);
13 }
14}
15
16// override getContext()
17System.getContext = function () {
18 return fakeContext;
19}
20
21return System.getModule("com.test.dropdowns").getOptions();
The code overrides the System.getContext()
JavaScript function with a function returning fake context information.
The input parameter can be bound in the XaaS form. Now it works fine:
A simple unit test workflow script with a similar code:
1// define context values
2var params = {
3 __asd_tenantRef: "dev",
4}
5
6// define object and functions
7var fakeContext = {
8 getParameter: function (param) {
9 return params[param];
10 },
11 parameterNames: function () {
12 return Object.keys(params);
13 }
14}
15
16// override getContext()
17System.getContext = function () {
18 return fakeContext;
19}
20
21var options = System.getModule("com.test.dropdowns").getOptions();
22if ('["D1","D2"]' != JSON.stringify(options))
23 throw "getOptions action test failure";