aboutsummaryrefslogtreecommitdiff
path: root/contexts/data/lib/closure-library/closure/goog/net/imageloader_test.html
blob: 1e2f04527928aa5839afaf6405cce487ca44d479 (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
<!DOCTYPE html>
<html>
<!--
Copyright 2006 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<!--
-->
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Closure Unit Tests - goog.net.ImageLoader</title>
  <script src="../base.js"></script>
  <script>
    goog.require('goog.Timer');
    goog.require('goog.dispose');
    goog.require('goog.events');
    goog.require('goog.events.EventType');
    goog.require('goog.net.ImageLoader');
    goog.require('goog.object');
    goog.require('goog.testing.AsyncTestCase');
    goog.require('goog.testing.jsunit');
    goog.require('goog.testing.recordFunction');
  </script>
</head>
<body>
<script>
var asyncTestCase = goog.testing.AsyncTestCase.createAndInstall(document.title);

// Set the AsyncTestCase timeout to larger value to allow more time
// for images to load.
asyncTestCase.stepTimeout = 5000;


var TEST_EVENT_TYPES = [
  goog.events.EventType.LOAD,
  goog.net.EventType.COMPLETE,
  goog.net.EventType.ERROR
];


/**
 * Mapping from test image file name to:
 * [expected width, expected height, expected event to be fired].
 */
var TEST_IMAGES = {
  'imageloader_testimg1.gif': [20, 20, goog.events.EventType.LOAD],
  'imageloader_testimg2.gif': [20, 20, goog.events.EventType.LOAD],
  'imageloader_testimg3.gif': [32, 32, goog.events.EventType.LOAD],

  'this-is-not-image-1.gif': [0, 0, goog.net.EventType.ERROR],
  'this-is-not-image-2.gif': [0, 0, goog.net.EventType.ERROR]
};


var startTime;
var loader;


function setUp() {
  startTime = goog.now();

  loader = new goog.net.ImageLoader();

  // Adds test images to the loader.
  var i = 0;
  for (var key in TEST_IMAGES) {
    var imageId = 'img_' + i++;
    loader.addImage(imageId, key);
  }
}


function tearDown() {
  goog.dispose(loader);
}


/**
 * Tests loading image and disposing before loading completes.
 */
function testDisposeInTheMiddleOfLoadingWorks() {
  goog.events.listen(loader, TEST_EVENT_TYPES,
      goog.partial(handleDisposalImageLoaderEvent, loader));
  // waitForAsync before starting loader just in case
  // handleDisposalImageLoaderEvent is called from within loader.start
  // (before we yield control). This may happen in IE7/IE8.
  asyncTestCase.waitForAsync('Waiting for loader handler to fire.');
  loader.start();
}


function handleDisposalImageLoaderEvent(loader, e) {
  assertFalse('Handler is still invoked after loader is disposed.',
      loader.isDisposed());

  switch (e.type) {
    case goog.net.EventType.COMPLETE:
      fail('This test should never get COMPLETE event.');
      return;

    case goog.events.EventType.LOAD:
    case goog.net.EventType.ERROR:
      loader.dispose();
      break;
  }

  // Make sure that handler is never called again after disposal before
  // marking test as successful.
  asyncTestCase.waitForAsync('Wait to ensure that COMPLETE is never fired');
  goog.Timer.callOnce(function() {
    asyncTestCase.continueTesting();
  }, 500);
}


/**
 * Tests loading of images until completion.
 */
function testLoadingUntilCompletion() {
  var results = {};
  goog.events.listen(loader, TEST_EVENT_TYPES,
      function(e) {
        switch (e.type) {
          case goog.events.EventType.LOAD:
            var image = e.target;
            results[image.src.substring(image.src.lastIndexOf('/') + 1)] =
                [image.naturalWidth, image.naturalHeight, e.type];
            return;

          case goog.net.EventType.ERROR:
            var image = e.target;
            results[image.src.substring(image.src.lastIndexOf('/') + 1)] =
                [image.naturalWidth, image.naturalHeight, e.type];
            return;

          case goog.net.EventType.COMPLETE:
            // Test completes successfully.
            asyncTestCase.continueTesting();

            assertImagesAreCorrect(results);
            return;
        }
      });

  // waitForAsync before starting loader just in case handleImageLoaderEvent
  // is called from within loader.start (before we yield control).
  // This may happen in IE7/IE8.
  asyncTestCase.waitForAsync('Waiting for loader handler to fire.');
  loader.start();
}


function assertImagesAreCorrect(results) {
  assertEquals(
      goog.object.getCount(TEST_IMAGES), goog.object.getCount(results));
  goog.object.forEach(TEST_IMAGES, function(value, key) {
    // Check if fires the COMPLETE event.
    assertTrue('Image is not loaded completely.', key in results);

    var image = results[key];

    // Check image size.
    assertEquals('Image width is not correct', value[0], image[0]);
    assertEquals('Image length is not correct', value[1], image[1]);

    // Check if fired the correct event.
    assertEquals('Event *' + value[2] + '* must be fired', value[2], image[2]);
  });
}


/**
 * Overrides the loader's loadImage_ method so that it dispatches an image
 * loaded event immediately, causing any event listners to receive them
 * synchronously.  This allows tests to assume synchronous execution.
 */
function makeLoaderSynchronous(loader) {
  var originalLoadImage = loader.loadImage_;
  loader.loadImage_ = function(src, id) {
    originalLoadImage.call(this, src, id);

    var event = new goog.events.Event(goog.events.EventType.LOAD);
    event.currentTarget = this.imageIdToImageMap_[id];
    loader.onNetworkEvent_(event);
  };

  // Make listen() a no-op.
  loader.handler_.listen = goog.nullFunction
}


/**
 * Verifies that if an additional image is added after start() was called, but
 * before COMPLETE was dispatched, no COMPLETE event is sent.  Verifies COMPLETE
 * is finally sent when .start() is called again and all images have now
 * completed loading.
 */
function testImagesAddedAfterStart() {
  // Use synchronous image loading.
  makeLoaderSynchronous(loader);

  // Add another image once the first images finishes loading.
  goog.events.listenOnce(loader, goog.events.EventType.LOAD, function() {
    loader.addImage('extra_image', 'extra_image.gif');
  });

  // Keep track of the total # of image loads.
  var loadRecordFn = goog.testing.recordFunction();
  goog.events.listen(loader, goog.events.EventType.LOAD, loadRecordFn);

  // Keep track of how many times COMPLETE was dispatched.
  var completeRecordFn = goog.testing.recordFunction();
  goog.events.listen(loader, goog.net.EventType.COMPLETE, completeRecordFn);

  // Start testing.
  loader.start();
  assertEquals(
      'COMPLETE event should not have been dispatched yet: An image was ' +
          'added after the initial batch was started.',
      0, completeRecordFn.getCallCount());
  assertEquals('Just the test images should have loaded',
      goog.object.getCount(TEST_IMAGES), loadRecordFn.getCallCount());

  loader.start();
  assertEquals('COMPLETE should have been dispatched once.',
      1, completeRecordFn.getCallCount());
  assertEquals('All images should have been loaded',
      goog.object.getCount(TEST_IMAGES) + 1, loadRecordFn.getCallCount());
}


/**
 * Verifies that more images can be added after an upload starts, and start()
 * can be called for them, resulting in just one COMPLETE event once all the
 * images have completed.
 */
function testImagesAddedAndStartedAfterStart() {
  // Use synchronous image loading.
  makeLoaderSynchronous(loader);

  // Keep track of the total # of image loads.
  var loadRecordFn = goog.testing.recordFunction();
  goog.events.listen(loader, goog.events.EventType.LOAD, loadRecordFn);

  // Add more images once the first images finishes loading, and call start()
  // to get them going.
  goog.events.listenOnce(loader, goog.events.EventType.LOAD, function(e) {
    loader.addImage('extra_image', 'extra_image.gif');
    loader.addImage('extra_image2', 'extra_image2.gif');
    loader.start();
  });

  // Keep track of how many times COMPLETE was dispatched.
  var completeRecordFn = goog.testing.recordFunction();
  goog.events.listen(loader, goog.net.EventType.COMPLETE, completeRecordFn);

  // Start testing.  Make sure all 7 images loaded.
  loader.start();
  assertEquals('COMPLETE should have been dispatched once.',
      1, completeRecordFn.getCallCount());
  assertEquals('All images should have been loaded',
      goog.object.getCount(TEST_IMAGES) + 2, loadRecordFn.getCallCount());
}


/**
 * Verifies that if images are removed after loading has started, COMPLETE
 * is dispatched once the remaining images have finished.
 */
function testImagesRemovedAfterStart() {
  // Use synchronous image loading.
  makeLoaderSynchronous(loader);

  // Remove 2 images once the first image finishes loading.
  goog.events.listenOnce(loader, goog.events.EventType.LOAD, function(e) {
    loader.removeImage(
        goog.array.peek(goog.object.getKeys(this.imageIdToUrlMap_)));
    loader.removeImage(
        goog.array.peek(goog.object.getKeys(this.imageIdToUrlMap_)));
  });

  // Keep track of the total # of image loads.
  var loadRecordFn = goog.testing.recordFunction();
  goog.events.listen(loader, goog.events.EventType.LOAD, loadRecordFn);

  // Keep track of how many times COMPLETE was dispatched.
  var completeRecordFn = goog.testing.recordFunction();
  goog.events.listen(loader, goog.net.EventType.COMPLETE, completeRecordFn);

  // Start testing.  Make sure only the 3 images remaining loaded.
  loader.start();
  assertEquals('COMPLETE should have been dispatched once.',
      1, completeRecordFn.getCallCount());
  assertEquals('All images should have been loaded',
      goog.object.getCount(TEST_IMAGES) - 2, loadRecordFn.getCallCount());
}

</script>
</body>
</html>