~didrocks/+junk/face-detection-15.04

« back to all changes in this revision

Viewing changes to facedetection/www/bower_components/sw-toolbox/test/libs/helper-functions.js

  • Committer: Didier Roche
  • Date: 2016-05-10 23:09:11 UTC
  • Revision ID: didier.roche@canonical.com-20160510230911-c7xr490zrj3yrzxd
New version

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/**
 
2
 * Copyright 2016 Google Inc. All rights reserved.
 
3
 *
 
4
 * Licensed under the Apache License, Version 2.0 (the "License");
 
5
 * you may not use this file except in compliance with the License.
 
6
 * You may obtain a copy of the License at
 
7
 *
 
8
 *     http://www.apache.org/licenses/LICENSE-2.0
 
9
 *
 
10
 * Unless required by applicable law or agreed to in writing, software
 
11
 * distributed under the License is distributed on an "AS IS" BASIS,
 
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 
13
 * See the License for the specific language governing permissions and
 
14
 * limitations under the License.
 
15
 *
 
16
 */
 
17
 
 
18
/* eslint-env browser */
 
19
 
 
20
var testCounter = 0;
 
21
 
 
22
// Each service worker that is registered should be given a unique
 
23
// scope. To achieve this we register it with a scope the same as
 
24
// an iframe's src that is unique for each test.
 
25
// Service workers will then be made to claim pages on this scope -
 
26
// i.e. the iframe
 
27
var getIframe = function() {
 
28
  return new Promise(resolve => {
 
29
    var existingIframe = document.querySelector('.js-test-iframe');
 
30
    if (existingIframe) {
 
31
      return resolve(existingIframe);
 
32
    }
 
33
 
 
34
    // This will be used as a unique service worker scope
 
35
    testCounter++;
 
36
 
 
37
    var newIframe = document.createElement('iframe');
 
38
    newIframe.classList.add('js-test-iframe');
 
39
    newIframe.src = '/test/iframe/' + testCounter;
 
40
    newIframe.addEventListener('load', () => {
 
41
      resolve(newIframe);
 
42
    });
 
43
    document.body.appendChild(newIframe);
 
44
  });
 
45
};
 
46
 
 
47
window.testHelper = {
 
48
  unregisterAllRegistrations: function() {
 
49
    return navigator.serviceWorker.getRegistrations()
 
50
      .then(registrations => {
 
51
        return Promise.all(registrations.map(registration => {
 
52
          registration.unregister();
 
53
        }));
 
54
      });
 
55
  },
 
56
 
 
57
  clearAllCaches: function() {
 
58
    return window.caches.keys()
 
59
      .then(cacheNames => {
 
60
        return Promise.all(cacheNames.map(cacheName => {
 
61
          window.caches.delete(cacheName);
 
62
        }));
 
63
      });
 
64
  },
 
65
 
 
66
  // Waiting for a service worker to install is handy if you only care
 
67
  // about testing events that have occured in the install event
 
68
  installSW: function(swUrl) {
 
69
    return new Promise((resolve, reject) => {
 
70
      var iframe;
 
71
      getIframe()
 
72
      .then(newIframe => {
 
73
        var options = null;
 
74
        if (newIframe) {
 
75
          options = {scope: iframe.contentWindow.location.pathname};
 
76
          iframe = newIframe;
 
77
        }
 
78
 
 
79
        return navigator.serviceWorker.register(swUrl, options);
 
80
      })
 
81
      .then(registration => {
 
82
        if (registration.installing === null) {
 
83
          throw new Error(swUrl + ' already installed.');
 
84
        }
 
85
 
 
86
        // We unregister all service workers after each test - this should
 
87
        // always trigger an install state change
 
88
        registration.installing.onstatechange = function() {
 
89
          if (this.state !== 'installed') {
 
90
            return;
 
91
          }
 
92
 
 
93
          resolve(iframe);
 
94
        };
 
95
      })
 
96
      .catch(err => {
 
97
        reject(err);
 
98
      });
 
99
    });
 
100
  },
 
101
 
 
102
  // To test fetch event behaviour in a service worker you will need to wait
 
103
  // for the service worker to activate
 
104
  activateSW: function(swUrl) {
 
105
    return new Promise((resolve, reject) => {
 
106
      var iframe;
 
107
      getIframe()
 
108
      .then(newIframe => {
 
109
        var options = null;
 
110
        if (newIframe) {
 
111
          options = {scope: newIframe.contentWindow.location.pathname};
 
112
          iframe = newIframe;
 
113
        }
 
114
        return navigator.serviceWorker.register(swUrl, options);
 
115
      })
 
116
      .then(registration => {
 
117
        if (registration.installing === null) {
 
118
          throw new Error(swUrl + ' already installed.');
 
119
        }
 
120
 
 
121
        // We unregister all service workers after each test - so this should
 
122
        // always have an activate event if the service worker calls
 
123
        // self.clients.claim()
 
124
        registration.installing.onstatechange = function() {
 
125
          if (this.state !== 'activated') {
 
126
            return;
 
127
          }
 
128
 
 
129
          resolve(iframe);
 
130
        };
 
131
      })
 
132
      .catch(err => {
 
133
        reject(err);
 
134
      });
 
135
    });
 
136
  },
 
137
 
 
138
  // This is a helper method that checks the cache exists before
 
139
  // getting all the cached responses.
 
140
  // This is limited to text at the moment.
 
141
  getAllCachedAssets: function(cacheName) {
 
142
    var cache = null;
 
143
    return window.caches.has(cacheName)
 
144
      .then(hasCache => {
 
145
        if (!hasCache) {
 
146
          throw new Error('Cache doesn\'t exist.');
 
147
        }
 
148
 
 
149
        return window.caches.open(cacheName);
 
150
      })
 
151
      .then(openedCache => {
 
152
        cache = openedCache;
 
153
        return cache.keys();
 
154
      })
 
155
      .then(cacheKeys => {
 
156
        return Promise.all(cacheKeys.map(cacheKey => {
 
157
          return cache.match(cacheKey);
 
158
        }));
 
159
      })
 
160
      .then(cacheResponses => {
 
161
        // This method extracts the response streams and pairs
 
162
        // them with a url.
 
163
        var output = {};
 
164
        cacheResponses.map(response => {
 
165
          output[response.url] = response;
 
166
        });
 
167
        return output;
 
168
      });
 
169
  },
 
170
 
 
171
  // Helper to unregister all service workers and clean all caches
 
172
  // This should be called before each test
 
173
  cleanState: function() {
 
174
    return Promise.all([
 
175
      this.unregisterAllRegistrations(),
 
176
      this.clearAllCaches()
 
177
    ])
 
178
    .then(() => {
 
179
      var iframeList = document.querySelectorAll('.js-test-iframe');
 
180
      for (var i = 0; i < iframeList.length; i++) {
 
181
        iframeList[i].parentElement.removeChild(iframeList[i]);
 
182
      }
 
183
    });
 
184
  }
 
185
};