Get rid of some global variables - Part 9

* Replace the following global variables with named imports:
  - Gerrit._pluginLoader
  - Gerrit._endpoints
* Update gr-app-global-var-init.js
* Move reset plugins function to test-utils.js

Note: This is not a recommended approach. pluginLoader and endpoints must be
moved to appContext (see todo in the files gr-plugin-loader.js and
gr-plugin-endpoints.js)

Change-Id: Ifc3454c293fc19830f12088168e83748f67d7cff
This commit is contained in:
Dmitrii Filippov
2020-04-07 09:59:22 +02:00
parent 2b461f66a7
commit f97fc6e320
25 changed files with 293 additions and 261 deletions

View File

@@ -35,6 +35,7 @@ import '../../../test/common-test-setup.js';
import './gr-admin-view.js'; import './gr-admin-view.js';
import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js'; import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js';
import {GerritNav} from '../../core/gr-navigation/gr-navigation.js'; import {GerritNav} from '../../core/gr-navigation/gr-navigation.js';
import {pluginLoader} from '../../shared/gr-js-api-interface/gr-plugin-loader.js';
suite('gr-admin-view tests', () => { suite('gr-admin-view tests', () => {
let element; let element;
@@ -49,7 +50,7 @@ suite('gr-admin-view tests', () => {
}, },
}); });
const pluginsLoaded = Promise.resolve(); const pluginsLoaded = Promise.resolve();
sandbox.stub(Gerrit, 'awaitPluginsLoaded').returns(pluginsLoaded); sandbox.stub(pluginLoader, 'awaitPluginsLoaded').returns(pluginsLoaded);
pluginsLoaded.then(() => flush(done)); pluginsLoaded.then(() => flush(done));
}); });

View File

