Best JavaScript code snippet using best
_db_update_document.spec.js
Source:_db_update_document.spec.js
1module.exports = function(createStream) {2 describe('update document db', function() {3 var users, usersCollection, userDocument, worker, patches;4 describe('externally modified property fails query', function() {5 before(function(done) {6 helper.loadFixture('users', function(err, result) {7 users = result;8 done(err);9 });10 });11 before(function(done) {12 usersCollection = helper.db.collection('users');13 worker = sinon.spy(function(document, callback) {14 callback(null, { $set: { 'location.postcode': 8000 } });15 });16 var delayedUsersCollection = helper.delayCollection(usersCollection);17 delayedUsersCollection.onfindandmodify = function(callback) {18 usersCollection.update({ name: 'user_2' }, { $set: { 'location.city': 'London' } }, function(err) {19 if(err) {20 return done(err);21 }22 callback();23 });24 };25 var updateStream = createStream(worker);26 helper.readStream(updateStream, function(err, result) {27 patches = result;28 done(err);29 });30 updateStream.write({31 before: users[1],32 modifier: { $set: { 'location.postcode': 8000 } },33 collection: delayedUsersCollection,34 query: { 'location.city': 'Aarhus' }35 });36 updateStream.end();37 });38 before(function(done) {39 usersCollection.findOne({ name: 'user_2' }, function(err, result) {40 userDocument = result;41 done(err);42 });43 });44 it('should only patch one user', function() {45 chai.expect(patches.length).to.equal(1);46 });47 it('should have patch with before document', function() {48 chai.expect(patches[0])49 .to.have.property('before')50 .to.contain.subset({51 name: 'user_2',52 associates: ['user_1', 'user_3'],53 location: {54 city: 'Aarhus',55 address: 'Niels Borhs Vej'56 }57 });58 });59 it('should not have modified document', function() {60 chai.expect(patches[0]).to.have.property('modified', false);61 });62 it('should have skipped document', function() {63 chai.expect(patches[0]).to.have.property('skipped', true);64 });65 it('should have one attempt', function() {66 chai.expect(patches[0]).to.have.property('attempts', 1);67 });68 it('should not update externally changed document', function() {69 chai.expect(userDocument)70 .to.contain.subset({71 name: 'user_2',72 associates: ['user_1', 'user_3'],73 location: {74 city: 'London',75 address: 'Niels Borhs Vej'76 }77 })78 .not.to.have.deep.property('location.postcode');79 });80 it('should not have called worker', function() {81 chai.expect(worker.callCount).to.equal(0);82 });83 });84 describe('externally added property fails query', function() {85 before(function(done) {86 helper.loadFixture('users', function(err, result) {87 users = result;88 done(err);89 });90 });91 before(function(done) {92 usersCollection = helper.db.collection('users');93 worker = sinon.spy(function(document, callback) {94 callback(null, { $set: { updatedAt: '2014-04-01' } });95 });96 var delayedUsersCollection = helper.delayCollection(usersCollection);97 delayedUsersCollection.onfindandmodify = function(callback) {98 usersCollection.update({ name: 'user_1' }, { $set: { updatedAt: '2014-03-30' } }, function(err) {99 if(err) {100 return done(err);101 }102 callback();103 });104 };105 var updateStream = createStream(worker);106 helper.readStream(updateStream, function(err, result) {107 patches = result;108 done(err);109 });110 updateStream.write({111 before: users[0],112 modifier: { $set: { updatedAt: '2014-04-01' } },113 collection: delayedUsersCollection,114 query: { updatedAt: { $exists: false } }115 });116 updateStream.end();117 });118 before(function(done) {119 usersCollection.findOne({ name: 'user_1' }, function(err, result) {120 userDocument = result;121 done(err);122 });123 });124 it('should only patch one user', function() {125 chai.expect(patches.length).to.equal(1);126 });127 it('should have patch with changed before document', function() {128 chai.expect(patches[0])129 .to.have.property('before')130 .to.contain.subset({131 name: 'user_1',132 associates: [],133 location: {134 city: 'Copenhagen',135 address: 'Wildersgade'136 }137 });138 });139 it('should not have modified document', function() {140 chai.expect(patches[0]).to.have.property('modified', false);141 });142 it('should have skipped document', function() {143 chai.expect(patches[0]).to.have.property('skipped', true);144 });145 it('should have one attempt', function() {146 chai.expect(patches[0]).to.have.property('attempts', 1);147 });148 it('should not update externally changed document', function() {149 chai.expect(userDocument)150 .to.contain.subset({151 name: 'user_1',152 associates: [],153 location: {154 city: 'Copenhagen',155 address: 'Wildersgade'156 }157 })158 .to.have.property('updatedAt', '2014-03-30');159 });160 it('should not have called worker', function() {161 chai.expect(worker.callCount).to.equal(0);162 });163 });164 describe('externally modified property satisfies query', function() {165 before(function(done) {166 helper.loadFixture('users', function(err, result) {167 users = result;168 done(err);169 });170 });171 before(function(done) {172 usersCollection = helper.db.collection('users');173 worker = sinon.spy(function(document, callback) {174 callback(null, { $set: { 'location.address': 'Silkeborg Vej' } });175 });176 var delayedUsersCollection = helper.delayCollection(usersCollection);177 delayedUsersCollection.onfindandmodify = function(callback) {178 // Unrelated property (location.city) modified externally179 usersCollection.update({ name: 'user_1' }, { $set: { 'location.city': 'London' } }, function(err) {180 if(err) {181 return done(err);182 }183 // Do not perform external update when called again184 delayedUsersCollection.onfindandmodify = null;185 callback();186 });187 };188 var updateStream = createStream(worker);189 helper.readStream(updateStream, function(err, result) {190 patches = result;191 done(err);192 });193 updateStream.write({194 before: users[0],195 modifier: { $set: { 'location.address': 'Silkeborg Vej' } },196 collection: delayedUsersCollection,197 query: { name: 'user_1' }198 });199 updateStream.end();200 });201 before(function(done) {202 usersCollection.findOne({ name: 'user_1' }, function(err, result) {203 userDocument = result;204 done(err);205 });206 });207 it('should only patch one user', function() {208 chai.expect(patches.length).to.equal(1);209 });210 it('should have patch with changed before document', function() {211 chai.expect(patches[0])212 .to.have.property('before')213 .to.contain.subset({214 name: 'user_1',215 associates: [],216 location: {217 city: 'London',218 address: 'Wildersgade'219 }220 });221 });222 it('should have patch with changed after document', function() {223 chai.expect(patches[0])224 .to.have.property('after')225 .to.contain.subset({226 name: 'user_1',227 associates: [],228 location: {229 city: 'London',230 address: 'Silkeborg Vej'231 }232 });233 });234 it('should have modified document', function() {235 chai.expect(patches[0]).to.have.property('modified', true);236 });237 it('should not have skipped document', function() {238 chai.expect(patches[0]).to.have.property('skipped', false);239 });240 it('should have two attempts', function() {241 chai.expect(patches[0]).to.have.property('attempts', 2);242 });243 it('should have diff with only patched changes', function() {244 chai.expect(patches[0])245 .to.have.property('diff')246 .to.deep.equal({247 location: {248 address: 'updated'249 }250 });251 });252 it('should update externally changed document', function() {253 chai.expect(userDocument)254 .to.contain.subset({255 name: 'user_1',256 associates: [],257 location: {258 city: 'London',259 address: 'Silkeborg Vej'260 }261 });262 });263 it('should have called worker', function() {264 chai.expect(worker.callCount).to.equal(1);265 });266 it('should have called worker with document and callback', function() {267 chai.expect(worker.firstCall.calledWith(sinon.match.object, sinon.match.func)).to.be.true;268 });269 it('should have called worker with changed document as first argument', function() {270 chai.expect(worker.firstCall.args[0])271 .to.contain.subset({272 name: 'user_1',273 associates: [],274 location: {275 city: 'London',276 address: 'Wildersgade'277 }278 });279 });280 });281 describe('double externally modified property satisfies query', function() {282 before(function(done) {283 helper.loadFixture('users', function(err, result) {284 users = result;285 done(err);286 });287 });288 before(function(done) {289 usersCollection = helper.db.collection('users');290 worker = sinon.spy(function(document, callback) {291 callback(null, { $set: { 'location.address': 'Silkeborg Vej' } });292 });293 var delayedUsersCollection = helper.delayCollection(usersCollection);294 delayedUsersCollection.onfindandmodify = function(firstCallback) {295 usersCollection.update({ name: 'user_3' }, { $push: { 'associates': 'user_1' } }, function(err) {296 if(err) {297 return done(err);298 }299 delayedUsersCollection.onfindandmodify = function(secondCallback) {300 usersCollection.update({ name: 'user_3' }, { $set: { 'location.city': 'London' } }, function(err) {301 if(err) {302 return done(err);303 }304 delayedUsersCollection.onfindandmodify = null;305 secondCallback();306 });307 };308 firstCallback();309 });310 };311 var updateStream = createStream(worker);312 helper.readStream(updateStream, function(err, result) {313 patches = result;314 done(err);315 });316 updateStream.write({317 before: users[2],318 modifier: { $set: { 'location.address': 'Silkeborg Vej' } },319 collection: delayedUsersCollection,320 query: { name: 'user_3' }321 });322 updateStream.end();323 });324 before(function(done) {325 usersCollection.findOne({ name: 'user_3' }, function(err, result) {326 userDocument = result;327 done(err);328 });329 });330 it('should only patch one user', function() {331 chai.expect(patches.length).to.equal(1);332 });333 it('should have patch with changed before document', function() {334 chai.expect(patches[0])335 .to.have.property('before')336 .to.contain.subset({337 name: 'user_3',338 associates: ['user_2', 'user_1'],339 location: {340 city: 'London',341 address: 'Hovedgade'342 }343 });344 });345 it('should have patch with changed after document', function() {346 chai.expect(patches[0])347 .to.have.property('after')348 .to.contain.subset({349 name: 'user_3',350 associates: ['user_2', 'user_1'],351 location: {352 city: 'London',353 address: 'Silkeborg Vej'354 }355 });356 });357 it('should have modified document', function() {358 chai.expect(patches[0]).to.have.property('modified', true);359 });360 it('should not have skipped document', function() {361 chai.expect(patches[0]).to.have.property('skipped', false);362 });363 it('should have three attempts', function() {364 chai.expect(patches[0]).to.have.property('attempts', 3);365 });366 it('should have diff with only patched changes', function() {367 chai.expect(patches[0])368 .to.have.property('diff')369 .to.deep.equal({370 location: {371 address: 'updated'372 }373 });374 });375 it('should update externally changed document', function() {376 chai.expect(userDocument)377 .to.contain.subset({378 name: 'user_3',379 associates: ['user_2', 'user_1'],380 location: {381 city: 'London',382 address: 'Silkeborg Vej'383 }384 });385 });386 it('should have called worker twice', function() {387 chai.expect(worker.callCount).to.equal(2);388 });389 it('should have called worker with changed associates in first call', function() {390 chai.expect(worker.firstCall.args[0])391 .to.contain.subset({392 name: 'user_3',393 associates: ['user_2', 'user_1'],394 location: {395 city: 'Aarhus',396 address: 'Hovedgade'397 }398 });399 });400 it('should have called worker with changed city in second call', function() {401 chai.expect(worker.lastCall.args[0])402 .to.contain.subset({403 name: 'user_3',404 associates: ['user_2', 'user_1'],405 location: {406 city: 'London',407 address: 'Hovedgade'408 }409 });410 });411 });412 describe('externally modified property fails worker', function() {413 before(function(done) {414 helper.loadFixture('users', function(err, result) {415 users = result;416 done(err);417 });418 });419 before(function(done) {420 usersCollection = helper.db.collection('users');421 worker = sinon.spy(function(document, callback) {422 callback(null, null);423 });424 var delayedUsersCollection = helper.delayCollection(usersCollection);425 delayedUsersCollection.onfindandmodify = function(callback) {426 usersCollection.update({ name: 'user_1' }, { $set: { 'location.city': 'London' } }, function(err) {427 if(err) {428 return done(err);429 }430 callback();431 });432 };433 var updateStream = createStream(worker);434 helper.readStream(updateStream, function(err, result) {435 patches = result;436 done(err);437 });438 updateStream.write({439 before: users[0],440 modifier: { $set: { 'location.address': 'Silkeborg Vej' } },441 collection: delayedUsersCollection,442 query: { name: 'user_1' }443 });444 updateStream.end();445 });446 before(function(done) {447 usersCollection.findOne({ name: 'user_1' }, function(err, result) {448 userDocument = result;449 done(err);450 });451 });452 it('should only patch one user', function() {453 chai.expect(patches.length).to.equal(1);454 });455 it('should have patch with changed before document', function() {456 chai.expect(patches[0])457 .to.have.property('before')458 .to.contain.subset({459 name: 'user_1',460 associates: [],461 location: {462 city: 'London',463 address: 'Wildersgade'464 }465 });466 });467 it('should not have modified document', function() {468 chai.expect(patches[0]).to.have.property('modified', false);469 });470 it('should have skipped document', function() {471 chai.expect(patches[0]).to.have.property('skipped', true);472 });473 it('should have one attempt', function() {474 chai.expect(patches[0]).to.have.property('attempts', 1);475 });476 it('should have patch with no modifier', function() {477 chai.expect(patches[0].modifier).not.to.exist;478 });479 it('should not update externally changed document', function() {480 chai.expect(userDocument)481 .to.contain.subset({482 name: 'user_1',483 associates: [],484 location: {485 city: 'London',486 address: 'Wildersgade'487 }488 });489 });490 it('should have called worker', function() {491 chai.expect(worker.callCount).to.equal(1);492 });493 it('should have called worker with changed document as first argument', function() {494 chai.expect(worker.firstCall.args[0])495 .to.contain.subset({496 name: 'user_1',497 associates: [],498 location: {499 city: 'London',500 address: 'Wildersgade'501 }502 });503 });504 });505 describe('update using fallback', function() {506 before(function(done) {507 helper.loadFixture('users', function(err, result) {508 users = result;509 done(err);510 });511 });512 before(function(done) {513 usersCollection = helper.db.collection('users');514 worker = sinon.spy();515 var updateStream = createStream(worker);516 helper.readStream(updateStream, function(err, result) {517 patches = result;518 done(err);519 });520 updateStream.write({521 before: users[0],522 modifier: { $set: { 'location.address': 'Silkeborg Vej' } },523 collection: usersCollection,524 query: { name: 'user_1' },525 attempts: 5526 });527 updateStream.end();528 });529 before(function(done) {530 usersCollection.findOne({ name: 'user_1' }, function(err, result) {531 userDocument = result;532 done(err);533 });534 });535 it('should only patch one user', function() {536 chai.expect(patches.length).to.equal(1);537 });538 it('should have modified document', function() {539 chai.expect(patches[0]).to.have.property('modified', true);540 });541 it('should not have skipped document', function() {542 chai.expect(patches[0]).to.have.property('skipped', false);543 });544 it('should attempted one more time', function() {545 chai.expect(patches[0]).to.have.property('attempts', 6);546 });547 it('should update document', function() {548 chai.expect(userDocument)549 .to.contain.subset({550 name: 'user_1',551 associates: [],552 location: {553 city: 'Copenhagen',554 address: 'Silkeborg Vej'555 }556 });557 });558 it('should not have called worker', function() {559 chai.expect(worker.callCount).to.equal(0);560 });561 });562 describe('update fails using fallback', function() {563 before(function(done) {564 helper.loadFixture('users', function(err, result) {565 users = result;566 done(err);567 });568 });569 before(function(done) {570 usersCollection = helper.db.collection('users');571 worker = sinon.spy();572 var updateStream = createStream(worker);573 var user = users[0];574 helper.readStream(updateStream, function(err, result) {575 patches = result;576 done(err);577 });578 user.location.city = 'London';579 updateStream.write({580 before: user,581 modifier: { $set: { 'location.address': 'Silkeborg Vej' } },582 collection: usersCollection,583 query: { name: 'user_1' },584 attempts: 5585 });586 updateStream.end();587 });588 before(function(done) {589 usersCollection.findOne({ name: 'user_1' }, function(err, result) {590 userDocument = result;591 done(err);592 });593 });594 it('should only patch one user', function() {595 chai.expect(patches.length).to.equal(1);596 });597 it('should not have modified document', function() {598 chai.expect(patches[0]).to.have.property('modified', false);599 });600 it('should have skipped document', function() {601 chai.expect(patches[0]).to.have.property('skipped', true);602 });603 it('should attempted one more time', function() {604 chai.expect(patches[0]).to.have.property('attempts', 6);605 });606 it('should update document', function() {607 chai.expect(userDocument)608 .to.contain.subset({609 name: 'user_1',610 associates: [],611 location: {612 city: 'Copenhagen',613 address: 'Wildersgade'614 }615 });616 });617 it('should not have called worker', function() {618 chai.expect(worker.callCount).to.equal(0);619 });620 });621 describe('update using fallback (document with complex types)', function() {622 var comments, commentsCollection, commentDocument;623 before(function(done) {624 helper.loadFixture('comments', { copy: false }, function(err, result) {625 comments = result;626 done(err);627 });628 });629 before(function(done) {630 commentsCollection = helper.db.collection('comments');631 worker = sinon.spy();632 var updateStream = createStream(worker);633 helper.readStream(updateStream, function(err, result) {634 patches = result;635 done(err);636 });637 updateStream.write({638 before: comments[1],639 modifier: { $set: { content: '> User has been banned for this comment' } },640 collection: commentsCollection,641 query: { owner: 'user_1', title: 'title_2' },642 attempts: 5643 });644 updateStream.end();645 });646 before(function(done) {647 commentsCollection.findOne({ owner: 'user_1', title: 'title_2' }, function(err, result) {648 commentDocument = result;649 done(err);650 });651 });652 it('should only patch one comment', function() {653 chai.expect(patches.length).to.equal(1);654 });655 it('should have modified document', function() {656 chai.expect(patches[0]).to.have.property('modified', true);657 });658 it('should not have skipped document', function() {659 chai.expect(patches[0]).to.have.property('skipped', false);660 });661 it('should attempted one more time', function() {662 chai.expect(patches[0]).to.have.property('attempts', 6);663 });664 it('should update document', function() {665 chai.expect(commentDocument)666 .to.contain.subset({667 owner: 'user_1',668 album: 'album_1',669 title: 'title_2',670 content: '> User has been banned for this comment'671 });672 });673 it('should not have called worker', function() {674 chai.expect(worker.callCount).to.equal(0);675 });676 });677 });...
index.js
Source:index.js
1import * as fsb from "fs";2import * as path from "path";3import * as util from "util";4import { parse } from "./test_md.js";5import peggy from "../vendor/peggy.min.cjs";6import tap from "libtap";7import temp from "temp";8const fs = fsb.promises;9temp.track();10/**11 * Take trace events from Peggy and log them as test comments.12 */13class CommentTracer {14 constructor(test) {15 this.test = test;16 this.indent = 0;17 }18 log(event) {19 this.test.comment(20 `${event.location.start.line}:${event.location.start.column} ${event.type.padEnd(10)} ${"".padEnd(this.indent)}${event.rule}`21 );22 }23 trace(event) {24 switch (event.type) {25 case "rule.enter":26 this.log(event); // Note: *before* indent */27 this.indent++;28 break;29 case "rule.match":30 this.indent--;31 this.log(event);32 break;33 case "rule.fail":34 this.indent--;35 this.log(event);36 break;37 /* c8 ignore next 2 */38 default:39 throw new Error(`Invalid event type: "${event.type}".`);40 }41 }42}43async function endStream(stream, contents) {44 await util.promisify(stream.end.bind(stream))(contents);45 return stream;46}47function tempStream(dir, suffix, contents) {48 const s = temp.createWriteStream({49 dir,50 suffix,51 });52 return new Promise((resolve, reject) => {53 s.on("ready", () => resolve(s));54 s.on("error", reject);55 }).then(s => contents ? endStream(s, contents) : s);56}57// Only exported for testing58export function outputCodeBlock(updateStream, block) {59 const lim = (block && block.marks) || "```";60 if (block && block.src && block.src.includes(lim)) {61 throw new Error(`Invalid nesting. "${block.src}" includes "${lim}"`);62 }63 updateStream.write(lim);64 if (block && typeof block.lang === "string") {65 updateStream.write(block.lang);66 }67 updateStream.write("\n");68 if (block && (typeof block.src === "string")) {69 updateStream.write(block.src);70 updateStream.write("\n");71 }72 updateStream.write(lim);73 updateStream.write("\n\n");74}75function runSection(section, sectionTest, parser, opts, updateStream) {76 if (updateStream) {77 updateStream.write(`${section.title[0]}${section.title[1]}\n`);78 }79 for (const graf of section.grafs) {80 if (updateStream) {81 if (typeof graf === "string") {82 updateStream.write(graf);83 continue;84 } else {85 const tags = Object86 .keys(graf.input.tags)87 .reduce((t, v) => t + ` (${v})`, "");88 if (graf.input.rule) {89 updateStream.write(`Input to rule \`${graf.input.rule}\`:${tags}\n`);90 } else {91 updateStream.write(`Input:${tags}\n`);92 }93 outputCodeBlock(updateStream, graf.input);94 }95 }96 if (typeof graf === "string") {97 continue;98 }99 if (opts.only && !graf.input.tags.only) {100 // We're in only mode, and this test isn't one of the only.101 if (graf.output && updateStream) {102 updateStream.write("Output:\n");103 outputCodeBlock(updateStream, graf.output);104 }105 continue;106 }107 const grammarSource = new peggy.GrammarLocation(108 graf.input.codeLocation.source,109 graf.input.codeLocation.start110 );111 const src = graf.input.src;112 const ruleName = graf.input.rule || "default";113 // If we are forced and not updating, don't skip.114 // If we are force-updating, still don't run skipped tests.115 if (graf.input.tags.skip && (!opts.force || updateStream)) {116 sectionTest.skip(ruleName);117 if (updateStream && graf.output) {118 updateStream.write("Output:\n");119 outputCodeBlock(updateStream, graf.output);120 }121 continue;122 }123 const output = {};124 try {125 const parseOpts = {126 grammarSource,127 tracer: graf.input.tags.trace128 ? new CommentTracer(sectionTest)129 : { trace: () => 0 },130 };131 if (graf.input.rule) {132 parseOpts.startRule = graf.input.rule;133 } else if (opts.defaultRule) {134 parseOpts.startRule = opts.defaultRule;135 } // Else don't set it136 const parseResult = parser.parse(src, parseOpts);137 output.src = util.inspect(parseResult, {138 depth: Infinity,139 color: false,140 maxArrayLength: Infinity,141 maxStringLength: Infinity,142 compact: false,143 sorted: true,144 numericSeparator: false,145 });146 output.lang = "js";147 } catch (e) {148 if (typeof e.format === "function") {149 output.src = e.format([{ source: grammarSource, text: src }]);150 } else {151 output.src = e.message;152 }153 }154 if (updateStream) {155 updateStream.write("Output:\n");156 if (!opts.force && graf.output) {157 outputCodeBlock(updateStream, graf.output);158 sectionTest.equal(output.src, graf.output.src, ruleName, {159 at: `${graf.input.codeLocation.source}:${graf.input.codeLocation.start.line}:${graf.input.codeLocation.start.column}`,160 });161 } else {162 if (output.src.includes("```")) {163 output.marks = "~~~";164 }165 outputCodeBlock(updateStream, output);166 sectionTest.pass(`wrote: ${output}`);167 }168 } else if (graf.output) {169 sectionTest.equal(output.src, graf.output.src, ruleName, {170 at: `${graf.input.codeLocation.source}:${graf.input.codeLocation.start.line}:${graf.input.codeLocation.start.column}`,171 });172 } else {173 sectionTest.todo(ruleName);174 sectionTest.comment(output.src);175 }176 }177}178function runTests(suite, parser, opts, updateStream) {179 let secNum = 0;180 let sections = 0;181 let only = 0;182 for (const section of suite.sections) {183 section.numTests = 0;184 section.numOnly = 0;185 for (const graf of section.grafs) {186 if (typeof graf === "object") {187 if (section.numTests++ === 0) {188 sections++;189 }190 if (graf.input.tags.only) {191 if (section.numOnly++ === 0) {192 only++;193 }194 }195 }196 }197 }198 opts.only = only > 0;199 tap.plan(opts.only ? only : sections);200 if (suite.meta.updated) {201 tap.comment(`Updated: ${suite.meta.updated}`);202 }203 for (const section of suite.sections) {204 secNum++;205 if ((opts.only && (section.numOnly > 0))206 || (!opts.only && (section.numTests > 0))) {207 tap.test(208 (section.title[1] || `Section ${secNum}`).trim(),209 sectionTest => {210 sectionTest.plan((only > 0) ? section.numOnly : section.numTests);211 runSection(212 section,213 sectionTest,214 parser,215 opts,216 updateStream217 );218 sectionTest.end();219 }220 );221 } else if (updateStream) {222 runSection(223 section,224 null,225 parser,226 opts,227 updateStream228 );229 }230 }231 tap.end();232 return tap.passing() ? 0 : 1;233}234export async function testFile(opts) {235 if (opts.quiet) {236 process.stdout.write = () => 0;237 }238 let grammarSource = opts.testFile;239 let src = await fs.readFile(grammarSource, "utf8");240 try {241 const testDir = path.dirname(grammarSource);242 const suite = parse(src, {243 grammarSource,244 });245 if (suite.meta) {246 opts = { ...suite.meta, ...opts };247 if (suite.meta.outDir) {248 opts.outDir = path.resolve(testDir, suite.meta.outDir);249 }250 }251 if (!opts.source) {252 throw new Error("source not specified");253 }254 const grammarFile = path.join(testDir, opts.source);255 if (!opts.outDir) {256 opts.outDir = path.dirname(grammarFile);257 }258 grammarSource = path.relative(opts.outDir, grammarFile);259 src = await fs.readFile(grammarFile, "utf8");260 const grammar = peggy.generate(src, {261 allowedStartRules: ["*"],262 format: "es",263 output: "source-with-inline-map",264 trace: true,265 grammarSource,266 });267 // Wite temp file with JS output, then import it.268 const tmp = await tempStream(269 opts.outDir,270 ".mjs", // Force module loading, since we're using "es" above271 grammar272 );273 const instrumented = await import("file://" + path.resolve(process.cwd(), tmp.path));274 let updateStream = null;275 if (opts.update) {276 suite.meta = suite.meta || {};277 suite.meta.updated = new Date().toISOString();278 updateStream = await tempStream(testDir, path.extname(opts.testFile));279 updateStream.write("---\n");280 for (const [key, value] of Object.entries(suite.meta)) {281 updateStream.write(`${key}: ${value}\n`);282 }283 updateStream.write("---\n\n");284 for (const i of suite.intro) {285 updateStream.write(i);286 }287 }288 const error = runTests(suite, instrumented, opts, updateStream);289 if (updateStream) {290 await endStream(updateStream);291 if (error === 0) {292 await fs.rename(updateStream.path, opts.testFile);293 }294 }295 return error;296 } catch (e) {297 if (typeof e.format === "function") {298 console.log(e.format([{ source: grammarSource, text: src }]));299 return 2;300 } else {301 throw e;302 }303 }304}305export async function generateFile(opts) {306 try {307 await fs.stat(opts.testFile);308 if (!opts.force) {309 console.error(`File "${opts.testFile}" already exists. Use --force to overwrite.`);310 return 1;311 }312 } catch (ignored) {313 // Ignored314 }315 const grammarSource = opts.generate;316 const src = await fs.readFile(grammarSource, "utf8");317 try {318 const ast = peggy.parser.parse(src, {319 grammarSource,320 });321 const updateStream = await tempStream(322 path.dirname(opts.testFile),323 path.extname(opts.testFile)324 );325 const defaultRule = ast.rules[0].name;326 updateStream.write(`\327---328source: ${path.relative(path.dirname(opts.testFile), grammarSource)}329defaultRule: ${defaultRule}330updated: ${new Date().toISOString()}331---332# Tests for full grammar for ${grammarSource}333Use this section to test full inputs to the grammar.334Input: (skip)335\`\`\`336\`\`\`337## Tests for each rule338`);339 for (const rule of ast.rules) {340 if (rule.name === defaultRule) {341 continue;342 }343 updateStream.write(`344Input to rule \`${rule.name}\`: (skip)345\`\`\`346\`\`\`347`);348 }349 await endStream(updateStream);350 await fs.rename(updateStream.path, opts.testFile);351 return 0;352 } catch (e) {353 if (typeof e.format === "function") {354 console.log(e.format([{ source: grammarSource, text: src }]));355 return 2;356 } else {357 throw e;358 }359 }...
update-stream.test.js
Source:update-stream.test.js
1const helper = require('../helper.js');2const { UpdateStream } = require('../../src');3test('Stream should work when 0 records to update', async () => {4 const readStream = helper.getReadStream(0);5 const esClient = {6 bulk: jest.fn((opts, done) => {7 done(null, {});8 }),9 };10 const updateStream = new UpdateStream({11 esClient,12 esIndex: 'test',13 esType: 'type1',14 });15 await new Promise((resolve, reject) => {16 readStream17 .pipe(updateStream)18 .on('error', reject)19 .on('finish', () => {20 expect(esClient.bulk).toHaveBeenCalledTimes(0);21 resolve();22 });23 });24});25test('Stream should work when 1 record to update', async () => {26 const readStream = helper.getReadStream(1);27 const esClient = {28 bulk: jest.fn((opts, done) => {29 done(null, {});30 }),31 };32 const updateStream = new UpdateStream({33 esClient,34 esIndex: 'test',35 esType: 'type1',36 });37 await new Promise((resolve, reject) => {38 readStream39 .pipe(updateStream)40 .on('error', reject)41 .on('finish', () => {42 expect(esClient.bulk).toHaveBeenCalledTimes(1);43 const firstCallOpts = esClient.bulk.mock.calls[0][0];44 expect(firstCallOpts);45 expect(firstCallOpts.index).toBe('test');46 expect(firstCallOpts.type).toBe('type1');47 expect(firstCallOpts.refresh).toStrictEqual(true);48 expect(firstCallOpts.body.length).toBe(2);49 expect(firstCallOpts.body[0].update).toBeTruthy();50 // eslint-disable-next-line no-underscore-dangle51 expect(firstCallOpts.body[0].update._id).toBeTruthy();52 resolve();53 });54 });55});56test('Stream should work when 100 records to index', async () => {57 const readStream = helper.getReadStream(100);58 const esClient = {59 bulk: jest.fn((opts, done) => {60 done(null, {});61 }),62 };63 const updateStream = new UpdateStream({64 esClient,65 esIndex: 'test',66 esType: 'type1',67 });68 await new Promise((resolve, reject) => {69 readStream70 .pipe(updateStream)71 .on('error', reject)72 .on('finish', () => {73 expect(esClient.bulk).toHaveBeenCalledTimes(1);74 const firstCallOpts = esClient.bulk.mock.calls[0][0];75 expect(firstCallOpts);76 expect(firstCallOpts.index).toBe('test');77 expect(firstCallOpts.type).toBe('type1');78 expect(firstCallOpts.refresh).toStrictEqual(true);79 expect(firstCallOpts.body.length).toBe(200);80 resolve();81 });82 });83});84test('Stream shoud work when 101 records to update', async () => {85 const readStream = helper.getReadStream(101);86 const esClient = {87 bulk: jest.fn((opts, done) => {88 done(null, {});89 }),90 };91 const updateStream = new UpdateStream({92 esClient,93 esIndex: 'test',94 esType: 'type1',95 });96 await new Promise((resolve, reject) => {97 readStream98 .pipe(updateStream)99 .on('error', reject)100 .on('finish', () => {101 expect(esClient.bulk).toHaveBeenCalledTimes(2);102 const secondCallOpts = esClient.bulk.mock.calls[1][0];103 expect(secondCallOpts);104 expect(secondCallOpts.index).toBe('test');105 expect(secondCallOpts.type).toBe('type1');106 expect(secondCallOpts.refresh).toStrictEqual(true);107 expect(secondCallOpts.body.length).toBe(2);108 resolve();109 });110 });111});112test('Stream should work when 1000 records to index', async () => {113 const readStream = helper.getReadStream(1000);114 const esClient = {115 bulk: jest.fn((opts, done) => {116 done(null, {});117 }),118 };119 const updateStream = new UpdateStream({120 esClient,121 esIndex: 'test',122 esType: 'type1',123 });124 await new Promise((resolve, reject) => {125 readStream126 .pipe(updateStream)127 .on('error', reject)128 .on('finish', () => {129 expect(esClient.bulk).toHaveBeenCalledTimes(10);130 const tenthCallOpts = esClient.bulk.mock.calls[9][0];131 expect(tenthCallOpts);132 expect(tenthCallOpts.index).toBe('test');133 expect(tenthCallOpts.type).toBe('type1');134 expect(tenthCallOpts.refresh).toStrictEqual(true);135 expect(tenthCallOpts.body.length).toBe(200);136 resolve();137 });138 });139});140test('Stream should return error when bulk fails', async () => {141 const readStream = helper.getReadStream(1);142 const esClient = {143 bulk: jest.fn((opts, done) => {144 done(new Error('Should fail'));145 }),146 };147 const updateStream = new UpdateStream({148 esClient,149 esIndex: 'test',150 esType: 'type1',151 });152 await new Promise((resolve, reject) => {153 readStream154 .pipe(updateStream)155 .on('error', (err) => {156 expect(err.message).toBe('Should fail');157 resolve();158 })159 .on('finish', () => {160 reject();161 });162 });163});164test('Stream should return error when bulk contains errors', async () => {165 const readStream = helper.getReadStream(1);166 const esClient = {167 bulk: jest.fn((opts, done) => {168 done(null, { errors: true });169 }),170 };171 const updateStream = new UpdateStream({172 esClient,173 esIndex: 'test',174 esType: 'type1',175 });176 await new Promise((resolve, reject) => {177 readStream178 .pipe(updateStream)179 .on('error', (err) => {180 expect(err.message).toBe('Errors in bulk request');181 resolve();182 })183 .on('finish', () => {184 reject();185 });186 });...
Using AI Code Generation
1var BestBuy = require('bestbuy');2var bestbuy = new BestBuy('your api key here');3var fs = require('fs');4var stream = fs.createWriteStream('test4.txt');5var options = {6};7bestbuy.products('(search=smartphone)', options, function(error, data) {8 if (error) {9 console.log(error);10 } else {11 console.log(data);12 }13}).pipe(stream);
Using AI Code Generation
1var bb = require('bestbuy')('mykey');2var stream = bb.stream('products(upc=012345678901)', {show: 'name,sku'});3stream.on('data', function (data) {4 console.log(data);5});6stream.on('end', function () {7 console.log('end');8});9stream.on('error', function (err) {10 console.error(err);11});12var bb = require('bestbuy')('mykey');13var stream = bb.stream('products(upc=012345678901)', {show: 'name,sku'});14stream.on('data', function (data) {15 console.log(data);16});17stream.on('end', function () {18 console.log('end');19});20stream.on('error', function (err) {21 console.error(err);22});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!