Approving files with the same content

I use mocha / supertest / should.js to test the leisure service

GET /files/<hash> returns the file as a stream.

How can I claim in the is.js file that the contents of the file are the same?

 it('should return file as stream', function (done) { var writeStream = fs.createWriteStream('test/fixtures/tmp.json'); var req = api.get('/files/676dfg1430af3595'); req.on('end', function(){ var tmpBuf = fs.readFileSync('test/fixtures/tmp.json'); var testBuf = fs.readFileSync('test/fixtures/test.json'); // How to assert with should.js file contents are the same (tmpBuf == testBuf ) // ... done(); }); }); 
+6
source share
5 answers

Surprisingly, no one suggested Buffer.equals . This is apparently the fastest and easiest approach and exists since v0.11.

So your code will become tmpBuf.equals(testBuf)

+1
source

You have 3 solutions:

First

Compare result lines

 tmpBuf.toString() === testBuf.toString(); 

Second

Using a loop to read bytes bytes byte by byte

 var index = 0, length = tmpBuf.length, match = true; while (index < length) { if (tmpBuf[index] === testBuf[index]) { index++; } else { match = false; break; } } match; // true -> contents are the same, false -> otherwise 

Third

Using a third-party module, for example, buffertools and the buffertools.compare method (buffer, buffer | string).

+3
source

In should.js you can use .eql to compare buffer instances:

 > var buf1 = new Buffer('abc'); undefined > var buf2 = new Buffer('abc'); undefined > var buf3 = new Buffer('dsfg'); undefined > buf1.should.be.eql(buf1) ... > buf1.should.be.eql(buf2) ... > buf1.should.be.eql(buf3) AssertionError: expected <Buffer 61 62 63> to equal <Buffer 64 73 66 67> ... > 
+3
source

Solution using file-compare and node-temp :

 it('should return test2.json as a stream', function (done) { var writeStream = temp.createWriteStream(); temp.track(); var req = api.get('/files/7386afde8992'); req.on('end', function() { comparator.compare(writeStream.path, TEST2_JSON_FILE, function(result, err) { if (err) { return done(err); } result.should.true; done(); }); }); req.pipe(writeStream); }); 
+2
source

to compare large files, for example. images when approving a file loads a comparison of buffers or strings with should.eql takes a lot of time. I recommend approving a hash of a head with a crypto module:

 const buf1Hash = crypto.createHash('sha256').update(buf1).digest(); const buf2Hash = crypto.createHash('sha256').update(buf2).digest(); buf1Hash.should.eql(buf2Hash); 

A simpler approach claims the length of the buffer as follows:

 buf1.length.should.eql(buf2.length) 

instead of using ifjs as an approval module you can use another tool

0
source

Source: https://habr.com/ru/post/975117/


All Articles