@@ -38,6 +38,7 @@ import {PathListBehavior} from '../../../behaviors/gr-path-list-behavior/gr-path
import {URLEncodingBehavior} from '../../../behaviors/gr-url-encoding-behavior/gr-url-encoding-behavior.js'; import {URLEncodingBehavior} from '../../../behaviors/gr-url-encoding-behavior/gr-url-encoding-behavior.js';
import {RESTClientBehavior} from '../../../behaviors/rest-client-behavior/rest-client-behavior.js'; import {RESTClientBehavior} from '../../../behaviors/rest-client-behavior/rest-client-behavior.js';
import {GerritNav} from '../../core/gr-navigation/gr-navigation.js'; import {GerritNav} from '../../core/gr-navigation/gr-navigation.js';
import {pluginEndpoints} from '../../shared/gr-js-api-interface/gr-plugin-endpoints.js';
const CHANGE_SIZE = { const CHANGE_SIZE = {
XS: 10, XS: 10,
@@ -99,7 +100,7 @@ class GrChangeListItem extends mixinBehaviors( [
attached() { attached() {
super.attached(); super.attached();
Gerrit.awaitPluginsLoaded().then(() => { Gerrit.awaitPluginsLoaded().then(() => {
this._dynamicCellEndpoints = Gerrit._endpoints.getDynamicEndpoints( this._dynamicCellEndpoints = pluginEndpoints.getDynamicEndpoints(
'change-list-item-cell'); 'change-list-item-cell');
}); });
} }

View File

@@ -36,6 +36,7 @@ import {URLEncodingBehavior} from '../../../behaviors/gr-url-encoding-behavior/g
import {KeyboardShortcutBehavior} from '../../../behaviors/keyboard-shortcut-behavior/keyboard-shortcut-behavior.js'; import {KeyboardShortcutBehavior} from '../../../behaviors/keyboard-shortcut-behavior/keyboard-shortcut-behavior.js';
import {RESTClientBehavior} from '../../../behaviors/rest-client-behavior/rest-client-behavior.js'; import {RESTClientBehavior} from '../../../behaviors/rest-client-behavior/rest-client-behavior.js';
import {GerritNav} from '../../core/gr-navigation/gr-navigation.js'; import {GerritNav} from '../../core/gr-navigation/gr-navigation.js';
import {pluginEndpoints} from '../../shared/gr-js-api-interface/gr-plugin-endpoints.js';
const NUMBER_FIXED_COLUMNS = 3; const NUMBER_FIXED_COLUMNS = 3;
const CLOSED_STATUS = ['MERGED', 'ABANDONED']; const CLOSED_STATUS = ['MERGED', 'ABANDONED'];
@@ -177,7 +178,7 @@ class GrChangeList extends mixinBehaviors( [
attached() { attached() {
super.attached(); super.attached();
Gerrit.awaitPluginsLoaded().then(() => { Gerrit.awaitPluginsLoaded().then(() => {
this._dynamicHeaderEndpoints = Gerrit._endpoints.getDynamicEndpoints( this._dynamicHeaderEndpoints = pluginEndpoints.getDynamicEndpoints(
'change-list-header'); 'change-list-header');
}); });
} }

View File

@@ -35,6 +35,7 @@ import '../../../test/common-test-setup.js';
import './gr-change-actions.js'; import './gr-change-actions.js';
import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js'; import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js';
import {GerritNav} from '../../core/gr-navigation/gr-navigation.js'; import {GerritNav} from '../../core/gr-navigation/gr-navigation.js';
import {pluginLoader} from '../../shared/gr-js-api-interface/gr-plugin-loader.js';
const CHERRY_PICK_TYPES = { const CHERRY_PICK_TYPES = {
SINGLE_CHANGE: 1, SINGLE_CHANGE: 1,
TOPIC: 2, TOPIC: 2,
@@ -98,7 +99,8 @@ suite('gr-change-actions tests', () => {
}); });
sandbox = sinon.sandbox.create(); sandbox = sinon.sandbox.create();
sandbox.stub(Gerrit, 'awaitPluginsLoaded').returns(Promise.resolve()); sandbox.stub(pluginLoader, 'awaitPluginsLoaded')
.returns(Promise.resolve());
element = fixture('basic'); element = fixture('basic');
element.change = {}; element.change = {};
@@ -1987,7 +1989,8 @@ suite('gr-change-actions tests', () => {
}); });
sandbox = sinon.sandbox.create(); sandbox = sinon.sandbox.create();
sandbox.stub(Gerrit, 'awaitPluginsLoaded').returns(Promise.resolve()); sandbox.stub(pluginLoader, 'awaitPluginsLoaded')
.returns(Promise.resolve());
element = fixture('basic'); element = fixture('basic');
// getChangeRevisionActions is not called without // getChangeRevisionActions is not called without

View File

@@ -41,6 +41,9 @@ import '../../../test/common-test-setup.js';
import '../../plugins/gr-plugin-host/gr-plugin-host.js'; import '../../plugins/gr-plugin-host/gr-plugin-host.js';
import './gr-change-metadata.js'; import './gr-change-metadata.js';
import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js'; import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js';
import {resetPlugins} from '../../../test/test-utils.js';
import {pluginLoader} from '../../shared/gr-js-api-interface/gr-plugin-loader.js';
suite('gr-change-metadata integration tests', () => { suite('gr-change-metadata integration tests', () => {
let sandbox; let sandbox;
let element; let element;
@@ -87,7 +90,7 @@ suite('gr-change-metadata integration tests', () => {
teardown(() => { teardown(() => {
sandbox.restore(); sandbox.restore();
Gerrit._testOnly_resetPlugins(); resetPlugins();
}); });
suite('by default', () => { suite('by default', () => {
@@ -105,7 +108,7 @@ suite('gr-change-metadata integration tests', () => {
suite('with plugin style', () => { suite('with plugin style', () => {
setup(done => { setup(done => {
Gerrit._testOnly_resetPlugins(); resetPlugins();
const pluginHost = fixture('plugin-host'); const pluginHost = fixture('plugin-host');
pluginHost.config = { pluginHost.config = {
plugin: { plugin: {
@@ -118,7 +121,7 @@ suite('gr-change-metadata integration tests', () => {
}; };
element = createElement(); element = createElement();
const importSpy = sandbox.spy(element.$.externalStyle, '_import'); const importSpy = sandbox.spy(element.$.externalStyle, '_import');
Gerrit.awaitPluginsLoaded().then(() => { pluginLoader.awaitPluginsLoaded().then(() => {
Promise.all(importSpy.returnValues).then(() => { Promise.all(importSpy.returnValues).then(() => {
flush(done); flush(done);
}); });
@@ -139,8 +142,8 @@ suite('gr-change-metadata integration tests', () => {
Gerrit.install(p => plugin = p, '0.1', Gerrit.install(p => plugin = p, '0.1',
new URL('test/plugin.html?' + Math.random(), new URL('test/plugin.html?' + Math.random(),
window.location.href).toString()); window.location.href).toString());
sandbox.stub(Gerrit, '_arePluginsLoaded').returns(true); sandbox.stub(pluginLoader, 'arePluginsLoaded').returns(true);
Gerrit._loadPlugins([]); pluginLoader.loadPlugins([]);
element = createElement(); element = createElement();
}); });

View File

@@ -61,6 +61,8 @@ import {GrEditConstants} from '../../edit/gr-edit-constants.js';
import {GrCountStringFormatter} from '../../shared/gr-count-string-formatter/gr-count-string-formatter.js'; import {GrCountStringFormatter} from '../../shared/gr-count-string-formatter/gr-count-string-formatter.js';
import {util} from '../../../scripts/util.js'; import {util} from '../../../scripts/util.js';
import {GerritNav} from '../../core/gr-navigation/gr-navigation.js'; import {GerritNav} from '../../core/gr-navigation/gr-navigation.js';
import {pluginEndpoints} from '../../shared/gr-js-api-interface/gr-plugin-endpoints.js';
import {pluginLoader} from '../../shared/gr-js-api-interface/gr-plugin-loader.js';
import {PrimaryTabs, SecondaryTabs} from '../../../constants/constants.js'; import {PrimaryTabs, SecondaryTabs} from '../../../constants/constants.js';
import {NO_ROBOT_COMMENTS_THREADS_MSG} from '../../../constants/messages.js'; import {NO_ROBOT_COMMENTS_THREADS_MSG} from '../../../constants/messages.js';
@@ -484,9 +486,9 @@ class GrChangeView extends mixinBehaviors( [
Gerrit.awaitPluginsLoaded() Gerrit.awaitPluginsLoaded()
.then(() => { .then(() => {
this._dynamicTabHeaderEndpoints = this._dynamicTabHeaderEndpoints =
Gerrit._endpoints.getDynamicEndpoints('change-view-tab-header'); pluginEndpoints.getDynamicEndpoints('change-view-tab-header');
this._dynamicTabContentEndpoints = this._dynamicTabContentEndpoints =
Gerrit._endpoints.getDynamicEndpoints('change-view-tab-content'); pluginEndpoints.getDynamicEndpoints('change-view-tab-content');
if (this._dynamicTabContentEndpoints.length !== if (this._dynamicTabContentEndpoints.length !==
this._dynamicTabHeaderEndpoints.length) { this._dynamicTabHeaderEndpoints.length) {
console.warn('Different number of tab headers and tab content.'); console.warn('Different number of tab headers and tab content.');
@@ -1051,7 +1053,7 @@ class GrChangeView extends mixinBehaviors( [
this._performPostLoadTasks(); this._performPostLoadTasks();
}); });
Gerrit.awaitPluginsLoaded().then(() => { pluginLoader.awaitPluginsLoaded().then(() => {
this._initActiveTabs(value); this._initActiveTabs(value);
}); });
} }

View File

@@ -46,9 +46,10 @@ import {PrimaryTabs, SecondaryTabs} from '../../../constants/constants.js';
import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js'; import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js';
import {KeyboardShortcutBinder} from '../../../behaviors/keyboard-shortcut-behavior/keyboard-shortcut-behavior.js'; import {KeyboardShortcutBinder} from '../../../behaviors/keyboard-shortcut-behavior/keyboard-shortcut-behavior.js';
import {GrEditConstants} from '../../edit/gr-edit-constants.js'; import {GrEditConstants} from '../../edit/gr-edit-constants.js';
import {GrPluginEndpoints} from '../../shared/gr-js-api-interface/gr-plugin-endpoints.js'; import {_testOnly_resetEndpoints} from '../../shared/gr-js-api-interface/gr-plugin-endpoints.js';
import {util} from '../../../scripts/util.js'; import {util} from '../../../scripts/util.js';
import {GerritNav} from '../../core/gr-navigation/gr-navigation.js'; import {GerritNav} from '../../core/gr-navigation/gr-navigation.js';
import {pluginLoader} from '../../shared/gr-js-api-interface/gr-plugin-loader.js';
suite('gr-change-view tests', () => { suite('gr-change-view tests', () => {
const kb = KeyboardShortcutBinder; const kb = KeyboardShortcutBinder;
@@ -297,8 +298,8 @@ suite('gr-change-view tests', () => {
stub('gr-endpoint-decorator', { stub('gr-endpoint-decorator', {
_import: sandbox.stub().returns(Promise.resolve()), _import: sandbox.stub().returns(Promise.resolve()),
}); });
// Since _endpoints are global, must reset state. // Since pluginEndpoints are global, must reset state.
Gerrit._endpoints = new GrPluginEndpoints(); _testOnly_resetEndpoints();
navigateToChangeStub = sandbox.stub(GerritNav, 'navigateToChange'); navigateToChangeStub = sandbox.stub(GerritNav, 'navigateToChange');
stub('gr-rest-api-interface', { stub('gr-rest-api-interface', {
getConfig() { return Promise.resolve({test: 'config'}); }, getConfig() { return Promise.resolve({test: 'config'}); },
@@ -1584,7 +1585,7 @@ suite('gr-change-view tests', () => {
test('revert dialog opened with revert param', done => { test('revert dialog opened with revert param', done => {
sandbox.stub(element.$.restAPI, 'getLoggedIn', () => Promise.resolve(true)); sandbox.stub(element.$.restAPI, 'getLoggedIn', () => Promise.resolve(true));
sandbox.stub(Gerrit, 'awaitPluginsLoaded', () => Promise.resolve()); sandbox.stub(pluginLoader, 'awaitPluginsLoaded', () => Promise.resolve());
element._patchRange = { element._patchRange = {
basePatchNum: 'PARENT', basePatchNum: 'PARENT',
@@ -1612,7 +1613,7 @@ suite('gr-change-view tests', () => {
done); done);
element._maybeShowRevertDialog(); element._maybeShowRevertDialog();
assert.isTrue(Gerrit.awaitPluginsLoaded.called); assert.isTrue(pluginLoader.awaitPluginsLoaded.called);
}); });
suite('scroll related tests', () => { suite('scroll related tests', () => {

View File

@@ -44,6 +44,7 @@ import {KeyboardShortcutBehavior} from '../../../behaviors/keyboard-shortcut-beh
import {GrFileListConstants} from '../gr-file-list-constants.js'; import {GrFileListConstants} from '../gr-file-list-constants.js';
import {GrCountStringFormatter} from '../../shared/gr-count-string-formatter/gr-count-string-formatter.js'; import {GrCountStringFormatter} from '../../shared/gr-count-string-formatter/gr-count-string-formatter.js';
import {GerritNav} from '../../core/gr-navigation/gr-navigation.js'; import {GerritNav} from '../../core/gr-navigation/gr-navigation.js';
import {pluginEndpoints} from '../../shared/gr-js-api-interface/gr-plugin-endpoints.js';
// Maximum length for patch set descriptions. // Maximum length for patch set descriptions.
const PATCH_DESC_MAX_LENGTH = 500; const PATCH_DESC_MAX_LENGTH = 500;
@@ -299,11 +300,11 @@ class GrFileList extends mixinBehaviors( [
attached() { attached() {
super.attached(); super.attached();
Gerrit.awaitPluginsLoaded().then(() => { Gerrit.awaitPluginsLoaded().then(() => {
this._dynamicHeaderEndpoints = Gerrit._endpoints.getDynamicEndpoints( this._dynamicHeaderEndpoints = pluginEndpoints.getDynamicEndpoints(
'change-view-file-list-header'); 'change-view-file-list-header');
this._dynamicContentEndpoints = Gerrit._endpoints.getDynamicEndpoints( this._dynamicContentEndpoints = pluginEndpoints.getDynamicEndpoints(
'change-view-file-list-content'); 'change-view-file-list-content');
this._dynamicSummaryEndpoints = Gerrit._endpoints.getDynamicEndpoints( this._dynamicSummaryEndpoints = pluginEndpoints.getDynamicEndpoints(
'change-view-file-list-summary'); 'change-view-file-list-summary');
if (this._dynamicHeaderEndpoints.length !== if (this._dynamicHeaderEndpoints.length !==

View File

@@ -41,6 +41,8 @@ import '../../../test/common-test-setup.js';
import '../../plugins/gr-plugin-host/gr-plugin-host.js'; import '../../plugins/gr-plugin-host/gr-plugin-host.js';
import './gr-reply-dialog.js'; import './gr-reply-dialog.js';
import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js'; import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js';
import {resetPlugins} from '../../../test/test-utils.js';
suite('gr-reply-dialog tests', () => { suite('gr-reply-dialog tests', () => {
let element; let element;
let changeNum; let changeNum;
@@ -131,7 +133,7 @@ suite('gr-reply-dialog tests', () => {
}); });
test('lgtm plugin', done => { test('lgtm plugin', done => {
Gerrit._testOnly_resetPlugins(); resetPlugins();
const pluginHost = fixture('plugin-host'); const pluginHost = fixture('plugin-host');
pluginHost.config = { pluginHost.config = {
plugin: { plugin: {

View File

@@ -41,7 +41,7 @@ import {GrEtagDecorator} from './shared/gr-rest-api-interface/gr-etag-decorator.
import {GrThemeApi} from './plugins/gr-theme-api/gr-theme-api.js'; import {GrThemeApi} from './plugins/gr-theme-api/gr-theme-api.js';
import {SiteBasedCache, FetchPromisesCache, GrRestApiHelper} from './shared/gr-rest-api-interface/gr-rest-apis/gr-rest-api-helper.js'; import {SiteBasedCache, FetchPromisesCache, GrRestApiHelper} from './shared/gr-rest-api-interface/gr-rest-apis/gr-rest-api-helper.js';
import {GrLinkTextParser} from './shared/gr-linked-text/link-text-parser.js'; import {GrLinkTextParser} from './shared/gr-linked-text/link-text-parser.js';
import {GrPluginEndpoints} from './shared/gr-js-api-interface/gr-plugin-endpoints.js'; import {pluginEndpoints, GrPluginEndpoints} from './shared/gr-js-api-interface/gr-plugin-endpoints.js';
import {GrReviewerUpdatesParser} from './shared/gr-rest-api-interface/gr-reviewer-updates-parser.js'; import {GrReviewerUpdatesParser} from './shared/gr-rest-api-interface/gr-reviewer-updates-parser.js';
import {GrPopupInterface} from './plugins/gr-popup-interface/gr-popup-interface.js'; import {GrPopupInterface} from './plugins/gr-popup-interface/gr-popup-interface.js';
import {GrRangeNormalizer} from './diff/gr-diff-highlight/gr-range-normalizer.js'; import {GrRangeNormalizer} from './diff/gr-diff-highlight/gr-range-normalizer.js';
@@ -63,16 +63,9 @@ import {GrPluginRestApi} from './shared/gr-js-api-interface/gr-plugin-rest-api.j
import {GrRepoApi} from './plugins/gr-repo-api/gr-repo-api.js'; import {GrRepoApi} from './plugins/gr-repo-api/gr-repo-api.js';
import {GrSettingsApi} from './plugins/gr-settings-api/gr-settings-api.js'; import {GrSettingsApi} from './plugins/gr-settings-api/gr-settings-api.js';
import {GrStylesApi} from './plugins/gr-styles-api/gr-styles-api.js'; import {GrStylesApi} from './plugins/gr-styles-api/gr-styles-api.js';
import {PluginLoader} from './shared/gr-js-api-interface/gr-plugin-loader.js'; import {pluginLoader, PluginLoader} from './shared/gr-js-api-interface/gr-plugin-loader.js';
import {GrPluginActionContext} from './shared/gr-js-api-interface/gr-plugin-action-context.js'; import {GrPluginActionContext} from './shared/gr-js-api-interface/gr-plugin-action-context.js';
import { import {getBaseUrl, getPluginNameFromUrl, getRestAPI, PLUGIN_LOADING_TIMEOUT_MS, PRELOADED_PROTOCOL, send} from './shared/gr-js-api-interface/gr-api-utils.js';
getBaseUrl,
getPluginNameFromUrl,
getRestAPI,
PLUGIN_LOADING_TIMEOUT_MS,
PRELOADED_PROTOCOL,
send,
} from './shared/gr-js-api-interface/gr-api-utils.js';
import {GerritNav} from './core/gr-navigation/gr-navigation.js'; import {GerritNav} from './core/gr-navigation/gr-navigation.js';
import {getRootElement} from '../scripts/rootElement.js'; import {getRootElement} from '../scripts/rootElement.js';
@@ -136,4 +129,7 @@ export function initGlobalVariables() {
window.Gerrit = window.Gerrit || {}; window.Gerrit = window.Gerrit || {};
window.Gerrit.Nav = GerritNav; window.Gerrit.Nav = GerritNav;
window.Gerrit.getRootElement = getRootElement; window.Gerrit.getRootElement = getRootElement;
window.Gerrit._pluginLoader = pluginLoader;
window.Gerrit._endpoints = pluginEndpoints;
} }

View File

@@ -23,6 +23,7 @@ import {GestureEventListeners} from '@polymer/polymer/lib/mixins/gesture-event-l
import {LegacyElementMixin} from '@polymer/polymer/lib/legacy/legacy-element-mixin.js'; import {LegacyElementMixin} from '@polymer/polymer/lib/legacy/legacy-element-mixin.js';
import {PolymerElement} from '@polymer/polymer/polymer-element.js'; import {PolymerElement} from '@polymer/polymer/polymer-element.js';
import {htmlTemplate} from './gr-endpoint-decorator_html.js'; import {htmlTemplate} from './gr-endpoint-decorator_html.js';
import {pluginEndpoints} from '../../shared/gr-js-api-interface/gr-plugin-endpoints.js';
const INIT_PROPERTIES_TIMEOUT_MS = 10000; const INIT_PROPERTIES_TIMEOUT_MS = 10000;
@@ -62,7 +63,7 @@ class GrEndpointDecorator extends GestureEventListeners(
for (const [el, domHook] of this._domHooks) { for (const [el, domHook] of this._domHooks) {
domHook.handleInstanceDetached(el); domHook.handleInstanceDetached(el);
} }
Gerrit._endpoints.onDetachedEndpoint(this.name, this._endpointCallBack); pluginEndpoints.onDetachedEndpoint(this.name, this._endpointCallBack);
} }
/** /**
@@ -161,14 +162,14 @@ class GrEndpointDecorator extends GestureEventListeners(
ready() { ready() {
super.ready(); super.ready();
this._endpointCallBack = this._initModule.bind(this); this._endpointCallBack = this._initModule.bind(this);
Gerrit._endpoints.onNewEndpoint(this.name, this._endpointCallBack); pluginEndpoints.onNewEndpoint(this.name, this._endpointCallBack);
Gerrit.awaitPluginsLoaded() Gerrit.awaitPluginsLoaded()
.then(() => Promise.all( .then(() => Promise.all(
Gerrit._endpoints.getPlugins(this.name).map( pluginEndpoints.getPlugins(this.name).map(
pluginUrl => this._import(pluginUrl))) pluginUrl => this._import(pluginUrl)))
) )
.then(() => .then(() =>
Gerrit._endpoints pluginEndpoints
.getDetails(this.name) .getDetails(this.name)
.forEach(this._initModule, this) .forEach(this._initModule, this)
); );

View File

@@ -45,6 +45,8 @@ import '../../../test/common-test-setup.js';
import './gr-endpoint-decorator.js'; import './gr-endpoint-decorator.js';
import '../gr-endpoint-param/gr-endpoint-param.js'; import '../gr-endpoint-param/gr-endpoint-param.js';
import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js'; import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js';
import {resetPlugins} from '../../../test/test-utils.js';
suite('gr-endpoint-decorator', () => { suite('gr-endpoint-decorator', () => {
let container; let container;
let sandbox; let sandbox;
@@ -57,7 +59,7 @@ suite('gr-endpoint-decorator', () => {
stub('gr-endpoint-decorator', { stub('gr-endpoint-decorator', {
_import: sandbox.stub().returns(Promise.resolve()), _import: sandbox.stub().returns(Promise.resolve()),
}); });
Gerrit._testOnly_resetPlugins(); resetPlugins();
container = fixture('basic'); container = fixture('basic');
Gerrit.install(p => plugin = p, '0.1', 'http://some/plugin/url.html'); Gerrit.install(p => plugin = p, '0.1', 'http://some/plugin/url.html');
// Decoration // Decoration

View File

@@ -23,6 +23,7 @@ import {GestureEventListeners} from '@polymer/polymer/lib/mixins/gesture-event-l
import {LegacyElementMixin} from '@polymer/polymer/lib/legacy/legacy-element-mixin.js'; import {LegacyElementMixin} from '@polymer/polymer/lib/legacy/legacy-element-mixin.js';
import {PolymerElement} from '@polymer/polymer/polymer-element.js'; import {PolymerElement} from '@polymer/polymer/polymer-element.js';
import {htmlTemplate} from './gr-external-style_html.js'; import {htmlTemplate} from './gr-external-style_html.js';
import {pluginEndpoints} from '../../shared/gr-js-api-interface/gr-plugin-endpoints.js';
/** @extends Polymer.Element */ /** @extends Polymer.Element */
class GrExternalStyle extends GestureEventListeners( class GrExternalStyle extends GestureEventListeners(
@@ -79,10 +80,10 @@ class GrExternalStyle extends GestureEventListeners(
} }
_importAndApply() { _importAndApply() {
Promise.all(Gerrit._endpoints.getPlugins(this.name).map( Promise.all(pluginEndpoints.getPlugins(this.name).map(
pluginUrl => this._import(pluginUrl)) pluginUrl => this._import(pluginUrl))
).then(() => { ).then(() => {
const moduleNames = Gerrit._endpoints.getModules(this.name); const moduleNames = pluginEndpoints.getModules(this.name);
for (const name of moduleNames) { for (const name of moduleNames) {
this._applyStyle(name); this._applyStyle(name);
} }

View File

@@ -32,6 +32,7 @@ limitations under the License.
<script type="module"> <script type="module">
import '../../../test/common-test-setup.js'; import '../../../test/common-test-setup.js';
import './gr-external-style.js'; import './gr-external-style.js';
import {pluginLoader} from '../../shared/gr-js-api-interface/gr-plugin-loader.js';
suite('gr-external-style integration tests', () => { suite('gr-external-style integration tests', () => {
const TEST_URL = 'http://some/plugin/url.html'; const TEST_URL = 'http://some/plugin/url.html';
@@ -78,7 +79,8 @@ suite('gr-external-style integration tests', () => {
importHrefStub(url, resolve, reject); importHrefStub(url, resolve, reject);
}, },
}); });
sandbox.stub(Gerrit, 'awaitPluginsLoaded').returns(Promise.resolve()); sandbox.stub(pluginLoader, 'awaitPluginsLoaded')
.returns(Promise.resolve());
}); });
teardown(() => { teardown(() => {

View File

@@ -33,6 +33,8 @@ limitations under the License.
<script type="module"> <script type="module">
import '../../../test/common-test-setup.js'; import '../../../test/common-test-setup.js';
import './gr-plugin-host.js'; import './gr-plugin-host.js';
import {pluginLoader} from '../../shared/gr-js-api-interface/gr-plugin-loader.js';
suite('gr-plugin-host tests', () => { suite('gr-plugin-host tests', () => {
let element; let element;
let sandbox; let sandbox;
@@ -48,21 +50,21 @@ suite('gr-plugin-host tests', () => {
}); });
test('load plugins should be called', () => { test('load plugins should be called', () => {
sandbox.stub(Gerrit, '_loadPlugins'); sandbox.stub(pluginLoader, 'loadPlugins');
element.config = { element.config = {
plugin: { plugin: {
html_resource_paths: ['plugins/foo/bar', 'plugins/baz'], html_resource_paths: ['plugins/foo/bar', 'plugins/baz'],
js_resource_paths: ['plugins/42'], js_resource_paths: ['plugins/42'],
}, },
}; };
assert.isTrue(Gerrit._loadPlugins.calledOnce); assert.isTrue(pluginLoader.loadPlugins.calledOnce);
assert.isTrue(Gerrit._loadPlugins.calledWith([ assert.isTrue(pluginLoader.loadPlugins.calledWith([
'plugins/42', 'plugins/foo/bar', 'plugins/baz', 'plugins/42', 'plugins/foo/bar', 'plugins/baz',
], {})); ], {}));
}); });
test('theme plugins should be loaded if enabled', () => { test('theme plugins should be loaded if enabled', () => {
sandbox.stub(Gerrit, '_loadPlugins'); sandbox.stub(pluginLoader, 'loadPlugins');
element.config = { element.config = {
default_theme: 'gerrit-theme.html', default_theme: 'gerrit-theme.html',
plugin: { plugin: {
@@ -70,23 +72,23 @@ suite('gr-plugin-host tests', () => {
js_resource_paths: ['plugins/42'], js_resource_paths: ['plugins/42'],
}, },
}; };
assert.isTrue(Gerrit._loadPlugins.calledOnce); assert.isTrue(pluginLoader.loadPlugins.calledOnce);
assert.isTrue(Gerrit._loadPlugins.calledWith([ assert.isTrue(pluginLoader.loadPlugins.calledWith([
'gerrit-theme.html', 'plugins/42', 'plugins/foo/bar', 'plugins/baz', 'gerrit-theme.html', 'plugins/42', 'plugins/foo/bar', 'plugins/baz',
], {'gerrit-theme.html': {sync: true}})); ], {'gerrit-theme.html': {sync: true}}));
}); });
test('skip theme if preloaded', () => { test('skip theme if preloaded', () => {
sandbox.stub(Gerrit, '_isPluginPreloaded') sandbox.stub(pluginLoader, 'isPluginPreloaded')
.withArgs('preloaded:gerrit-theme') .withArgs('preloaded:gerrit-theme')
.returns(true); .returns(true);
sandbox.stub(Gerrit, '_loadPlugins'); sandbox.stub(pluginLoader, 'loadPlugins');
element.config = { element.config = {
default_theme: '/oof', default_theme: '/oof',
plugin: {}, plugin: {},
}; };
assert.isTrue(Gerrit._loadPlugins.calledOnce); assert.isTrue(pluginLoader.loadPlugins.calledOnce);
assert.isTrue(Gerrit._loadPlugins.calledWith([], {})); assert.isTrue(pluginLoader.loadPlugins.calledWith([], {}));
}); });
}); });
</script> </script>

View File

@@ -38,6 +38,8 @@ breaking changes to gr-change-actions wont be noticed.
import '../../../test/common-test-setup.js'; import '../../../test/common-test-setup.js';
import '../../change/gr-change-actions/gr-change-actions.js'; import '../../change/gr-change-actions/gr-change-actions.js';
import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js'; import {dom} from '@polymer/polymer/lib/legacy/polymer.dom.js';
import {resetPlugins} from '../../../test/test-utils.js';
suite('gr-js-api-interface tests', () => { suite('gr-js-api-interface tests', () => {
let element; let element;
let changeActions; let changeActions;
@@ -53,7 +55,7 @@ suite('gr-js-api-interface tests', () => {
suite('early init', () => { suite('early init', () => {
setup(() => { setup(() => {
Gerrit._testOnly_resetPlugins(); resetPlugins();
Gerrit.install(p => { plugin = p; }, '0.1', Gerrit.install(p => { plugin = p; }, '0.1',
'http://test.com/plugins/testplugin/static/test.js'); 'http://test.com/plugins/testplugin/static/test.js');
// Mimic all plugins loaded. // Mimic all plugins loaded.
@@ -64,7 +66,7 @@ suite('gr-js-api-interface tests', () => {
teardown(() => { teardown(() => {
changeActions = null; changeActions = null;
Gerrit._testOnly_resetPlugins(); resetPlugins();
}); });
test('does not throw', ()=> { test('does not throw', ()=> {
@@ -76,7 +78,7 @@ suite('gr-js-api-interface tests', () => {
suite('normal init', () => { suite('normal init', () => {
setup(() => { setup(() => {
Gerrit._testOnly_resetPlugins(); resetPlugins();
element = fixture('basic'); element = fixture('basic');
sinon.stub(element, '_editStatusChanged'); sinon.stub(element, '_editStatusChanged');
element.change = {}; element.change = {};
@@ -90,7 +92,7 @@ suite('gr-js-api-interface tests', () => {
teardown(() => { teardown(() => {
changeActions = null; changeActions = null;
Gerrit._testOnly_resetPlugins(); resetPlugins();
}); });
test('property existence', () => { test('property existence', () => {

View File

@@ -20,51 +20,30 @@
* should be defined or linked here. * should be defined or linked here.
*/ */
import {GrPluginEndpoints} from './gr-plugin-endpoints.js'; import {pluginLoader} from './gr-plugin-loader.js';
import {EventEmitter} from '../gr-event-interface/gr-event-interface.js'; import {EventEmitter} from '../gr-event-interface/gr-event-interface.js';
import {PluginLoader} from './gr-plugin-loader.js';
import {getRestAPI, send} from './gr-api-utils.js'; import {getRestAPI, send} from './gr-api-utils.js';
import {testOnly_resetInternalState} from './gr-api-utils.js';
(function(window) { /**
'use strict';
/**
* Trigger the preinstalls for bundled plugins. * Trigger the preinstalls for bundled plugins.
* This needs to happen before Gerrit as plugin bundle overrides the Gerrit. * This needs to happen before Gerrit as plugin bundle overrides the Gerrit.
*/ */
function flushPreinstalls() { function flushPreinstalls() {
if (window.Gerrit.flushPreinstalls) { if (window.Gerrit.flushPreinstalls) {
window.Gerrit.flushPreinstalls(); window.Gerrit.flushPreinstalls();
} }
} }
flushPreinstalls(); flushPreinstalls();
export const _testOnly_flushPreinstalls = flushPreinstalls;
window.Gerrit = window.Gerrit || {}; window.Gerrit = window.Gerrit || {};
const Gerrit = window.Gerrit; const Gerrit = window.Gerrit;
Gerrit._pluginLoader = new PluginLoader();
Gerrit._endpoints = new GrPluginEndpoints(); /**
// Provide reset plugins function to clear installed plugins between tests.
const app = document.querySelector('#app');
if (!app) {
// No gr-app found (running tests)
Gerrit._testOnly_installPreloadedPlugins = (...args) => Gerrit._pluginLoader
.installPreloadedPlugins(...args);
Gerrit._testOnly_flushPreinstalls = flushPreinstalls;
Gerrit._testOnly_resetPlugins = () => {
testOnly_resetInternalState();
Gerrit._endpoints = new GrPluginEndpoints();
Gerrit._pluginLoader = new PluginLoader();
};
}
/**
* @deprecated Use plugin.styles().css(rulesStr) instead. Please, consult * @deprecated Use plugin.styles().css(rulesStr) instead. Please, consult
* the documentation how to replace it accordingly. * the documentation how to replace it accordingly.
*/ */
Gerrit.css = function(rulesStr) { Gerrit.css = function(rulesStr) {
console.warn('Gerrit.css(rulesStr) is deprecated!', console.warn('Gerrit.css(rulesStr) is deprecated!',
'Use plugin.styles().css(rulesStr)'); 'Use plugin.styles().css(rulesStr)');
if (!Gerrit._customStyleSheet) { if (!Gerrit._customStyleSheet) {
@@ -77,34 +56,34 @@ import {testOnly_resetInternalState} from './gr-api-utils.js';
Gerrit._customStyleSheet.cssRules.length; Gerrit._customStyleSheet.cssRules.length;
Gerrit._customStyleSheet.insertRule('.' + name + '{' + rulesStr + '}', 0); Gerrit._customStyleSheet.insertRule('.' + name + '{' + rulesStr + '}', 0);
return name; return name;
}; };
Gerrit.install = function(callback, opt_version, opt_src) { Gerrit.install = function(callback, opt_version, opt_src) {
Gerrit._pluginLoader.install(callback, opt_version, opt_src); pluginLoader.install(callback, opt_version, opt_src);
}; };
Gerrit.getLoggedIn = function() { Gerrit.getLoggedIn = function() {
console.warn('Gerrit.getLoggedIn() is deprecated! ' + console.warn('Gerrit.getLoggedIn() is deprecated! ' +
'Use plugin.restApi().getLoggedIn()'); 'Use plugin.restApi().getLoggedIn()');
return document.createElement('gr-rest-api-interface').getLoggedIn(); return document.createElement('gr-rest-api-interface').getLoggedIn();
}; };
Gerrit.get = function(url, callback) { Gerrit.get = function(url, callback) {
console.warn('.get() is deprecated! Use plugin.restApi().get()'); console.warn('.get() is deprecated! Use plugin.restApi().get()');
send('GET', url, callback); send('GET', url, callback);
}; };
Gerrit.post = function(url, payload, callback) { Gerrit.post = function(url, payload, callback) {
console.warn('.post() is deprecated! Use plugin.restApi().post()'); console.warn('.post() is deprecated! Use plugin.restApi().post()');
send('POST', url, callback, payload); send('POST', url, callback, payload);
}; };
Gerrit.put = function(url, payload, callback) { Gerrit.put = function(url, payload, callback) {
console.warn('.put() is deprecated! Use plugin.restApi().put()'); console.warn('.put() is deprecated! Use plugin.restApi().put()');
send('PUT', url, callback, payload); send('PUT', url, callback, payload);
}; };
Gerrit.delete = function(url, opt_callback) { Gerrit.delete = function(url, opt_callback) {
console.warn('.delete() is deprecated! Use plugin.restApi().delete()'); console.warn('.delete() is deprecated! Use plugin.restApi().delete()');
return getRestAPI().send('DELETE', url) return getRestAPI().send('DELETE', url)
.then(response => { .then(response => {
@@ -122,43 +101,43 @@ import {testOnly_resetInternalState} from './gr-api-utils.js';
} }
return response; return response;
}); });
}; };
Gerrit.awaitPluginsLoaded = function() { Gerrit.awaitPluginsLoaded = function() {
return Gerrit._pluginLoader.awaitPluginsLoaded(); return pluginLoader.awaitPluginsLoaded();
}; };
// TODO(taoalpha): consider removing these proxy methods // TODO(taoalpha): consider removing these proxy methods
// and using _pluginLoader directly // and using _pluginLoader directly
Gerrit._loadPlugins = function(plugins, opt_option) { Gerrit._loadPlugins = function(plugins, opt_option) {
Gerrit._pluginLoader.loadPlugins(plugins, opt_option); pluginLoader.loadPlugins(plugins, opt_option);
}; };
Gerrit._arePluginsLoaded = function() { Gerrit._arePluginsLoaded = function() {
return Gerrit._pluginLoader.arePluginsLoaded; return pluginLoader.arePluginsLoaded();
}; };
Gerrit._isPluginPreloaded = function(url) { Gerrit._isPluginPreloaded = function(url) {
return Gerrit._pluginLoader.isPluginPreloaded(url); return pluginLoader.isPluginPreloaded(url);
}; };
Gerrit._isPluginEnabled = function(pathOrUrl) { Gerrit._isPluginEnabled = function(pathOrUrl) {
return Gerrit._pluginLoader.isPluginEnabled(pathOrUrl); return pluginLoader.isPluginEnabled(pathOrUrl);
}; };
Gerrit._isPluginLoaded = function(pathOrUrl) { Gerrit._isPluginLoaded = function(pathOrUrl) {
return Gerrit._pluginLoader.isPluginLoaded(pathOrUrl); return pluginLoader.isPluginLoaded(pathOrUrl);
}; };
// Preloaded plugins should be installed after Gerrit.install() is set, // Preloaded plugins should be installed after Gerrit.install() is set,
// since plugin preloader substitutes Gerrit.install() temporarily. // since plugin preloader substitutes Gerrit.install() temporarily.
Gerrit._pluginLoader.installPreloadedPlugins(); pluginLoader.installPreloadedPlugins();
// TODO(taoalpha): List all internal supported event names. // TODO(taoalpha): List all internal supported event names.
// Also convert this to inherited class once we move Gerrit to class. // Also convert this to inherited class once we move Gerrit to class.
Gerrit._eventEmitter = new EventEmitter(); Gerrit._eventEmitter = new EventEmitter();
['addListener', ['addListener',
'dispatch', 'dispatch',
'emit', 'emit',
'off', 'off',
@@ -166,7 +145,7 @@ import {testOnly_resetInternalState} from './gr-api-utils.js';
'once', 'once',
'removeAllListeners', 'removeAllListeners',
'removeListener', 'removeListener',
].forEach(method => { ].forEach(method => {
/** /**
* Enabling EventEmitter interface on Gerrit. * Enabling EventEmitter interface on Gerrit.
* *
@@ -190,5 +169,4 @@ import {testOnly_resetInternalState} from './gr-api-utils.js';
* }); * });
*/ */
Gerrit[method] = Gerrit._eventEmitter[method].bind(Gerrit._eventEmitter); Gerrit[method] = Gerrit._eventEmitter[method].bind(Gerrit._eventEmitter);
}); });
})(window);

View File

@@ -33,6 +33,9 @@ limitations under the License.
<script type="module"> <script type="module">
import '../../../test/common-test-setup.js'; import '../../../test/common-test-setup.js';
import './gr-js-api-interface.js'; import './gr-js-api-interface.js';
import {pluginLoader} from './gr-plugin-loader.js';
import {resetPlugins} from '../../../test/test-utils.js';
suite('gr-gerrit tests', () => { suite('gr-gerrit tests', () => {
let element; let element;
let sandbox; let sandbox;
@@ -57,14 +60,14 @@ suite('gr-gerrit tests', () => {
window.clock.restore(); window.clock.restore();
sandbox.restore(); sandbox.restore();
element._removeEventCallbacks(); element._removeEventCallbacks();
Gerrit._testOnly_resetPlugins(); resetPlugins();
}); });
suite('proxy methods', () => { suite('proxy methods', () => {
test('Gerrit._isPluginEnabled proxy to pluginLoader', () => { test('Gerrit._isPluginEnabled proxy to pluginLoader', () => {
const stubFn = sandbox.stub(); const stubFn = sandbox.stub();
sandbox.stub( sandbox.stub(
Gerrit._pluginLoader, pluginLoader,
'isPluginEnabled', 'isPluginEnabled',
(...args) => stubFn(...args) (...args) => stubFn(...args)
); );
@@ -75,7 +78,7 @@ suite('gr-gerrit tests', () => {
test('Gerrit._isPluginLoaded proxy to pluginLoader', () => { test('Gerrit._isPluginLoaded proxy to pluginLoader', () => {
const stubFn = sandbox.stub(); const stubFn = sandbox.stub();
sandbox.stub( sandbox.stub(
Gerrit._pluginLoader, pluginLoader,
'isPluginLoaded', 'isPluginLoaded',
(...args) => stubFn(...args) (...args) => stubFn(...args)
); );
@@ -86,7 +89,7 @@ suite('gr-gerrit tests', () => {
test('Gerrit._isPluginPreloaded proxy to pluginLoader', () => { test('Gerrit._isPluginPreloaded proxy to pluginLoader', () => {
const stubFn = sandbox.stub(); const stubFn = sandbox.stub();
sandbox.stub( sandbox.stub(
Gerrit._pluginLoader, pluginLoader,
'isPluginPreloaded', 'isPluginPreloaded',
(...args) => stubFn(...args) (...args) => stubFn(...args)
); );

View File

@@ -155,3 +155,9 @@ GrPluginEndpoints.prototype.getPlugins = function(name, opt_options) {
} }
return Array.from(new Set(modulesData.map(m => m.pluginUrl))); return Array.from(new Set(modulesData.map(m => m.pluginUrl)));
}; };
// TODO(dmfilippov): Convert to service and add to appContext
export let pluginEndpoints = new GrPluginEndpoints();
export function _testOnly_resetEndpoints() {
pluginEndpoints = new GrPluginEndpoints();
}

View File

@@ -28,6 +28,7 @@ limitations under the License.
import '../../../test/common-test-setup.js'; import '../../../test/common-test-setup.js';
import './gr-js-api-interface.js'; import './gr-js-api-interface.js';
import {GrPluginEndpoints} from './gr-plugin-endpoints.js'; import {GrPluginEndpoints} from './gr-plugin-endpoints.js';
import {pluginLoader} from './gr-plugin-loader.js';
suite('gr-plugin-endpoints tests', () => { suite('gr-plugin-endpoints tests', () => {
let sandbox; let sandbox;
@@ -48,7 +49,7 @@ suite('gr-plugin-endpoints tests', () => {
'http://test.com/plugins/testplugin/static/bar.html'); 'http://test.com/plugins/testplugin/static/bar.html');
instance.registerModule( instance.registerModule(
pluginBar, 'a-place', 'style', 'bar-module', domHook); pluginBar, 'a-place', 'style', 'bar-module', domHook);
sandbox.stub(Gerrit, '_arePluginsLoaded').returns(true); sandbox.stub(pluginLoader, 'arePluginsLoaded').returns(true);
}); });
teardown(() => { teardown(() => {

View File

@@ -193,7 +193,9 @@ export class PluginLoader {
} }
} }
get arePluginsLoaded() { // The polygerrit uses version of sinon where you can't stub getter,
// declare it as a function here
arePluginsLoaded() {
// As the size of plugins is relatively small, // As the size of plugins is relatively small,
// so the performance of this check should be reasonable // so the performance of this check should be reasonable
if (!this._pluginListLoaded) return false; if (!this._pluginListLoaded) return false;
@@ -204,7 +206,7 @@ export class PluginLoader {
} }
_checkIfCompleted() { _checkIfCompleted() {
if (this.arePluginsLoaded && this._loadingResolver) { if (this.arePluginsLoaded() && this._loadingResolver) {
this._loadingResolver(); this._loadingResolver();
this._loadingResolver = null; this._loadingResolver = null;
this._loadingPromise = null; this._loadingPromise = null;
@@ -399,7 +401,7 @@ export class PluginLoader {
// Resolve if completed. // Resolve if completed.
this._checkIfCompleted(); this._checkIfCompleted();
if (this.arePluginsLoaded) { if (this.arePluginsLoaded()) {
return Promise.resolve(); return Promise.resolve();
} }
if (!this._loadingPromise) { if (!this._loadingPromise) {
@@ -435,3 +437,9 @@ PluginLoader.PluginObject;
* }} * }}
*/ */
PluginLoader.PluginOption; PluginLoader.PluginOption;
// TODO(dmfilippov): Convert to service and add to appContext
export let pluginLoader = new PluginLoader();
export function _testOnly_resetPluginLoader() {
pluginLoader = new PluginLoader();
}

View File

@@ -35,6 +35,9 @@ import '../../../test/common-test-setup.js';
import './gr-js-api-interface.js'; import './gr-js-api-interface.js';
import {BaseUrlBehavior} from '../../../behaviors/base-url-behavior/base-url-behavior.js'; import {BaseUrlBehavior} from '../../../behaviors/base-url-behavior/base-url-behavior.js';
import {PRELOADED_PROTOCOL, PLUGIN_LOADING_TIMEOUT_MS} from './gr-api-utils.js'; import {PRELOADED_PROTOCOL, PLUGIN_LOADING_TIMEOUT_MS} from './gr-api-utils.js';
import {pluginLoader} from './gr-plugin-loader.js';
import {resetPlugins} from '../../../test/test-utils.js';
import {_testOnly_flushPreinstalls} from './gr-gerrit.js';
suite('gr-plugin-loader tests', () => { suite('gr-plugin-loader tests', () => {
let plugin; let plugin;
@@ -62,7 +65,7 @@ suite('gr-plugin-loader tests', () => {
teardown(() => { teardown(() => {
sandbox.restore(); sandbox.restore();
window.clock.restore(); window.clock.restore();
Gerrit._testOnly_resetPlugins(); resetPlugins();
}); });
test('reuse plugin for install calls', () => { test('reuse plugin for install calls', () => {
@@ -77,10 +80,10 @@ suite('gr-plugin-loader tests', () => {
test('flushes preinstalls if provided', () => { test('flushes preinstalls if provided', () => {
assert.doesNotThrow(() => { assert.doesNotThrow(() => {
Gerrit._testOnly_flushPreinstalls(); _testOnly_flushPreinstalls();
}); });
window.Gerrit.flushPreinstalls = sandbox.stub(); window.Gerrit.flushPreinstalls = sandbox.stub();
Gerrit._testOnly_flushPreinstalls(); _testOnly_flushPreinstalls();
assert.isTrue(window.Gerrit.flushPreinstalls.calledOnce); assert.isTrue(window.Gerrit.flushPreinstalls.calledOnce);
delete window.Gerrit.flushPreinstalls; delete window.Gerrit.flushPreinstalls;
}); });
@@ -119,7 +122,7 @@ suite('gr-plugin-loader tests', () => {
}); });
test('plugins installed successfully', done => { test('plugins installed successfully', done => {
sandbox.stub(Gerrit._pluginLoader, '_loadJsPlugin', url => { sandbox.stub(pluginLoader, '_loadJsPlugin', url => {
Gerrit.install(() => void 0, undefined, url); Gerrit.install(() => void 0, undefined, url);
}); });
const pluginsLoadedStub = sandbox.stub(); const pluginsLoadedStub = sandbox.stub();
@@ -141,7 +144,7 @@ suite('gr-plugin-loader tests', () => {
}); });
test('isPluginEnabled and isPluginLoaded', done => { test('isPluginEnabled and isPluginLoaded', done => {
sandbox.stub(Gerrit._pluginLoader, '_loadJsPlugin', url => { sandbox.stub(pluginLoader, '_loadJsPlugin', url => {
Gerrit.install(() => void 0, undefined, url); Gerrit.install(() => void 0, undefined, url);
}); });
const pluginsLoadedStub = sandbox.stub(); const pluginsLoadedStub = sandbox.stub();
@@ -156,13 +159,13 @@ suite('gr-plugin-loader tests', () => {
]; ];
Gerrit._loadPlugins(plugins); Gerrit._loadPlugins(plugins);
assert.isTrue( assert.isTrue(
plugins.every(plugin => Gerrit._pluginLoader.isPluginEnabled(plugin)) plugins.every(plugin => pluginLoader.isPluginEnabled(plugin))
); );
flush(() => { flush(() => {
assert.isTrue(Gerrit._arePluginsLoaded()); assert.isTrue(Gerrit._arePluginsLoaded());
assert.isTrue( assert.isTrue(
plugins.every(plugin => Gerrit._pluginLoader.isPluginLoaded(plugin)) plugins.every(plugin => pluginLoader.isPluginLoaded(plugin))
); );
done(); done();
@@ -178,7 +181,7 @@ suite('gr-plugin-loader tests', () => {
const alertStub = sandbox.stub(); const alertStub = sandbox.stub();
document.addEventListener('show-alert', alertStub); document.addEventListener('show-alert', alertStub);
sandbox.stub(Gerrit._pluginLoader, '_loadJsPlugin', url => { sandbox.stub(pluginLoader, '_loadJsPlugin', url => {
Gerrit.install(() => { Gerrit.install(() => {
if (url === plugins[0]) { if (url === plugins[0]) {
throw new Error('failed'); throw new Error('failed');
@@ -210,7 +213,7 @@ suite('gr-plugin-loader tests', () => {
const alertStub = sandbox.stub(); const alertStub = sandbox.stub();
document.addEventListener('show-alert', alertStub); document.addEventListener('show-alert', alertStub);
sandbox.stub(Gerrit._pluginLoader, '_loadJsPlugin', url => { sandbox.stub(pluginLoader, '_loadJsPlugin', url => {
Gerrit.install(() => { Gerrit.install(() => {
if (url === plugins[0]) { if (url === plugins[0]) {
throw new Error('failed'); throw new Error('failed');
@@ -225,15 +228,15 @@ suite('gr-plugin-loader tests', () => {
Gerrit._loadPlugins(plugins); Gerrit._loadPlugins(plugins);
assert.isTrue( assert.isTrue(
plugins.every(plugin => Gerrit._pluginLoader.isPluginEnabled(plugin)) plugins.every(plugin => pluginLoader.isPluginEnabled(plugin))
); );
flush(() => { flush(() => {
assert.isTrue(pluginsLoadedStub.calledWithExactly(['bar'])); assert.isTrue(pluginsLoadedStub.calledWithExactly(['bar']));
assert.isTrue(Gerrit._arePluginsLoaded()); assert.isTrue(Gerrit._arePluginsLoaded());
assert.isTrue(alertStub.calledOnce); assert.isTrue(alertStub.calledOnce);
assert.isTrue(Gerrit._pluginLoader.isPluginLoaded(plugins[1])); assert.isTrue(pluginLoader.isPluginLoaded(plugins[1]));
assert.isFalse(Gerrit._pluginLoader.isPluginLoaded(plugins[0])); assert.isFalse(pluginLoader.isPluginLoaded(plugins[0]));
done(); done();
}); });
}); });
@@ -247,7 +250,7 @@ suite('gr-plugin-loader tests', () => {
const alertStub = sandbox.stub(); const alertStub = sandbox.stub();
document.addEventListener('show-alert', alertStub); document.addEventListener('show-alert', alertStub);
sandbox.stub(Gerrit._pluginLoader, '_loadJsPlugin', url => { sandbox.stub(pluginLoader, '_loadJsPlugin', url => {
Gerrit.install(() => { Gerrit.install(() => {
throw new Error('failed'); throw new Error('failed');
}, undefined, url); }, undefined, url);
@@ -277,7 +280,7 @@ suite('gr-plugin-loader tests', () => {
const alertStub = sandbox.stub(); const alertStub = sandbox.stub();
document.addEventListener('show-alert', alertStub); document.addEventListener('show-alert', alertStub);
sandbox.stub(Gerrit._pluginLoader, '_loadJsPlugin', url => { sandbox.stub(pluginLoader, '_loadJsPlugin', url => {
Gerrit.install(() => { Gerrit.install(() => {
}, url === plugins[0] ? '' : 'alpha', url); }, url === plugins[0] ? '' : 'alpha', url);
}); });
@@ -298,7 +301,7 @@ suite('gr-plugin-loader tests', () => {
}); });
test('multiple assets for same plugin installed successfully', done => { test('multiple assets for same plugin installed successfully', done => {
sandbox.stub(Gerrit._pluginLoader, '_loadJsPlugin', url => { sandbox.stub(pluginLoader, '_loadJsPlugin', url => {
Gerrit.install(() => void 0, undefined, url); Gerrit.install(() => void 0, undefined, url);
}); });
const pluginsLoadedStub = sandbox.stub(); const pluginsLoadedStub = sandbox.stub();
@@ -325,18 +328,18 @@ suite('gr-plugin-loader tests', () => {
let loadJsPluginStub; let loadJsPluginStub;
setup(() => { setup(() => {
importHtmlPluginStub = sandbox.stub(); importHtmlPluginStub = sandbox.stub();
sandbox.stub(Gerrit._pluginLoader, '_loadHtmlPlugin', url => { sandbox.stub(pluginLoader, '_loadHtmlPlugin', url => {
importHtmlPluginStub(url); importHtmlPluginStub(url);
}); });
loadJsPluginStub = sandbox.stub(); loadJsPluginStub = sandbox.stub();
sandbox.stub(Gerrit._pluginLoader, '_createScriptTag', url => { sandbox.stub(pluginLoader, '_createScriptTag', url => {
loadJsPluginStub(url); loadJsPluginStub(url);
}); });
}); });
test('invalid plugin path', () => { test('invalid plugin path', () => {
const failToLoadStub = sandbox.stub(); const failToLoadStub = sandbox.stub();
sandbox.stub(Gerrit._pluginLoader, '_failToLoad', (...args) => { sandbox.stub(pluginLoader, '_failToLoad', (...args) => {
failToLoadStub(...args); failToLoadStub(...args);
}); });
@@ -411,11 +414,11 @@ suite('gr-plugin-loader tests', () => {
setup(() => { setup(() => {
window.ASSETS_PATH = 'https://cdn.com'; window.ASSETS_PATH = 'https://cdn.com';
importHtmlPluginStub = sandbox.stub(); importHtmlPluginStub = sandbox.stub();
sandbox.stub(Gerrit._pluginLoader, '_loadHtmlPlugin', url => { sandbox.stub(pluginLoader, '_loadHtmlPlugin', url => {
importHtmlPluginStub(url); importHtmlPluginStub(url);
}); });
loadJsPluginStub = sandbox.stub(); loadJsPluginStub = sandbox.stub();
sandbox.stub(Gerrit._pluginLoader, '_createScriptTag', url => { sandbox.stub(pluginLoader, '_createScriptTag', url => {
loadJsPluginStub(url); loadJsPluginStub(url);
}); });
}); });
@@ -491,7 +494,7 @@ suite('gr-plugin-loader tests', () => {
installed = true; installed = true;
} }
} }
sandbox.stub(Gerrit._pluginLoader, '_loadJsPlugin', url => { sandbox.stub(pluginLoader, '_loadJsPlugin', url => {
Gerrit.install(() => pluginCallback(url), undefined, url); Gerrit.install(() => pluginCallback(url), undefined, url);
}); });
@@ -509,15 +512,15 @@ suite('gr-plugin-loader tests', () => {
suite('preloaded plugins', () => { suite('preloaded plugins', () => {
test('skips preloaded plugins when load plugins', () => { test('skips preloaded plugins when load plugins', () => {
const importHtmlPluginStub = sandbox.stub(); const importHtmlPluginStub = sandbox.stub();
sandbox.stub(Gerrit._pluginLoader, '_importHtmlPlugin', url => { sandbox.stub(pluginLoader, '_importHtmlPlugin', url => {
importHtmlPluginStub(url); importHtmlPluginStub(url);
}); });
const loadJsPluginStub = sandbox.stub(); const loadJsPluginStub = sandbox.stub();
sandbox.stub(Gerrit._pluginLoader, '_loadJsPlugin', url => { sandbox.stub(pluginLoader, '_loadJsPlugin', url => {
loadJsPluginStub(url); loadJsPluginStub(url);
}); });
Gerrit._preloadedPlugins = { window.Gerrit._preloadedPlugins = {
foo: () => void 0, foo: () => void 0,
bar: () => void 0, bar: () => void 0,
}; };
@@ -533,19 +536,19 @@ suite('gr-plugin-loader tests', () => {
}); });
test('isPluginPreloaded', () => { test('isPluginPreloaded', () => {
Gerrit._preloadedPlugins = {baz: ()=>{}}; window.Gerrit._preloadedPlugins = {baz: ()=>{}};
assert.isFalse(Gerrit._pluginLoader.isPluginPreloaded('plugins/foo/bar')); assert.isFalse(pluginLoader.isPluginPreloaded('plugins/foo/bar'));
assert.isFalse(Gerrit._pluginLoader.isPluginPreloaded('http://a.com/42')); assert.isFalse(pluginLoader.isPluginPreloaded('http://a.com/42'));
assert.isTrue( assert.isTrue(
Gerrit._pluginLoader.isPluginPreloaded(PRELOADED_PROTOCOL + 'baz') pluginLoader.isPluginPreloaded(PRELOADED_PROTOCOL + 'baz')
); );
Gerrit._preloadedPlugins = null; window.Gerrit._preloadedPlugins = null;
}); });
test('preloaded plugins are installed', () => { test('preloaded plugins are installed', () => {
const installStub = sandbox.stub(); const installStub = sandbox.stub();
Gerrit._preloadedPlugins = {foo: installStub}; window.Gerrit._preloadedPlugins = {foo: installStub};
Gerrit._pluginLoader.installPreloadedPlugins(); pluginLoader.installPreloadedPlugins();
assert.isTrue(installStub.called); assert.isTrue(installStub.called);
const pluginApi = installStub.lastCall.args[0]; const pluginApi = installStub.lastCall.args[0];
assert.strictEqual(pluginApi.getPluginName(), 'foo'); assert.strictEqual(pluginApi.getPluginName(), 'foo');

View File

@@ -31,6 +31,8 @@ import {GrRepoApi} from '../../plugins/gr-repo-api/gr-repo-api.js';
import {GrSettingsApi} from '../../plugins/gr-settings-api/gr-settings-api.js'; import {GrSettingsApi} from '../../plugins/gr-settings-api/gr-settings-api.js';
import {GrStylesApi} from '../../plugins/gr-styles-api/gr-styles-api.js'; import {GrStylesApi} from '../../plugins/gr-styles-api/gr-styles-api.js';
import {GrPluginActionContext} from './gr-plugin-action-context.js'; import {GrPluginActionContext} from './gr-plugin-action-context.js';
import {pluginEndpoints} from './gr-plugin-endpoints.js';
import { import {
PRELOADED_PROTOCOL, PRELOADED_PROTOCOL,
getPluginNameFromUrl, getPluginNameFromUrl,
@@ -96,7 +98,7 @@ import {
}; };
Plugin.prototype.registerStyleModule = function(endpointName, moduleName) { Plugin.prototype.registerStyleModule = function(endpointName, moduleName) {
Gerrit._endpoints.registerModule( pluginEndpoints.registerModule(
this, endpointName, EndpointType.STYLE, moduleName); this, endpointName, EndpointType.STYLE, moduleName);
}; };
@@ -128,7 +130,7 @@ import {
EndpointType.REPLACE : EndpointType.DECORATE; EndpointType.REPLACE : EndpointType.DECORATE;
const hook = this._domHooks.getDomHook(endpointName, opt_moduleName); const hook = this._domHooks.getDomHook(endpointName, opt_moduleName);
const moduleName = opt_moduleName || hook.getModuleName(); const moduleName = opt_moduleName || hook.getModuleName();
Gerrit._endpoints.registerModule( pluginEndpoints.registerModule(
this, endpointName, type, moduleName, hook, dynamicEndpoint); this, endpointName, type, moduleName, hook, dynamicEndpoint);
return hook.getPublicAPI(); return hook.getPublicAPI();
}; };

View File

@@ -21,6 +21,7 @@ import '@polymer/iron-test-helpers/iron-test-helpers.js';
import './test-router.js'; import './test-router.js';
import {SafeTypes} from '../behaviors/safe-types-behavior/safe-types-behavior.js'; import {SafeTypes} from '../behaviors/safe-types-behavior/safe-types-behavior.js';
import {initAppContext} from '../services/app-context-init.js'; import {initAppContext} from '../services/app-context-init.js';
import {_testOnly_resetPluginLoader} from '../elements/shared/gr-js-api-interface/gr-plugin-loader.js';
security.polymer_resin.install({ security.polymer_resin.install({
allowedIdentifierPrefixes: [''], allowedIdentifierPrefixes: [''],
@@ -73,10 +74,7 @@ setup(() => {
// overwritten by some other code. // overwritten by some other code.
assert.equal(cleanups.length, 0); assert.equal(cleanups.length, 0);
if (!window.Gerrit) { return; } _testOnly_resetPluginLoader();
if (Gerrit._testOnly_resetPlugins) {
Gerrit._testOnly_resetPlugins();
}
initAppContext(); initAppContext();
}); });

View File

@@ -15,6 +15,10 @@
* limitations under the License. * limitations under the License.
*/ */
import {_testOnly_resetPluginLoader} from '../elements/shared/gr-js-api-interface/gr-plugin-loader.js';
import {testOnly_resetInternalState} from '../elements/shared/gr-js-api-interface/gr-api-utils.js';
import {_testOnly_resetEndpoints} from '../elements/shared/gr-js-api-interface/gr-plugin-endpoints.js';
export const mockPromise = () => { export const mockPromise = () => {
let res; let res;
const promise = new Promise(resolve => { const promise = new Promise(resolve => {
@@ -24,3 +28,11 @@ export const mockPromise = () => {
return promise; return promise;
}; };
export const isHidden = el => getComputedStyle(el).display === 'none'; export const isHidden = el => getComputedStyle(el).display === 'none';
// Provide reset plugins function to clear installed plugins between tests.
// No gr-app found (running tests)
export const resetPlugins = () => {
testOnly_resetInternalState();
_testOnly_resetEndpoints();
_testOnly_resetPluginLoader();
};