Verify input, add more unit tests
Signed-off-by: Lukas Reschke <lukas@statuscode.ch>
This commit is contained in:
parent
ec4bca619d
commit
d4c088cb79
|
@ -1670,21 +1670,26 @@ OC.Util = {
|
|||
|
||||
/**
|
||||
* Returns a file size in bytes from a humanly readable string
|
||||
* Makes 2kB to 2048.
|
||||
* Inspired by computerFileSize in helper.php
|
||||
* @param {string} string file size in human readable format
|
||||
* @return {number} or null if string could not be parsed
|
||||
*
|
||||
* Makes 2kB to 2048.
|
||||
*
|
||||
* Inspired by computerFileSize in helper.php
|
||||
*/
|
||||
computerFileSize: function (string) {
|
||||
var s = string.toLowerCase();
|
||||
|
||||
if (!isNaN(parseFloat(s)) && isFinite(s)) {
|
||||
return parseFloat(s);
|
||||
if (typeof string != 'string') {
|
||||
return null;
|
||||
}
|
||||
|
||||
var bytes_array = {
|
||||
var s = string.toLowerCase();
|
||||
var bytes = parseFloat(s)
|
||||
|
||||
if (!isNaN(bytes) && isFinite(s)) {
|
||||
return bytes;
|
||||
}
|
||||
|
||||
var bytesArray = {
|
||||
'b' : 1,
|
||||
'k' : 1024,
|
||||
'kb': 1024,
|
||||
|
@ -1698,13 +1703,10 @@ OC.Util = {
|
|||
'p' : 1024 * 1024 * 1024 * 1024 * 1024
|
||||
};
|
||||
|
||||
var bytes = parseFloat(s);
|
||||
|
||||
var matches = s.match(/([kmgtp]?b?)$/i);
|
||||
if (matches[1]) {
|
||||
bytes = bytes * bytes_array[matches[1]];
|
||||
}
|
||||
else {
|
||||
bytes = bytes * bytesArray[matches[1]];
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
|
@ -593,6 +593,8 @@ describe('Core base tests', function() {
|
|||
describe('computerFileSize', function() {
|
||||
it('correctly parses file sizes from a human readable formated string', function() {
|
||||
var data = [
|
||||
['125', 125],
|
||||
['125.25', 125.25],
|
||||
['0 B', 0],
|
||||
['125 B', 125],
|
||||
['125b', 125],
|
||||
|
@ -603,13 +605,20 @@ describe('Core base tests', function() {
|
|||
['119.2 GB', 127990025421],
|
||||
['119.2gb', 127990025421],
|
||||
['116.4 TB', 127983153473126],
|
||||
['116.4tb', 127983153473126],
|
||||
['foobar', null]
|
||||
['116.4tb', 127983153473126]
|
||||
];
|
||||
for (var i = 0; i < data.length; i++) {
|
||||
expect(OC.Util.computerFileSize(data[i][0])).toEqual(data[i][1]);
|
||||
}
|
||||
});
|
||||
it('returns null if the parameter is not a string', function() {
|
||||
expect(OC.Util.computerFileSize(NaN)).toEqual(null);
|
||||
expect(OC.Util.computerFileSize(125)).toEqual(null);
|
||||
});
|
||||
it('returns null if the string is unparsable', function() {
|
||||
expect(OC.Util.computerFileSize('')).toEqual(null);
|
||||
expect(OC.Util.computerFileSize('foobar')).toEqual(null);
|
||||
});
|
||||
});
|
||||
describe('stripTime', function() {
|
||||
it('strips time from dates', function() {
|
||||
|
|
Loading…
Reference in New Issue