How to use getCompletePercent method in Testcafe

Best JavaScript code snippet using testcafe

Run Testcafe automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

uploaddownload.js

Source: uploaddownload.js Github

copy
1import Ember from 'ember';
2import Notification from '../models/notification';
3import config from '../config/environment';
4import stringResources from '../utils/string-resources';
5
6export default Ember.Controller.extend({
7    notifications: Ember.inject.service('notifications'),
8    explorer: Ember.inject.controller(),
9    nodeServices: Ember.inject.service(),
10    sourceUri: null,
11
12    /**
13     * Ensures that a subdirectory structure exists (sync)
14     * @param  {string} file - /tmp/this/path/does/not/exist.jpg
15     */
16    ensureDir: function (file) {
17        var fse = window.requireNode('fs-extra');
18        var path = window.requireNode('path');
19
20        if (fse && file) {
21            let dir = path.dirname(file);
22            return fse.ensureDirSync(dir);
23        }
24
25        return false;
26    },
27
28    actions: {
29        /**
30         * Upload one or multiple files to blobs
31         * @param  {Array} filePaths  - Local file paths of the files to upload
32         * @param  {string} azurePath - Remote Azure Storage path
33         */
34        uploadBlobData: function (paths, azurePath, activeContainer) {
35            var containerPath = azurePath.replace(/.*\:\//, ''),
36                promises = [];
37
38            this.store.find('container', activeContainer).then(foundContainer => {
39                paths.forEach(path => {
40                    var fileName = path.replace(/^.*[\\\/]/, ''),
41                        uploadNotification, speedSummary, uploadPromise, progressUpdateInterval;
42
43                    var promise = foundContainer.uploadBlob(path, containerPath + fileName).then(result => {
44                        speedSummary = result.speedSummary.summary;
45                        uploadPromise = result.promise;
46
47                        progressUpdateInterval = setInterval(() => {
48                            if (speedSummary) {
49                                // don't report a dead speed. this api reports a speed of 0 for small blobs
50                                var speed = speedSummary.getSpeed() === '0B/S' ? '' : speedSummary.getSpeed();
51
52                                uploadNotification.set('progress', speedSummary.getCompletePercent());
53                                uploadNotification.set('text', stringResources.uploadMessage(fileName, azurePath, speed, speedSummary.getCompletePercent()));
54                            }
55                        }, 200);
56
57                        uploadNotification = Notification.create({
58                            type: 'Upload',
59                            text: stringResources.uploadMessage(fileName, azurePath),
60                            cleanup: function () {
61                                clearInterval(this.get('customData').progressUpdateInterval);
62                            },
63                            customData: {
64                                progressUpdateInterval: progressUpdateInterval
65                            }
66                        });
67
68                        this.get('notifications').addPromiseNotification(result.promise, uploadNotification);
69                        return uploadPromise;
70                    });
71
72                    promises.push(promise);
73                });
74
75                appInsights.trackEvent('uploadBlobData');
76                appInsights.trackMetric('uploadBlobs', paths.length);
77
78                return Ember.RSVP.all(promises);
79            }).then(() => {
80                if (config.environment !== 'test') {
81                    this.get('explorer').send('refreshBlobs');
82                }
83            });
84        },
85
86        /**
87         * Takes an array of blobs and streams them to a target directory
88         * @param  {array} blobs        - Blobs to download
89         * @param  {string} directory   - Local directory to save them to
90         * @param  {boolean} saveAs     - Is the target a directory or a filename (saveAs)?
91         */
92        streamBlobsToDirectory: function (blobs, directory, saveAs) {
93            blobs.forEach(blob => {
94                var targetPath = (saveAs) ? directory : directory + '/' + blob.get('name'),
95                    downloadPromise = {
96                        isFulfilled: false
97                    },
98                    downloadNotification, speedSummary, progressUpdateInterval;
99
100                this.ensureDir(targetPath);
101
102                blob.toFile(targetPath).then(result => {
103                    speedSummary = result.speedSummary.summary;
104                    downloadPromise = result.promise;
105
106                    progressUpdateInterval = setInterval(() => {
107                        if (speedSummary) {
108                            // Don't report a dead speed. This api reports a speed of 0 for small blobs
109                            var speed = speedSummary.getSpeed() === '0B/S' ? '' : speedSummary.getSpeed();
110                            downloadNotification.set('progress', speedSummary.getCompletePercent());
111                            downloadNotification.set('text', stringResources.downloadMessage(blob.get('name'), speed, speedSummary.getCompletePercent()));
112                        }
113                    }, 200);
114
115                    downloadNotification = Notification.create({
116                        type: 'Download',
117                        text: stringResources.downloadMessage(blob.get('name')),
118                        cleanup: function () {
119                            clearInterval(this.get('customData').progressUpdateInterval);
120                        },
121                        customData: {
122                            progressUpdateInterval: progressUpdateInterval
123                        }
124                    });
125
126                    this.get('notifications').addPromiseNotification(downloadPromise, downloadNotification);
127                    return downloadPromise;
128                });
129            });
130        },
131
132        /**
133         * Copy a blob to azure storage
134         * @param  {array} blobs        - Blobs to copy
135         * @param  {string} azurePath - Remote Azure Storage path
136         */
137        copyBlobData: function (blob, azureDestPath, activeContainer) {
138            var targetContainerName = azureDestPath,
139                promises = [];
140
141            this.store.find('container', activeContainer).then(foundContainer => {
142                blob.getLink().then(result => {
143                    this.set('sourceUri', result.url);
144
145                    var sourceUri = this.get('sourceUri');
146                    var fileName = blob.get('name').replace(/^.*[\\\/]/, ''),
147                        copyNotification, speedSummary, copyPromise, progressCopyInterval;
148                    var promise = foundContainer.copyBlob(sourceUri, targetContainerName, fileName).then(result => {
149                        speedSummary = result.speedSummary.summary;
150                        copyPromise = result.promise;
151                        progressCopyInterval = setInterval(() => {
152                            if (speedSummary) {
153                                // don't report a dead speed. this api reports a speed of 0 for small blobs
154                                var speed = speedSummary.getSpeed() === '0B/S' ? '' : speedSummary.getSpeed();
155
156                                copyNotification.set('progress', speedSummary.getCompletePercent());
157                                copyNotification.set('text', stringResources.copyMessage(fileName, targetContainerName, speed, speedSummary.getCompletePercent()));
158                            }
159                        }, 200);
160
161                        copyNotification = Notification.create({
162                            type: 'Copy',
163                            text: stringResources.copyMessage(fileName, targetContainerName),
164                            cleanup: function () {
165                                clearInterval(this.get('customData').progressCopyInterval);
166                            },
167                            customData: {
168                                progressCopyInterval: progressCopyInterval
169                            }
170                        });
171
172                        this.get('notifications').addPromiseNotification(result.promise, copyNotification);
173
174                        return copyPromise;
175                    });
176                    promises.push(promise);
177                });
178                appInsights.trackEvent('copyBlobData');
179
180                return Ember.RSVP.all(promises);
181            }).then(() => {
182                if (config.environment !== 'test') {
183                    this.get('explorer').send('refreshBlobs');
184                }
185            });
186        }
187    }
188});
189
Full Screen

azure.js

Source: azure.js Github

copy
1const storage = require('azure-storage');
2const path = require('path');
3const fs = require('fs');
4const keys = require('../config')
5
6process.env.AZURE_STORAGE_ACCOUNT = keys.AZURE_STORAGE_ACCOUNT;
7process.env.AZURE_STORAGE_ACCESS_KEY = keys.AZURE_STORAGE_ACCESS_KEY;
8
9const blobService = storage.createBlobService();
10
11const getFileBlob = params => new Promise((resolve, reject) => {
12  blobService.getBlobProperties(params.container, params.blobname, (error1, result) => {
13    if (error1) {
14      return reject(error1);
15    }
16    const filename = params.localFileName ? `${params.localFileName}${path.extname(result.name)}` : path.basename(result.name);
17    const fpath = path.join(params.localdir, filename);
18    const speedSummary = blobService.getBlobToLocalFile(params.container, params.blobname, fpath, (error2) => { // eslint-disable-line
19      if (error2) {
20        return reject(error2);
21      }
22      return resolve(fpath);
23    });
24    speedSummary.on('progress', () => {
25      console.log(`[Download] Blob: ${params.blobname}, Progress: ${speedSummary.getCompletePercent()}%`);
26    });
27    return null;
28  });
29});
30
31const getTextBlob = (container, blobname) => new Promise((resolve, reject) => {
32  blobService.getBlobToText(container, blobname, (error, text) => {
33    if (error) {
34      return reject(error);
35    }
36    return resolve(text);
37  });
38});
39
40const getStreamBlob = (container, blobname) => new Promise((resolve, reject) => {
41  blobService.getBlobProperties(container, blobname, (error, result) => {
42    if (error) {
43      return reject(error);
44    }
45    const readStream = blobService.createReadStream(container, blobname);
46    return resolve({ content_length: result.contentLength, read_stream: readStream });
47  });
48});
49
50const getBlob = async (container, blobname, options) => {
51  switch (options.mode) {
52    case 'local': {
53      const localpath = await getFileBlob({
54        container,
55        blobname,
56        localdir: options.localdir,
57        localFileName: options.localFileName,
58      });
59      console.log(`Blob ${blobname} downloaded at ${localpath} successfully!`);
60      return localpath;
61    }
62    case 'text': {
63      const text = await getTextBlob(container, blobname);
64      return text;
65    }
66    case 'stream': {
67      const streamDetails = await getStreamBlob(container, blobname);
68      return streamDetails;
69    }
70    default:
71      throw new Error('Invalid file download mode!');
72  }
73};
74
75const uploadFileBlob = (container, blobname, filepath, options, callback) => {
76  const speedSummary = blobService.createBlockBlobFromLocalFile(container, blobname, filepath, options, (error) => { // eslint-disable-line
77    if (error) {
78      return callback(error);
79    }
80    const dataToSend = {
81      blobname,
82      container,
83    };
84    return callback(null, dataToSend);
85  });
86  speedSummary.on('progress', () => {
87    console.log(`[Upload] Blob: ${blobname}, Progress: ${speedSummary.getCompletePercent()}%`);
88  });
89};
90
91const uploadFileStreamToBlob = (container, blobname, filepath, options, callback) => {
92  const fileStats = fs.statSync(filepath);
93  const fileReadStream = fs.createReadStream(filepath);
94
95  const speedSummary = blobService.createBlockBlobFromStream(container, blobname, fileReadStream, fileStats.size, options, (error, result) => { // eslint-disable-line
96    if (error) {
97      return callback(error);
98    }
99    const dataToSend = {
100      blobname,
101      container,
102    };
103    return callback(null, dataToSend);
104  });
105
106  speedSummary.on('progress', () => {
107    console.log(`[Upload] Blob: ${blobname}, Progress: ${speedSummary.getCompletePercent()}%`);
108  });
109};
110
111const generatePublicURL = (container, blobname) => {
112  const publicURL = blobService.getUrl(
113    container,
114    blobname,
115    null,
116    `https://${process.env.AZURE_STORAGE_ACCOUNT}.blob.core.windows.net`,
117  );
118  return publicURL;
119};
120
121const generatePublicURLWithToken = (container, blobname, start, expiry) => {
122  let startDate = null;
123  let expiryDate = null;
124
125  if (start && expiry) {
126    startDate = new Date(start);
127    expiryDate = new Date(expiry);
128  } else {
129    startDate = new Date();
130    expiryDate = new Date(startDate);
131
132    startDate.setHours(startDate.getHours() - 1);
133    expiryDate.setHours(expiryDate.getHours() + 1);
134  }
135
136  const sharedAccessPolicy = {
137    AccessPolicy: {
138      Permissions: storage.BlobUtilities.SharedAccessPermissions.READ,
139      Start: startDate,
140      Expiry: expiryDate,
141    },
142  };
143
144  const sasToken = blobService.generateSharedAccessSignature(
145    container,
146    blobname,
147    sharedAccessPolicy,
148  );
149
150  const publicUrl = blobService.getUrl(
151    container,
152    blobname,
153    sasToken,
154    `https://${process.env.AZURE_STORAGE_ACCOUNT}.blob.core.windows.net`,
155  );
156
157  return publicUrl;
158};
159
160const generateUploadToken = (container, blobname) => {
161  const startDate = new Date();
162  const expiryDate = new Date(startDate);
163
164  startDate.setHours(startDate.getHours() - 1);
165  expiryDate.setHours(expiryDate.getHours() + 1);
166
167  const sharedAccessPolicy = {
168    AccessPolicy: {
169      Permissions: storage.BlobUtilities.SharedAccessPermissions.WRITE,
170      Start: startDate,
171      Expiry: expiryDate,
172    },
173  };
174
175  const sasToken = blobService.generateSharedAccessSignature(
176    container,
177    blobname,
178    sharedAccessPolicy,
179  );
180
181  return sasToken;
182};
183
184const updateBlobProperties = (container, blobname, options, callback) => {
185  blobService.setBlobProperties(container, blobname, options, (error) => {
186    if (error) {
187      return callback(error);
188    }
189    return callback();
190  });
191};
192
193const deleteBlob = (container, blobname, callback) => {
194  blobService.deleteBlobIfExists(container, blobname, (error) => {
195    if (error) {
196      return callback(error);
197    }
198    return callback();
199  });
200};
201
202module.exports = {
203  getBlob,
204  uploadFileBlob,
205  uploadFileStreamToBlob,
206  generatePublicURL,
207  generatePublicURLWithToken,
208  generateUploadToken,
209  updateBlobProperties,
210  deleteBlob,
211};
212
Full Screen

main.js

Source: main.js Github

copy
1const containerName = 'bigfiles'
2
3// fetchSAS fetches the SAS token from the server to authenticate
4function fetchSAS(filename) {
5    return fetch('/sas', {
6        method: 'POST',
7        body: JSON.stringify({
8            filename: filename
9        }),
10        headers: {
11            'Content-Type': 'application/json',
12        }
13    }).then(res => res.json())
14      .then(res => {
15        if (!filename) {
16            return AzureStorage.Blob.createBlobServiceWithSas(
17                res.uri, 
18                res.params
19            )
20        } else {
21            return `${res.uri}?${res.params}`
22        }
23      })
24}
25
26// openModal shows the file upload progress dialog
27function openModal(yes) {
28    const elems = document.querySelectorAll('.modal')
29    const instances = M.Modal.init(elems)
30
31    if (yes) {
32        instances[0].open()
33    } else {
34        instances[0].close()
35    }
36}
37
38// Start loads the set of Blobs in the container in Azure
39function start() {
40    fetchSAS()
41        .then(service => {
42            service.listBlobsSegmented(containerName, null, function (error, results) {
43                if (error) {
44                    console.error(error)
45                } else {
46                    generateFileCards(results.entries)
47                }
48            })
49        })
50        .catch(e => console.error(e))
51}
52
53// generateFileCards generates a card for each file to display on the UI
54function generateFileCards(blobs) {
55    
56    const innerHTML = blobs.map(blob => {
57        return `
58        <div class="col s12 m4">
59            <div class="card blue-grey darken-1">
60            <div class="card-content white-text">
61                <span class="card-title">${blob.name}</span>
62                <p class="size">${bytesToSize(blob.contentLength)}</p>
63            </div>
64            <div class="card-action">
65                <a href="#" data-filename="${blob.name}" onclick="downloadFile(event)">Download</a>
66            </div>
67            </div>
68        </div>
69        `
70    })
71
72    document.getElementById('rows').innerHTML = innerHTML.join('')
73    
74}
75
76function bytesToSize(bytes) {
77    var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
78    if (bytes == 0) return '0 Byte';
79    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
80    return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
81}
82
83// fileUpload uploads the file to storage
84function fileUpload() {
85    const file = document.querySelector('#fileInput').files[0]
86    
87    openModal(true)
88    document.getElementById('modalFileName').innerText = file.name
89
90    fetchSAS()
91        .then(service => {
92            const summary = service.createBlockBlobFromBrowserFile(
93                containerName,
94                file.name,
95                file,
96                (error) => {
97                    if(error) {
98                        console.error(error)
99                    } else {
100                        location.reload()
101                    }
102                })
103
104
105            summary.on('progress', () => {
106                document.getElementById('modalPercentageProgress').innerText = summary.getCompletePercent()
107                document.querySelector('.determinate').style.width = parseInt(summary.getCompletePercent()) + '%'
108            })
109        })
110        .catch(e => console.error(e))
111}
112
113function downloadFile(e) {
114
115    const filename = e.target.dataset.filename
116    
117    fetchSAS(filename)
118        .then(uri => {
119            console.log(uri)
120            document.location = uri
121        })
122        .catch(e => console.error(e))
123}
124
125start()
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Testcafe on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)