summaryrefslogtreecommitdiffstats
path: root/polygerrit-ui/app/elements/core/gr-error-manager/gr-error-manager_test.html
blob: f92feae40412f398520f72326e87d6607da1f8a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
<!DOCTYPE html>
<!--
@license
Copyright (C) 2016 The Android Open Source Project

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->

<meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0, user-scalable=yes">
<title>gr-error-manager</title>

<script src="../../../bower_components/webcomponentsjs/webcomponents-lite.min.js"></script>
<script src="../../../bower_components/web-component-tester/browser.js"></script>
<link rel="import" href="../../../test/common-test-setup.html"/>
<link rel="import" href="gr-error-manager.html">

<script>void(0);</script>

<test-fixture id="basic">
  <template>
    <gr-error-manager></gr-error-manager>
  </template>
</test-fixture>

<script>
  suite('gr-error-manager tests', () => {
    let element;
    let sandbox;

    setup(() => {
      sandbox = sinon.sandbox.create();
      stub('gr-rest-api-interface', {
        getLoggedIn() { return Promise.resolve(true); },
      });
      element = fixture('basic');
    });

    teardown(() => {
      sandbox.restore();
    });

    test('does not show auth error on 403 by default', done => {
      const showAuthErrorStub = sandbox.stub(element, '_showAuthErrorAlert');
      const responseText = Promise.resolve('server says no.');
      element.fire('server-error',
          {response: {status: 403, text() { return responseText; }}}
      );
      Promise.all([
        element.$.restAPI.getLoggedIn.lastCall.returnValue,
        responseText,
      ]).then(() => {
        assert.isFalse(showAuthErrorStub.calledOnce);
        done();
      });
    });

    test('shows auth error on 403 and Authentication required', done => {
      const showAuthErrorStub = sandbox.stub(element, '_showAuthErrorAlert');
      const responseText = Promise.resolve('Authentication required\n');
      element.fire('server-error',
          {response: {status: 403, text() { return responseText; }}}
      );
      Promise.all([
        element.$.restAPI.getLoggedIn.lastCall.returnValue,
        responseText,
      ]).then(() => {
        assert.isTrue(showAuthErrorStub.calledOnce);
        done();
      });
    });

    test('show logged in error', () => {
      sandbox.stub(element, '_showAuthErrorAlert');
      element.fire('show-auth-required');
      assert.isTrue(element._showAuthErrorAlert.calledWithExactly(
          'Log in is required to perform that action.', 'Log in.'));
    });

    test('show normal Error', done => {
      const showErrorStub = sandbox.stub(element, '_showErrorDialog');
      const textSpy = sandbox.spy(() => { return Promise.resolve('ZOMG'); });
      element.fire('server-error', {response: {status: 500, text: textSpy}});

      assert.isTrue(textSpy.called);
      Promise.all([
        element.$.restAPI.getLoggedIn.lastCall.returnValue,
        textSpy.lastCall.returnValue,
      ]).then(() => {
        assert.isTrue(showErrorStub.calledOnce);
        assert.isTrue(showErrorStub.lastCall.calledWithExactly(
            'Error 500: ZOMG'));
        done();
      });
    });

    test('_constructServerErrorMsg', () => {
      const errorText = 'change conflicts';
      const status = 409;
      const statusText = 'Conflict';
      const url = '/my/test/url';

      assert.equal(element._constructServerErrorMsg({status}),
          'Error 409');
      assert.equal(element._constructServerErrorMsg({status, url}),
          'Error 409: \nEndpoint: /my/test/url');
      assert.equal(element._constructServerErrorMsg({status, statusText, url}),
          'Error 409 (Conflict): \nEndpoint: /my/test/url');
      assert.equal(element._constructServerErrorMsg({
        status,
        statusText,
        errorText,
        url,
      }), 'Error 409 (Conflict): change conflicts' +
          '\nEndpoint: /my/test/url');
    });

    test('suppress TOO_MANY_FILES error', done => {
      const showAlertStub = sandbox.stub(element, '_showAlert');
      const textSpy = sandbox.spy(() => {
        return Promise.resolve('too many files to find conflicts');
      });
      element.fire('server-error', {response: {status: 500, text: textSpy}});

      assert.isTrue(textSpy.called);
      Promise.all([
        element.$.restAPI.getLoggedIn.lastCall.returnValue,
        textSpy.lastCall.returnValue,
      ]).then(() => {
        assert.isFalse(showAlertStub.called);
        done();
      });
    });

    test('show network error', done => {
      const consoleErrorStub = sandbox.stub(console, 'error');
      const showAlertStub = sandbox.stub(element, '_showAlert');
      element.fire('network-error', {error: new Error('ZOMG')});
      flush(() => {
        assert.isTrue(showAlertStub.calledOnce);
        assert.isTrue(showAlertStub.lastCall.calledWithExactly(
            'Server unavailable'));
        assert.isTrue(consoleErrorStub.calledOnce);
        assert.isTrue(consoleErrorStub.lastCall.calledWithExactly('ZOMG'));
        done();
      });
    });

    test('show auth refresh toast', done => {
      const refreshStub = sandbox.stub(element.$.restAPI, 'checkCredentials',
          () => { return Promise.resolve(true); });
      const toastSpy = sandbox.spy(element, '_createToastAlert');
      const windowOpen = sandbox.stub(window, 'open');
      const responseText = Promise.resolve('Authentication required\n');
      element.fire('server-error',
          {response: {status: 403, text() { return responseText; }}}
      );
      Promise.all([
        element.$.restAPI.getLoggedIn.lastCall.returnValue,
        responseText,
      ]).then(() => {
        assert.isTrue(toastSpy.called);
        let toast = toastSpy.lastCall.returnValue;
        assert.isOk(toast);
        assert.include(
            Polymer.dom(toast.root).textContent, 'Auth error');
        assert.include(
            Polymer.dom(toast.root).textContent, 'Refresh credentials.');

        assert.isFalse(windowOpen.called);
        MockInteractions.tap(toast.$$('gr-button.action'));
        assert.isTrue(windowOpen.called);

        // @see Issue 5822: noopener breaks closeAfterLogin
        assert.equal(windowOpen.lastCall.args[2].indexOf('noopener=yes'),
            -1);

        const hideToastSpy = sandbox.spy(toast, 'hide');

        element._handleWindowFocus();
        assert.isTrue(refreshStub.called);
        element.flushDebouncer('checkLoggedIn');
        flush(() => {
          assert.isTrue(refreshStub.called);
          assert.isTrue(hideToastSpy.called);

          assert.notStrictEqual(toastSpy.lastCall.returnValue, toast);
          toast = toastSpy.lastCall.returnValue;
          assert.isOk(toast);
          assert.include(
              Polymer.dom(toast.root).textContent, 'Credentials refreshed');
          done();
        });
      });
    });

    test('show alert', () => {
      const alertObj = {message: 'foo'};
      sandbox.stub(element, '_showAlert');
      element.fire('show-alert', alertObj);
      assert.isTrue(element._showAlert.calledOnce);
      assert.equal(element._showAlert.lastCall.args[0], 'foo');
      assert.isNotOk(element._showAlert.lastCall.args[1]);
      assert.isNotOk(element._showAlert.lastCall.args[2]);
    });

    test('checks stale credentials on visibility change', () => {
      const refreshStub = sandbox.stub(element.$.restAPI,
          'checkCredentials');
      sandbox.stub(Date, 'now').returns(999999);
      element._lastCredentialCheck = 0;
      element._handleVisibilityChange();

      // Since there is no known account, it should not test credentials.
      assert.isFalse(refreshStub.called);
      assert.equal(element._lastCredentialCheck, 0);

      element.knownAccountId = 123;
      element._handleVisibilityChange();

      // Should test credentials, since there is a known account.
      assert.isTrue(refreshStub.called);
      assert.equal(element._lastCredentialCheck, 999999);
    });

    test('refresh loop continues on credential fail', done => {
      const accountPromise = Promise.resolve(null);
      sandbox.stub(element.$.restAPI, 'checkCredentials')
          .returns(accountPromise);
      const requestCheckStub = sandbox.stub(element, '_requestCheckLoggedIn');
      const handleRefreshStub = sandbox.stub(element,
          '_handleCredentialRefreshed');
      const reloadStub = sandbox.stub(element, '_reloadPage');

      element._refreshingCredentials = true;
      element._checkSignedIn();

      accountPromise.then(() => {
        assert.isTrue(requestCheckStub.called);
        assert.isFalse(handleRefreshStub.called);
        assert.isFalse(reloadStub.called);
        done();
      });
    });

    test('refreshes with same credentials', done => {
      const accountPromise = Promise.resolve({_account_id: 1234});
      sandbox.stub(element.$.restAPI, 'checkCredentials')
          .returns(accountPromise);
      const requestCheckStub = sandbox.stub(element, '_requestCheckLoggedIn');
      const handleRefreshStub = sandbox.stub(element,
          '_handleCredentialRefreshed');
      const reloadStub = sandbox.stub(element, '_reloadPage');

      element.knownAccountId = 1234;
      element._refreshingCredentials = true;
      element._checkSignedIn();

      accountPromise.then(() => {
        assert.isFalse(requestCheckStub.called);
        assert.isTrue(handleRefreshStub.called);
        assert.isFalse(reloadStub.called);
        done();
      });
    });

    test('reloads when refreshed credentials differ', done => {
      const accountPromise = Promise.resolve({_account_id: 1234});
      sandbox.stub(element.$.restAPI, 'checkCredentials')
          .returns(accountPromise);
      const requestCheckStub = sandbox.stub(element, '_requestCheckLoggedIn');
      const handleRefreshStub = sandbox.stub(element,
          '_handleCredentialRefreshed');
      const reloadStub = sandbox.stub(element, '_reloadPage');

      element.knownAccountId = 4321; // Different from 1234
      element._refreshingCredentials = true;
      element._checkSignedIn();

      accountPromise.then(() => {
        assert.isFalse(requestCheckStub.called);
        assert.isFalse(handleRefreshStub.called);
        assert.isTrue(reloadStub.called);
        done();
      });
    });

    test('_showAlert hides existing alerts', () => {
      element._alertElement = element._createToastAlert();
      const hideStub = sandbox.stub(element, '_hideAlert');
      element._showAlert();
      assert.isTrue(hideStub.calledOnce);
    });

    test('show-error', () => {
      const openStub = sandbox.stub(element.$.errorOverlay, 'open');
      const closeStub = sandbox.stub(element.$.errorOverlay, 'close');
      const message = 'test message';
      element.fire('show-error', {message});
      flushAsynchronousOperations();

      assert.isTrue(openStub.called);
      assert.equal(element.$.errorDialog.text, message);

      element.$.errorDialog.fire('dismiss');
      flushAsynchronousOperations();

      assert.isTrue(closeStub.called);
    });
  });
</script>