Best JavaScript code snippet using sinon
index.test.js
Source:index.test.js  
...59          cli: { log: () => {} }60        },61        {}62      );63      var sandbox = sinon.createSandbox();64      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);65      var copyStub = sandbox.stub(fse, "copyAsync");66      var writeStub = sandbox.stub(fse, "writeFileAsync");67      var procStub = sandbox.stub(child_process, "spawnSync");68      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {69        expect(hasbinStub.calledWith("python2.7")).to.be.true;70        expect(copyStub.called).to.be.false;71        expect(writeStub.called).to.be.false;72        expect(procStub.called).to.be.false;73        sandbox.restore();74      });75    });76    it("packages wsgi handler", () => {77      var plugin = new Plugin(78        {79          config: { servicePath: "/tmp" },80          service: {81            provider: { runtime: "python2.7" },82            custom: { wsgi: { app: "api.app" } }83          },84          classes: { Error: Error },85          cli: { log: () => {} }86        },87        {}88      );89      var sandbox = sinon.createSandbox();90      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);91      var copyStub = sandbox.stub(fse, "copyAsync");92      var writeStub = sandbox.stub(fse, "writeFileAsync");93      var procStub = sandbox94        .stub(child_process, "spawnSync")95        .returns({ status: 0 });96      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {97        expect(hasbinStub.calledWith("python2.7")).to.be.true;98        expect(99          copyStub.calledWith(100            path.resolve(__dirname, "wsgi_handler.py"),101            "/tmp/wsgi_handler.py"102          )103        ).to.be.true;104        expect(105          copyStub.calledWith(106            path.resolve(__dirname, "serverless_wsgi.py"),107            "/tmp/serverless_wsgi.py"108          )109        ).to.be.true;110        expect(writeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;111        expect(JSON.parse(writeStub.lastCall.args[1])).to.deep.equal({112          app: "api.app"113        });114        expect(115          procStub.calledWith("python2.7", [116            path.resolve(__dirname, "requirements.py"),117            path.resolve(__dirname, "requirements.txt"),118            "/tmp/.requirements"119          ])120        ).to.be.true;121        sandbox.restore();122        expect(plugin.serverless.service.package.include).to.have.members([123          "wsgi_handler.py",124          "serverless_wsgi.py",125          ".serverless-wsgi"126        ]);127        expect(plugin.serverless.service.package.exclude).to.have.members([128          ".requirements/**"129        ]);130      });131    });132    it("packages wsgi handler with additional text mime types", () => {133      var plugin = new Plugin(134        {135          config: { servicePath: "/tmp" },136          service: {137            provider: { runtime: "python2.7" },138            custom: {139              wsgi: {140                app: "api.app",141                textMimeTypes: ["application/custom+json"]142              }143            }144          },145          classes: { Error: Error },146          cli: { log: () => {} }147        },148        {}149      );150      var sandbox = sinon.createSandbox();151      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);152      sandbox.stub(fse, "copyAsync");153      var writeStub = sandbox.stub(fse, "writeFileAsync");154      sandbox.stub(child_process, "spawnSync").returns({ status: 0 });155      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {156        expect(hasbinStub.calledWith("python2.7")).to.be.true;157        expect(writeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;158        expect(JSON.parse(writeStub.lastCall.args[1])).to.deep.equal({159          app: "api.app",160          text_mime_types: ["application/custom+json"]161        });162        sandbox.restore();163      });164    });165    it("falls back to default python if runtime version is not found", () => {166      var plugin = new Plugin(167        {168          config: { servicePath: "/tmp" },169          service: {170            provider: { runtime: "python3.6" },171            custom: {172              wsgi: {173                app: "api.app"174              }175            }176          },177          classes: { Error: Error },178          cli: { log: () => {} }179        },180        {}181      );182      var sandbox = sinon.createSandbox();183      var hasbinStub = sandbox.stub(hasbin, "sync").returns(false);184      sandbox.stub(fse, "copyAsync");185      sandbox.stub(fse, "writeFileAsync");186      var procStub = sandbox187        .stub(child_process, "spawnSync")188        .returns({ status: 0 });189      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {190        expect(hasbinStub.calledWith("python3.6")).to.be.true;191        expect(192          procStub.calledWith("python", [193            path.resolve(__dirname, "requirements.py"),194            path.resolve(__dirname, "requirements.txt"),195            "/tmp/.requirements"196          ])197        ).to.be.true;198        sandbox.restore();199      });200    });201    it("cleans up after deployment", () => {202      var plugin = new Plugin(203        {204          config: { servicePath: "/tmp" },205          service: {206            provider: { runtime: "python2.7" },207            custom: { wsgi: { app: "api.app" } }208          },209          classes: { Error: Error },210          cli: { log: () => {} }211        },212        {}213      );214      var sandbox = sinon.createSandbox();215      var removeStub = sandbox.stub(fse, "removeAsync");216      plugin.hooks["after:package:createDeploymentArtifacts"]().then(() => {217        expect(removeStub.calledWith("/tmp/wsgi_handler.py")).to.be.true;218        expect(removeStub.calledWith("/tmp/serverless_wsgi.py")).to.be.true;219        expect(removeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;220        expect(removeStub.calledWith("/tmp/.requirements")).to.be.false;221        sandbox.restore();222      });223    });224    it("packages wsgi handler with individual include and exclude patterns", () => {225      var plugin = new Plugin(226        {227          config: { servicePath: "/tmp" },228          service: {229            provider: { runtime: "python2.7" },230            package: { individually: true },231            custom: { wsgi: { app: "web/api.app" } },232            functions: {233              api: { handler: "wsgi.handler" }234            }235          },236          classes: { Error: Error },237          cli: { log: () => {} }238        },239        {}240      );241      var sandbox = sinon.createSandbox();242      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);243      var copyStub = sandbox.stub(fse, "copyAsync");244      var writeStub = sandbox.stub(fse, "writeFileAsync");245      var symlinkStub = sandbox.stub(fse, "symlinkSync");246      sandbox.stub(fse, "readdirSync").returns(["flask", "werkzeug"]);247      sandbox.stub(fse, "existsSync").returns(true);248      var procStub = sandbox249        .stub(child_process, "spawnSync")250        .returns({ status: 0 });251      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {252        expect(hasbinStub.calledWith("python2.7")).to.be.true;253        expect(254          copyStub.calledWith(255            path.resolve(__dirname, "wsgi_handler.py"),256            "/tmp/wsgi_handler.py"257          )258        ).to.be.true;259        expect(260          copyStub.calledWith(261            path.resolve(__dirname, "serverless_wsgi.py"),262            "/tmp/serverless_wsgi.py"263          )264        ).to.be.true;265        expect(writeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;266        expect(JSON.parse(writeStub.lastCall.args[1])).to.deep.equal({267          app: "web/api.app"268        });269        expect(symlinkStub.called).to.be.true;270        expect(271          procStub.calledWith("python2.7", [272            path.resolve(__dirname, "requirements.py"),273            path.resolve(__dirname, "requirements.txt"),274            "/tmp/web/requirements.txt",275            "/tmp/web/.requirements"276          ])277        ).to.be.true;278        sandbox.restore();279        expect(plugin.serverless.service.package.include).to.have.members([280          "wsgi_handler.py",281          "serverless_wsgi.py",282          ".serverless-wsgi",283          "web/flask",284          "web/flask/**",285          "web/werkzeug",286          "web/werkzeug/**"287        ]);288        expect(plugin.serverless.service.package.exclude).to.have.members([289          "web/.requirements/**"290        ]);291      });292    });293    it("packages wsgi handler in individually packaged modules by serverless-python-requirements", () => {294      var plugin = new Plugin(295        {296          config: { servicePath: "/tmp" },297          service: {298            provider: { runtime: "python2.7" },299            package: { individually: true },300            custom: { wsgi: { app: "web/api.app" } },301            functions: {302              api: { handler: "wsgi.handler", module: "web" }303            }304          },305          classes: { Error: Error },306          cli: { log: () => {} }307        },308        {}309      );310      var sandbox = sinon.createSandbox();311      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);312      var copyStub = sandbox.stub(fse, "copyAsync");313      var writeStub = sandbox.stub(fse, "writeFileAsync");314      var symlinkStub = sandbox.stub(fse, "symlinkSync");315      sandbox.stub(fse, "readdirSync").returns(["flask", "werkzeug"]);316      sandbox.stub(fse, "existsSync").returns(true);317      var procStub = sandbox318        .stub(child_process, "spawnSync")319        .returns({ status: 0 });320      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {321        expect(hasbinStub.calledWith("python2.7")).to.be.true;322        expect(323          copyStub.calledWith(324            path.resolve(__dirname, "wsgi_handler.py"),325            "/tmp/web/wsgi_handler.py"326          )327        ).to.be.true;328        expect(329          copyStub.calledWith(330            path.resolve(__dirname, "serverless_wsgi.py"),331            "/tmp/web/serverless_wsgi.py"332          )333        ).to.be.true;334        expect(writeStub.calledWith("/tmp/web/.serverless-wsgi")).to.be.true;335        expect(JSON.parse(writeStub.lastCall.args[1])).to.deep.equal({336          app: "api.app"337        });338        expect(symlinkStub.called).to.be.true;339        expect(340          procStub.calledWith("python2.7", [341            path.resolve(__dirname, "requirements.py"),342            path.resolve(__dirname, "requirements.txt"),343            "/tmp/web/requirements.txt",344            "/tmp/web/.requirements"345          ])346        ).to.be.true;347        sandbox.restore();348        expect(plugin.serverless.service.package.include).to.have.members([349          "web/wsgi_handler.py",350          "web/serverless_wsgi.py",351          "web/.serverless-wsgi",352          "web/flask",353          "web/flask/**",354          "web/werkzeug",355          "web/werkzeug/**"356        ]);357        expect(plugin.serverless.service.package.exclude).to.have.members([358          "web/.requirements/**"359        ]);360      });361    });362  });363  describe("requirements", () => {364    it("packages user requirements for wsgi app", () => {365      var plugin = new Plugin(366        {367          config: { servicePath: "/tmp" },368          service: {369            provider: { runtime: "python2.7" },370            custom: { wsgi: { app: "api.app" } },371            package: { include: ["sample.txt"] }372          },373          classes: { Error: Error },374          cli: { log: () => {} }375        },376        {}377      );378      var sandbox = sinon.createSandbox();379      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);380      var copyStub = sandbox.stub(fse, "copyAsync");381      var writeStub = sandbox.stub(fse, "writeFileAsync");382      var symlinkStub = sandbox.stub(fse, "symlinkSync");383      sandbox.stub(fse, "readdirSync").returns(["flask", "werkzeug"]);384      sandbox.stub(fse, "existsSync").returns(true);385      var procStub = sandbox386        .stub(child_process, "spawnSync")387        .returns({ status: 0 });388      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {389        expect(hasbinStub.calledWith("python2.7")).to.be.true;390        expect(copyStub.called).to.be.true;391        expect(writeStub.called).to.be.true;392        expect(symlinkStub.called).to.be.true;393        expect(394          procStub.calledWith("python2.7", [395            path.resolve(__dirname, "requirements.py"),396            path.resolve(__dirname, "requirements.txt"),397            "/tmp/requirements.txt",398            "/tmp/.requirements"399          ])400        ).to.be.true;401        expect(plugin.serverless.service.package.include).to.have.members([402          "sample.txt",403          "wsgi_handler.py",404          "serverless_wsgi.py",405          ".serverless-wsgi",406          "flask",407          "flask/**",408          "werkzeug",409          "werkzeug/**"410        ]);411        expect(plugin.serverless.service.package.exclude).to.have.members([412          ".requirements/**"413        ]);414        sandbox.restore();415      });416    });417    it("allows setting the python binary", () => {418      var plugin = new Plugin(419        {420          config: { servicePath: "/tmp" },421          service: {422            provider: { runtime: "python2.7" },423            custom: { wsgi: { app: "api.app", pythonBin: "my-python" } },424            package: { include: ["sample.txt"] }425          },426          classes: { Error: Error },427          cli: { log: () => {} }428        },429        {}430      );431      var sandbox = sinon.createSandbox();432      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);433      var copyStub = sandbox.stub(fse, "copyAsync");434      var writeStub = sandbox.stub(fse, "writeFileAsync");435      var symlinkStub = sandbox.stub(fse, "symlinkSync");436      sandbox.stub(fse, "readdirSync").returns(["flask"]);437      sandbox.stub(fse, "existsSync").returns(true);438      var procStub = sandbox439        .stub(child_process, "spawnSync")440        .returns({ status: 0 });441      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {442        expect(hasbinStub.called).to.be.false;443        expect(copyStub.called).to.be.true;444        expect(writeStub.called).to.be.true;445        expect(symlinkStub.called).to.be.true;446        expect(447          procStub.calledWith("my-python", [448            path.resolve(__dirname, "requirements.py"),449            path.resolve(__dirname, "requirements.txt"),450            "/tmp/requirements.txt",451            "/tmp/.requirements"452          ])453        ).to.be.true;454        expect(plugin.serverless.service.package.include).to.have.members([455          "sample.txt",456          "wsgi_handler.py",457          "serverless_wsgi.py",458          ".serverless-wsgi",459          "flask",460          "flask/**"461        ]);462        expect(plugin.serverless.service.package.exclude).to.have.members([463          ".requirements/**"464        ]);465        sandbox.restore();466      });467    });468    it("packages user requirements for wsgi app inside directory", () => {469      var plugin = new Plugin(470        {471          config: { servicePath: "/tmp" },472          service: {473            provider: {},474            custom: { wsgi: { app: "api/api.app" } }475          },476          classes: { Error: Error },477          cli: { log: () => {} }478        },479        {}480      );481      var sandbox = sinon.createSandbox();482      var copyStub = sandbox.stub(fse, "copyAsync");483      var writeStub = sandbox.stub(fse, "writeFileAsync");484      sandbox.stub(fse, "symlinkSync");485      sandbox.stub(fse, "readdirSync").returns(["werkzeug"]);486      sandbox.stub(fse, "existsSync").returns(true);487      var procStub = sandbox488        .stub(child_process, "spawnSync")489        .returns({ status: 0 });490      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {491        expect(copyStub.called).to.be.true;492        expect(writeStub.called).to.be.true;493        expect(494          procStub.calledWith("python", [495            path.resolve(__dirname, "requirements.py"),496            path.resolve(__dirname, "requirements.txt"),497            "/tmp/api/requirements.txt",498            "/tmp/api/.requirements"499          ])500        ).to.be.true;501        expect(plugin.serverless.service.package.include).to.have.members([502          "wsgi_handler.py",503          "serverless_wsgi.py",504          ".serverless-wsgi",505          "api/werkzeug",506          "api/werkzeug/**"507        ]);508        expect(plugin.serverless.service.package.exclude).to.have.members([509          "api/.requirements/**"510        ]);511        sandbox.restore();512      });513    });514    it("throws an error when a file already exists in the service root", () => {515      var plugin = new Plugin(516        {517          config: { servicePath: "/tmp" },518          service: { provider: { runtime: "python2.7" } },519          classes: { Error: Error },520          cli: { log: () => {} }521        },522        {}523      );524      var sandbox = sinon.createSandbox();525      sandbox.stub(hasbin, "sync").returns(true);526      sandbox.stub(fse, "copyAsync");527      sandbox.stub(fse, "writeFileAsync");528      sandbox.stub(fse, "symlinkSync").throws();529      sandbox.stub(fse, "readlinkSync").throws();530      sandbox.stub(fse, "readdirSync").returns(["flask"]);531      sandbox.stub(fse, "existsSync").returns(true);532      sandbox.stub(child_process, "spawnSync").returns({ status: 0 });533      expect(534        plugin.hooks["before:package:createDeploymentArtifacts"]()535      ).to.be.rejected.and.notify(() => {536        sandbox.restore();537      });538    });539    it("throws an error when a conflicting symlink already exists in the service root", () => {540      var plugin = new Plugin(541        {542          config: { servicePath: "/tmp" },543          service: { provider: { runtime: "python2.7" } },544          classes: { Error: Error },545          cli: { log: () => {} }546        },547        {}548      );549      var sandbox = sinon.createSandbox();550      sandbox.stub(hasbin, "sync").returns(true);551      sandbox.stub(fse, "copyAsync");552      sandbox.stub(fse, "writeFileAsync");553      sandbox.stub(fse, "symlinkSync").throws();554      sandbox.stub(fse, "readlinkSync").returns("not-flask");555      sandbox.stub(fse, "readdirSync").returns(["flask"]);556      sandbox.stub(fse, "existsSync").returns(true);557      sandbox.stub(child_process, "spawnSync").returns({ status: 0 });558      expect(559        plugin.hooks["before:package:createDeploymentArtifacts"]()560      ).to.be.rejected.and.notify(() => {561        sandbox.restore();562      });563    });564    it("packages user requirements for non-wsgi app", () => {565      var plugin = new Plugin(566        {567          config: { servicePath: "/tmp" },568          service: { provider: { runtime: "python2.7" } },569          classes: { Error: Error },570          cli: { log: () => {} }571        },572        {}573      );574      var sandbox = sinon.createSandbox();575      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);576      var copyStub = sandbox.stub(fse, "copyAsync");577      var writeStub = sandbox.stub(fse, "writeFileAsync");578      sandbox.stub(fse, "symlinkSync").throws();579      sandbox.stub(fse, "readlinkSync").returns("/tmp/.requirements/flask");580      sandbox.stub(fse, "readdirSync").returns(["flask"]);581      sandbox.stub(fse, "existsSync").returns(true);582      var procStub = sandbox583        .stub(child_process, "spawnSync")584        .returns({ status: 0 });585      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {586        expect(hasbinStub.calledWith("python2.7")).to.be.true;587        expect(copyStub.called).to.be.false;588        expect(writeStub.called).to.be.false;589        expect(590          procStub.calledWith("python2.7", [591            path.resolve(__dirname, "requirements.py"),592            "/tmp/requirements.txt",593            "/tmp/.requirements"594          ])595        ).to.be.true;596        sandbox.restore();597      });598    });599    it("packages user requirements with additional pip args", () => {600      var plugin = new Plugin(601        {602          config: { servicePath: "/tmp" },603          service: {604            provider: { runtime: "python3.6" },605            custom: { wsgi: { pipArgs: "--no-deps 'imaginary \"value\"'" } }606          },607          classes: { Error: Error },608          cli: { log: () => {} }609        },610        {}611      );612      var sandbox = sinon.createSandbox();613      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);614      var copyStub = sandbox.stub(fse, "copyAsync");615      var writeStub = sandbox.stub(fse, "writeFileAsync");616      sandbox.stub(fse, "symlinkSync").throws();617      sandbox.stub(fse, "readlinkSync").returns("/tmp/.requirements/flask");618      sandbox.stub(fse, "readdirSync").returns(["flask"]);619      sandbox.stub(fse, "existsSync").returns(true);620      var procStub = sandbox621        .stub(child_process, "spawnSync")622        .returns({ status: 0 });623      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {624        expect(hasbinStub.calledWith("python3.6")).to.be.true;625        expect(copyStub.called).to.be.false;626        expect(writeStub.called).to.be.false;627        expect(628          procStub.calledWith("python3.6", [629            path.resolve(__dirname, "requirements.py"),630            "--pip-args",631            "--no-deps 'imaginary \"value\"'",632            "/tmp/requirements.txt",633            "/tmp/.requirements"634          ])635        ).to.be.true;636        sandbox.restore();637      });638    });639    it("skips packaging for non-wsgi app without user requirements", () => {640      var plugin = new Plugin(641        {642          config: { servicePath: "/tmp" },643          service: { provider: { runtime: "python2.7" } },644          classes: { Error: Error },645          cli: { log: () => {} }646        },647        {}648      );649      var sandbox = sinon.createSandbox();650      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);651      var copyStub = sandbox.stub(fse, "copyAsync");652      var writeStub = sandbox.stub(fse, "writeFileAsync");653      sandbox.stub(fse, "existsSync").returns(false);654      var procStub = sandbox655        .stub(child_process, "spawnSync")656        .returns({ status: 0 });657      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {658        expect(hasbinStub.calledWith("python2.7")).to.be.true;659        expect(copyStub.called).to.be.false;660        expect(writeStub.called).to.be.false;661        expect(procStub.called).to.be.false;662        expect(plugin.serverless.service.package.exclude).to.have.members([663          ".requirements/**"664        ]);665        sandbox.restore();666      });667    });668    it("rejects with non successful exit code", () => {669      var plugin = new Plugin(670        {671          config: { servicePath: "/tmp" },672          service: { provider: { runtime: "python2.7" } },673          classes: { Error: Error },674          cli: { log: () => {} }675        },676        {}677      );678      var sandbox = sinon.createSandbox();679      sandbox.stub(hasbin, "sync").returns(true);680      sandbox.stub(fse, "existsSync").returns(true);681      sandbox.stub(child_process, "spawnSync").returns({ status: 1 });682      expect(683        plugin.hooks["before:package:createDeploymentArtifacts"]()684      ).to.eventually.be.rejected.and.notify(() => {685        sandbox.restore();686      });687    });688    it("rejects with stderr output", () => {689      var plugin = new Plugin(690        {691          config: { servicePath: "/tmp" },692          service: { provider: { runtime: "python2.7" } },693          classes: { Error: Error },694          cli: { log: () => {} }695        },696        {}697      );698      var sandbox = sinon.createSandbox();699      sandbox.stub(hasbin, "sync").returns(true);700      sandbox.stub(fse, "existsSync").returns(true);701      sandbox702        .stub(child_process, "spawnSync")703        .returns({ status: 0, error: "fail" });704      expect(705        plugin.hooks["before:package:createDeploymentArtifacts"]()706      ).to.eventually.be.rejected.and.notify(() => {707        sandbox.restore();708      });709    });710    it("handles missing Python binary error", () => {711      var plugin = new Plugin(712        {713          config: { servicePath: "/tmp" },714          service: { provider: { runtime: "python2.7" } },715          classes: { Error: Error },716          cli: { log: () => {} }717        },718        {}719      );720      var sandbox = sinon.createSandbox();721      sandbox.stub(hasbin, "sync").returns(true);722      sandbox.stub(fse, "existsSync").returns(true);723      sandbox724        .stub(child_process, "spawnSync")725        .returns({ error: { code: "ENOENT" } });726      expect(727        plugin.hooks["before:package:createDeploymentArtifacts"]()728      ).to.eventually.be.rejected.and.notify(() => {729        sandbox.restore();730      });731    });732    it("skips packaging if disabled", () => {733      var plugin = new Plugin(734        {735          config: { servicePath: "/tmp" },736          service: {737            provider: { runtime: "python2.7" },738            custom: { wsgi: { app: "api.app", packRequirements: false } }739          },740          classes: { Error: Error },741          cli: { log: () => {} }742        },743        {}744      );745      var sandbox = sinon.createSandbox();746      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);747      var copyStub = sandbox.stub(fse, "copyAsync");748      var writeStub = sandbox.stub(fse, "writeFileAsync");749      var existsStub = sandbox.stub(fse, "existsSync").returns(true);750      var procStub = sandbox751        .stub(child_process, "spawnSync")752        .returns({ status: 0 });753      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {754        expect(hasbinStub.calledWith("python2.7")).to.be.true;755        expect(copyStub.called).to.be.true;756        expect(writeStub.called).to.be.true;757        expect(existsStub.called).to.be.false;758        expect(procStub.called).to.be.false;759        expect(plugin.serverless.service.package.include).not.to.have.members([760          ".requirements/**"761        ]);762        sandbox.restore();763      });764    });765    it("skips requirements cleanup if disabled", () => {766      var plugin = new Plugin(767        {768          config: { servicePath: "/tmp" },769          service: {770            provider: { runtime: "python2.7" },771            custom: { wsgi: { app: "api.app", packRequirements: false } }772          },773          classes: { Error: Error },774          cli: { log: () => {} }775        },776        {}777      );778      var sandbox = sinon.createSandbox();779      var removeStub = sandbox.stub(fse, "removeAsync");780      plugin.hooks["after:package:createDeploymentArtifacts"]().then(() => {781        expect(removeStub.calledWith("/tmp/wsgi_handler.py")).to.be.true;782        expect(removeStub.calledWith("/tmp/serverless_wsgi.py")).to.be.true;783        expect(removeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;784        expect(removeStub.calledWith("/tmp/.requirements")).to.be.false;785        sandbox.restore();786      });787    });788    it("skips packaging if serverless-python-requirements is present", () => {789      var plugin = new Plugin(790        {791          config: { servicePath: "/tmp" },792          service: {793            provider: { runtime: "python2.7" },794            custom: { wsgi: { app: "api.app" } },795            plugins: ["serverless-wsgi", "serverless-python-requirements"]796          },797          classes: { Error: Error },798          cli: { log: () => {} }799        },800        {}801      );802      var sandbox = sinon.createSandbox();803      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);804      var copyStub = sandbox.stub(fse, "copyAsync");805      var writeStub = sandbox.stub(fse, "writeFileAsync");806      var existsStub = sandbox.stub(fse, "existsSync").returns(true);807      var procStub = sandbox808        .stub(child_process, "spawnSync")809        .returns({ status: 0 });810      plugin.hooks["before:package:createDeploymentArtifacts"]().then(() => {811        expect(hasbinStub.calledWith("python2.7")).to.be.true;812        expect(copyStub.called).to.be.true;813        expect(writeStub.called).to.be.true;814        expect(existsStub.called).to.be.false;815        expect(procStub.called).to.be.false;816        expect(plugin.serverless.service.package.include).not.to.have.members([817          ".requirements/**"818        ]);819        sandbox.restore();820      });821    });822  });823  describe("function deployment", () => {824    it("skips packaging for non-wsgi function", () => {825      var functions = {826        app: {}827      };828      var plugin = new Plugin(829        {830          config: { servicePath: "/tmp" },831          service: {832            provider: { runtime: "python2.7" },833            custom: { wsgi: { app: "api.app" } },834            functions: functions835          },836          classes: { Error: Error },837          cli: { log: () => {} }838        },839        { functionObj: functions.app }840      );841      var sandbox = sinon.createSandbox();842      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);843      var copyStub = sandbox.stub(fse, "copyAsync");844      var writeStub = sandbox.stub(fse, "writeFileAsync");845      var procStub = sandbox846        .stub(child_process, "spawnSync")847        .returns({ status: 0 });848      plugin.hooks["before:deploy:function:packageFunction"]().then(() => {849        expect(hasbinStub.calledWith("python2.7")).to.be.true;850        expect(copyStub.called).to.be.false;851        expect(writeStub.called).to.be.false;852        expect(procStub.called).to.be.true;853        sandbox.restore();854      });855    });856    it("packages wsgi handler", () => {857      var functions = {858        app: { handler: "wsgi_handler.handler" }859      };860      var plugin = new Plugin(861        {862          config: { servicePath: "/tmp" },863          service: {864            provider: { runtime: "python2.7" },865            custom: { wsgi: { app: "api.app" } },866            functions: functions867          },868          classes: { Error: Error },869          cli: { log: () => {} }870        },871        { functionObj: functions.app }872      );873      var sandbox = sinon.createSandbox();874      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);875      var copyStub = sandbox.stub(fse, "copyAsync");876      var writeStub = sandbox.stub(fse, "writeFileAsync");877      sandbox.stub(fse, "readdirSync").returns([]);878      sandbox.stub(fse, "existsSync").returns(true);879      var procStub = sandbox880        .stub(child_process, "spawnSync")881        .returns({ status: 0 });882      plugin.hooks["before:deploy:function:packageFunction"]().then(() => {883        expect(hasbinStub.calledWith("python2.7")).to.be.true;884        expect(885          copyStub.calledWith(886            path.resolve(__dirname, "wsgi_handler.py"),887            "/tmp/wsgi_handler.py"888          )889        ).to.be.true;890        expect(891          copyStub.calledWith(892            path.resolve(__dirname, "serverless_wsgi.py"),893            "/tmp/serverless_wsgi.py"894          )895        ).to.be.true;896        expect(writeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;897        expect(JSON.parse(writeStub.lastCall.args[1])).to.deep.equal({898          app: "api.app"899        });900        expect(901          procStub.calledWith("python2.7", [902            path.resolve(__dirname, "requirements.py"),903            path.resolve(__dirname, "requirements.txt"),904            "/tmp/requirements.txt",905            "/tmp/.requirements"906          ])907        ).to.be.true;908        sandbox.restore();909      });910    });911    it("cleans up after deployment", () => {912      var functions = {913        app: { handler: "wsgi_handler.handler" }914      };915      var plugin = new Plugin(916        {917          config: { servicePath: "/tmp" },918          service: {919            provider: { runtime: "python2.7" },920            custom: { wsgi: { app: "api.app" } },921            functions: functions922          },923          classes: { Error: Error },924          cli: { log: () => {} }925        },926        { functionObj: functions.app }927      );928      var sandbox = sinon.createSandbox();929      var removeStub = sandbox.stub(fse, "removeAsync");930      var existsStub = sandbox.stub(fse, "existsSync").returns(true);931      existsStub.withArgs("werkzeug").returns(false);932      sandbox.stub(fse, "readdirSync").returns(["flask", "werkzeug"]);933      var unlinkStub = sandbox.stub(fse, "unlinkSync");934      plugin.hooks["after:deploy:function:packageFunction"]().then(() => {935        expect(existsStub.calledWith("/tmp/.requirements")).to.be.true;936        expect(unlinkStub.calledWith("flask")).to.be.true;937        expect(unlinkStub.calledWith("werkzeug")).to.be.false;938        expect(removeStub.calledWith("/tmp/wsgi_handler.py")).to.be.true;939        expect(removeStub.calledWith("/tmp/serverless_wsgi.py")).to.be.true;940        expect(removeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;941        expect(removeStub.calledWith("/tmp/.requirements")).to.be.false;942        sandbox.restore();943      });944    });945  });946  describe("serve", () => {947    it("fails for non-wsgi app", () => {948      var plugin = new Plugin({949        config: { servicePath: "/tmp" },950        service: { provider: { runtime: "python2.7" } },951        classes: { Error: Error },952        cli: { log: () => {} }953      });954      return expect(plugin.hooks["wsgi:serve:serve"]()).to.be.rejected;955    });956    it("executes python wrapper", () => {957      var plugin = new Plugin(958        {959          config: { servicePath: "/tmp" },960          service: {961            provider: { runtime: "python2.7" },962            custom: { wsgi: { app: "api.app" } }963          },964          classes: { Error: Error },965          cli: { log: () => {} }966        },967        {}968      );969      var sandbox = sinon.createSandbox();970      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);971      var procStub = sandbox.stub(child_process, "spawnSync").returns({});972      plugin.hooks["wsgi:serve:serve"]().then(() => {973        expect(hasbinStub.calledWith("python2.7")).to.be.true;974        expect(975          procStub.calledWith(976            "python2.7",977            [978              path.resolve(__dirname, "serve.py"),979              "/tmp",980              "api.app",981              5000,982              "localhost"983            ],984            { stdio: "inherit" }985          )986        ).to.be.true;987        sandbox.restore();988      });989    });990    it("handles process errors", () => {991      var plugin = new Plugin(992        {993          config: { servicePath: "/tmp" },994          service: {995            provider: { runtime: "python2.7" },996            custom: { wsgi: { app: "api.app" } }997          },998          classes: { Error: Error },999          cli: { log: () => {} }1000        },1001        {}1002      );1003      var sandbox = sinon.createSandbox();1004      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);1005      var procStub = sandbox1006        .stub(child_process, "spawnSync")1007        .returns({ error: "Something failed" });1008      expect(1009        plugin.hooks["wsgi:serve:serve"]()1010      ).to.eventually.be.rejected.and.notify(() => {1011        expect(hasbinStub.calledWith("python2.7")).to.be.true;1012        expect(1013          procStub.calledWith(1014            "python2.7",1015            [1016              path.resolve(__dirname, "serve.py"),1017              "/tmp",1018              "api.app",1019              5000,1020              "localhost"1021            ],1022            { stdio: "inherit" }1023          )1024        ).to.be.true;1025        sandbox.restore();1026      });1027    });1028    it("handles missing Python binary error", () => {1029      var plugin = new Plugin(1030        {1031          config: { servicePath: "/tmp" },1032          service: {1033            provider: { runtime: "python2.7" },1034            custom: { wsgi: { app: "api.app" } }1035          },1036          classes: { Error: Error },1037          cli: { log: () => {} }1038        },1039        {}1040      );1041      var sandbox = sinon.createSandbox();1042      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);1043      var procStub = sandbox1044        .stub(child_process, "spawnSync")1045        .returns({ error: { code: "ENOENT" } });1046      expect(1047        plugin.hooks["wsgi:serve:serve"]()1048      ).to.eventually.be.rejected.and.notify(() => {1049        expect(hasbinStub.calledWith("python2.7")).to.be.true;1050        expect(1051          procStub.calledWith(1052            "python2.7",1053            [1054              path.resolve(__dirname, "serve.py"),1055              "/tmp",1056              "api.app",1057              5000,1058              "localhost"1059            ],1060            { stdio: "inherit" }1061          )1062        ).to.be.true;1063        sandbox.restore();1064      });1065    });1066    it("allows changing port", () => {1067      var plugin = new Plugin(1068        {1069          config: { servicePath: "/tmp" },1070          service: {1071            provider: { runtime: "python2.7" },1072            custom: { wsgi: { app: "api.app" } }1073          },1074          classes: { Error: Error },1075          cli: { log: () => {} }1076        },1077        { port: 8000 }1078      );1079      var sandbox = sinon.createSandbox();1080      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);1081      var procStub = sandbox.stub(child_process, "spawnSync").returns({});1082      plugin.hooks["wsgi:serve:serve"]().then(() => {1083        expect(hasbinStub.calledWith("python2.7")).to.be.true;1084        expect(1085          procStub.calledWith(1086            "python2.7",1087            [1088              path.resolve(__dirname, "serve.py"),1089              "/tmp",1090              "api.app",1091              8000,1092              "localhost"1093            ],1094            { stdio: "inherit" }1095          )1096        ).to.be.true;1097        sandbox.restore();1098      });1099    });1100    it("allows changing host", () => {1101      var plugin = new Plugin(1102        {1103          config: { servicePath: "/tmp" },1104          service: {1105            provider: { runtime: "python2.7" },1106            custom: { wsgi: { app: "api.app" } }1107          },1108          classes: { Error: Error },1109          cli: { log: () => {} }1110        },1111        { host: "0.0.0.0" }1112      );1113      var sandbox = sinon.createSandbox();1114      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);1115      var procStub = sandbox.stub(child_process, "spawnSync").returns({});1116      plugin.hooks["wsgi:serve:serve"]().then(() => {1117        expect(hasbinStub.calledWith("python2.7")).to.be.true;1118        expect(1119          procStub.calledWith(1120            "python2.7",1121            [1122              path.resolve(__dirname, "serve.py"),1123              "/tmp",1124              "api.app",1125              5000,1126              "0.0.0.0"1127            ],1128            { stdio: "inherit" }1129          )1130        ).to.be.true;1131        sandbox.restore();1132      });1133    });1134    it("allows disabling threading", () => {1135      var plugin = new Plugin(1136        {1137          config: { servicePath: "/tmp" },1138          service: {1139            provider: { runtime: "python2.7" },1140            custom: { wsgi: { app: "api.app" } }1141          },1142          classes: { Error: Error },1143          cli: { log: () => {} }1144        },1145        { "disable-threading": true }1146      );1147      var sandbox = sinon.createSandbox();1148      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);1149      var procStub = sandbox.stub(child_process, "spawnSync").returns({});1150      plugin.hooks["wsgi:serve:serve"]().then(() => {1151        expect(hasbinStub.calledWith("python2.7")).to.be.true;1152        expect(1153          procStub.calledWith(1154            "python2.7",1155            [1156              path.resolve(__dirname, "serve.py"),1157              "/tmp",1158              "api.app",1159              5000,1160              "localhost",1161              "--disable-threading"1162            ],1163            { stdio: "inherit" }1164          )1165        ).to.be.true;1166        sandbox.restore();1167      });1168    });1169    it("allows multiple processes", () => {1170      var plugin = new Plugin(1171        {1172          config: { servicePath: "/tmp" },1173          service: {1174            provider: { runtime: "python2.7" },1175            custom: { wsgi: { app: "api.app" } }1176          },1177          classes: { Error: Error },1178          cli: { log: () => {} }1179        },1180        { "num-processes": 10 }1181      );1182      var sandbox = sinon.createSandbox();1183      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);1184      var procStub = sandbox.stub(child_process, "spawnSync").returns({});1185      plugin.hooks["wsgi:serve:serve"]().then(() => {1186        expect(hasbinStub.calledWith("python2.7")).to.be.true;1187        expect(1188          procStub.calledWith(1189            "python2.7",1190            [1191              path.resolve(__dirname, "serve.py"),1192              "/tmp",1193              "api.app",1194              5000,1195              "localhost",1196              "--num-processes",1197              101198            ],1199            { stdio: "inherit" }1200          )1201        ).to.be.true;1202        sandbox.restore();1203      });1204    });1205    it("allows serving over https", () => {1206      var plugin = new Plugin(1207        {1208          config: { servicePath: "/tmp" },1209          service: {1210            provider: { runtime: "python2.7" },1211            custom: { wsgi: { app: "api.app" } }1212          },1213          classes: { Error: Error },1214          cli: { log: () => {} }1215        },1216        { ssl: true }1217      );1218      var sandbox = sinon.createSandbox();1219      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);1220      var procStub = sandbox.stub(child_process, "spawnSync").returns({});1221      plugin.hooks["wsgi:serve:serve"]().then(() => {1222        expect(hasbinStub.calledWith("python2.7")).to.be.true;1223        expect(1224          procStub.calledWith(1225            "python2.7",1226            [1227              path.resolve(__dirname, "serve.py"),1228              "/tmp",1229              "api.app",1230              5000,1231              "localhost",1232              "--ssl"1233            ],1234            { stdio: "inherit" }1235          )1236        ).to.be.true;1237        sandbox.restore();1238      });1239    });1240    it("loads environment variables", () => {1241      var plugin = new Plugin(1242        {1243          config: { servicePath: "/tmp" },1244          service: {1245            provider: {1246              runtime: "python2.7",1247              environment: {1248                SOME_ENV_VAR: 42,1249                ANOTHER_ONE: { Ref: "AWS::StackId" }1250              }1251            },1252            functions: {1253              func1: {1254                handler: "wsgi_handler.handler",1255                environment: { SECOND_VAR: 33 }1256              },1257              func2: { handler: "x.x", environment: { THIRD_VAR: 66 } },1258              func3: { handler: "wsgi_handler.handler" }1259            },1260            custom: { wsgi: { app: "api.app" } }1261          },1262          classes: { Error: Error },1263          cli: { log: () => {} }1264        },1265        { port: 8000 }1266      );1267      var sandbox = sinon.createSandbox();1268      sandbox.stub(hasbin, "sync").returns(true);1269      sandbox.stub(child_process, "spawnSync").returns({});1270      sandbox.stub(process, "env").value({});1271      plugin.hooks["wsgi:serve:serve"]().then(() => {1272        expect(process.env.SOME_ENV_VAR).to.equal(42);1273        expect(process.env.SECOND_VAR).to.equal(33);1274        expect(process.env.THIRD_VAR).to.be.undefined;1275        expect(process.env.ANOTHER_ONE).to.be.undefined;1276        sandbox.restore();1277      });1278    });1279    it("loads wsgi app from individually packed module", () => {1280      var plugin = new Plugin(1281        {1282          config: { servicePath: "/tmp" },1283          service: {1284            provider: { runtime: "python2.7" },1285            package: { individually: true },1286            custom: { wsgi: { app: "site/api.app" } },1287            functions: {1288              api: { handler: "wsgi.handler", module: "site" }1289            }1290          },1291          classes: { Error: Error },1292          cli: { log: () => {} }1293        },1294        {}1295      );1296      var sandbox = sinon.createSandbox();1297      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);1298      var procStub = sandbox.stub(child_process, "spawnSync").returns({});1299      plugin.hooks["wsgi:serve:serve"]().then(() => {1300        expect(hasbinStub.calledWith("python2.7")).to.be.true;1301        expect(1302          procStub.calledWith(1303            "python2.7",1304            [1305              path.resolve(__dirname, "serve.py"),1306              "/tmp/site",1307              "api.app",1308              5000,1309              "localhost"1310            ],1311            { stdio: "inherit" }1312          )1313        ).to.be.true;1314        sandbox.restore();1315      });1316    });1317  });1318  describe("install", () => {1319    it("installs handler and requirements", () => {1320      var plugin = new Plugin(1321        {1322          config: { servicePath: "/tmp" },1323          service: {1324            provider: { runtime: "python2.7" },1325            custom: { wsgi: { app: "api.app" } }1326          },1327          classes: { Error: Error },1328          cli: { log: () => {} }1329        },1330        {}1331      );1332      var sandbox = sinon.createSandbox();1333      var hasbinStub = sandbox.stub(hasbin, "sync").returns(true);1334      var copyStub = sandbox.stub(fse, "copyAsync");1335      var writeStub = sandbox.stub(fse, "writeFileAsync");1336      sandbox.stub(fse, "readdirSync").returns([]);1337      sandbox.stub(fse, "existsSync").returns(true);1338      var procStub = sandbox1339        .stub(child_process, "spawnSync")1340        .returns({ status: 0 });1341      plugin.hooks["wsgi:install:install"]().then(() => {1342        expect(hasbinStub.calledWith("python2.7")).to.be.true;1343        expect(1344          copyStub.calledWith(1345            path.resolve(__dirname, "wsgi_handler.py"),1346            "/tmp/wsgi_handler.py"1347          )1348        ).to.be.true;1349        expect(1350          copyStub.calledWith(1351            path.resolve(__dirname, "serverless_wsgi.py"),1352            "/tmp/serverless_wsgi.py"1353          )1354        ).to.be.true;1355        expect(writeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;1356        expect(JSON.parse(writeStub.lastCall.args[1])).to.deep.equal({1357          app: "api.app"1358        });1359        expect(1360          procStub.calledWith("python2.7", [1361            path.resolve(__dirname, "requirements.py"),1362            path.resolve(__dirname, "requirements.txt"),1363            "/tmp/requirements.txt",1364            "/tmp/.requirements"1365          ])1366        ).to.be.true;1367        sandbox.restore();1368      });1369    });1370  });1371  describe("clean", () => {1372    it("cleans up everything", () => {1373      var plugin = new Plugin(1374        {1375          config: { servicePath: "/tmp" },1376          service: {1377            provider: { runtime: "python2.7" },1378            custom: { wsgi: { app: "api.app" } }1379          },1380          classes: { Error: Error },1381          cli: { log: () => {} }1382        },1383        {}1384      );1385      var sandbox = sinon.createSandbox();1386      var removeStub = sandbox.stub(fse, "removeAsync");1387      var existsStub = sandbox.stub(fse, "existsSync").returns(true);1388      sandbox.stub(fse, "readdirSync").returns(["flask"]);1389      var unlinkStub = sandbox.stub(fse, "unlinkSync");1390      plugin.hooks["wsgi:clean:clean"]().then(() => {1391        expect(existsStub.calledWith("/tmp/.requirements")).to.be.true;1392        expect(unlinkStub.calledWith("flask")).to.be.true;1393        expect(removeStub.calledWith("/tmp/wsgi_handler.py")).to.be.true;1394        expect(removeStub.calledWith("/tmp/serverless_wsgi.py")).to.be.true;1395        expect(removeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;1396        expect(removeStub.calledWith("/tmp/.requirements")).to.be.true;1397        sandbox.restore();1398      });1399    });1400    it("skips cleaning requirements if packaging not enabled", () => {1401      var functions = {1402        app: { handler: "wsgi_handler.handler" }1403      };1404      var plugin = new Plugin(1405        {1406          config: { servicePath: "/tmp" },1407          service: {1408            provider: { runtime: "python2.7" },1409            custom: { wsgi: { app: "api.app", packRequirements: false } },1410            functions: functions1411          },1412          classes: { Error: Error },1413          cli: { log: () => {} }1414        },1415        { functionObj: functions.app }1416      );1417      var sandbox = sinon.createSandbox();1418      var removeStub = sandbox.stub(fse, "removeAsync");1419      var existsStub = sandbox.stub(fse, "existsSync").returns(true);1420      plugin.hooks["wsgi:clean:clean"]().then(() => {1421        expect(existsStub.calledWith("/tmp/.requirements")).to.be.false;1422        expect(removeStub.calledWith("/tmp/wsgi_handler.py")).to.be.true;1423        expect(removeStub.calledWith("/tmp/serverless_wsgi.py")).to.be.true;1424        expect(removeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;1425        expect(removeStub.calledWith("/tmp/.requirements")).to.be.false;1426        sandbox.restore();1427      });1428    });1429  });1430  describe("exec", () => {1431    it("fails when invoked without command or file", () => {1432      var plugin = new Plugin(1433        {1434          config: { servicePath: "/tmp" },1435          service: {1436            provider: { runtime: "python2.7" },1437            custom: { wsgi: { app: "api.app" } }1438          },1439          classes: { Error: Error },1440          cli: { log: () => {} }1441        },1442        {}1443      );1444      expect(plugin.hooks["wsgi:exec:exec"]()).to.be.rejectedWith(1445        "Please provide either a command (-c) or a file (-f)"1446      );1447    });1448    it("calls handler to execute code remotely from argument", () => {1449      var plugin = new Plugin(1450        {1451          config: { servicePath: "/tmp" },1452          service: {1453            provider: { runtime: "python2.7" },1454            custom: { wsgi: { app: "api.app" } },1455            functions: { app: { handler: "wsgi_handler.handler" } }1456          },1457          classes: { Error: Error },1458          cli: { log: () => {} },1459          pluginManager: {1460            cliOptions: {},1461            run: command =>1462              new BbPromise(resolve => {1463                expect(command).to.deep.equal(["invoke"]);1464                console.log('[0, "5"]'); // eslint-disable-line no-console1465                resolve();1466              })1467          }1468        },1469        { command: "print(1+4)" }1470      );1471      var sandbox = sinon.createSandbox();1472      let consoleSpy = sandbox.spy(console, "log");1473      plugin.hooks["wsgi:exec:exec"]().then(() => {1474        expect(plugin.serverless.pluginManager.cliOptions.c).to.be.undefined;1475        expect(plugin.serverless.pluginManager.cliOptions.context).to.be1476          .undefined;1477        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");1478        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(1479          "app"1480        );1481        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(1482          '{"_serverless-wsgi":{"command":"exec","data":"print(1+4)"}}'1483        );1484        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(1485          '{"_serverless-wsgi":{"command":"exec","data":"print(1+4)"}}'1486        );1487        expect(consoleSpy.calledWith("5")).to.be.true;1488        sandbox.restore();1489      });1490    });1491    it("calls handler to execute code remotely from file", () => {1492      var plugin = new Plugin(1493        {1494          config: { servicePath: "/tmp" },1495          service: {1496            provider: { runtime: "python2.7" },1497            custom: { wsgi: { app: "api.app" } },1498            functions: { app: { handler: "wsgi_handler.handler" } }1499          },1500          classes: { Error: Error },1501          cli: { log: () => {} },1502          pluginManager: {1503            cliOptions: {},1504            run: command =>1505              new BbPromise(resolve => {1506                expect(command).to.deep.equal(["invoke"]);1507                console.log('[0, {"response": "5"}]'); // eslint-disable-line no-console1508                resolve();1509              })1510          }1511        },1512        { file: "script.py" }1513      );1514      var sandbox = sinon.createSandbox();1515      let consoleSpy = sandbox.spy(console, "log");1516      sandbox.stub(fse, "readFileSync").returns("print(1+4)");1517      plugin.hooks["wsgi:exec:exec"]().then(() => {1518        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");1519        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(1520          "app"1521        );1522        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(1523          '{"_serverless-wsgi":{"command":"exec","data":"print(1+4)"}}'1524        );1525        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(1526          '{"_serverless-wsgi":{"command":"exec","data":"print(1+4)"}}'1527        );1528        expect(consoleSpy.calledWith({ response: "5" })).to.be.true;1529        sandbox.restore();1530      });1531    });1532    it("handles unsuccessful exit from command", () => {1533      var plugin = new Plugin(1534        {1535          config: { servicePath: "/tmp" },1536          service: {1537            provider: { runtime: "python2.7" },1538            custom: { wsgi: { app: "api.app" } },1539            functions: { app: { handler: "wsgi_handler.handler" } }1540          },1541          classes: { Error: Error },1542          cli: { log: () => {} },1543          pluginManager: {1544            cliOptions: {},1545            run: command =>1546              new BbPromise(resolve => {1547                expect(command).to.deep.equal(["invoke"]);1548                console.log('[1, "Error"]'); // eslint-disable-line no-console1549                resolve();1550              })1551          }1552        },1553        { command: "print(1+4)" }1554      );1555      expect(plugin.hooks["wsgi:exec:exec"]()).to.be.rejectedWith("Error");1556    });1557  });1558  describe("exec local", () => {1559    it("fails when invoked without command or file", () => {1560      var plugin = new Plugin(1561        {1562          config: { servicePath: "/tmp" },1563          service: {1564            provider: { runtime: "python2.7" },1565            custom: { wsgi: { app: "api.app" } }1566          },1567          classes: { Error: Error },1568          cli: { log: () => {} }1569        },1570        {}1571      );1572      expect(plugin.hooks["wsgi:exec:local:exec"]()).to.be.rejectedWith(1573        "Please provide either a command (-c) or a file (-f)"1574      );1575    });1576    it("calls handler to execute code locally from argument", () => {1577      var plugin = new Plugin(1578        {1579          config: { servicePath: "/tmp" },1580          service: {1581            provider: { runtime: "python2.7" },1582            custom: { wsgi: { app: "api.app" } },1583            functions: { app: { handler: "wsgi_handler.handler" } }1584          },1585          classes: { Error: Error },1586          cli: { log: () => {} },1587          pluginManager: {1588            cliOptions: {},1589            run: command =>1590              new BbPromise(resolve => {1591                expect(command).to.deep.equal(["invoke", "local"]);1592                console.log('[0, "5"]'); // eslint-disable-line no-console1593                resolve();1594              })1595          }1596        },1597        { command: "print(1+4)" }1598      );1599      var sandbox = sinon.createSandbox();1600      let consoleSpy = sandbox.spy(console, "log");1601      plugin.hooks["wsgi:exec:local:exec"]().then(() => {1602        expect(plugin.serverless.pluginManager.cliOptions.c).to.be.undefined;1603        expect(plugin.serverless.pluginManager.cliOptions.context).to.be1604          .undefined;1605        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");1606        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(1607          "app"1608        );1609        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(1610          '{"_serverless-wsgi":{"command":"exec","data":"print(1+4)"}}'1611        );1612        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(1613          '{"_serverless-wsgi":{"command":"exec","data":"print(1+4)"}}'1614        );1615        expect(consoleSpy.calledWith("5")).to.be.true;1616        sandbox.restore();1617      });1618    });1619    it("calls handler to execute code locally from file", () => {1620      var plugin = new Plugin(1621        {1622          config: { servicePath: "/tmp" },1623          service: {1624            provider: { runtime: "python2.7" },1625            custom: { wsgi: { app: "api.app" } },1626            functions: { app: { handler: "wsgi_handler.handler" } }1627          },1628          classes: { Error: Error },1629          cli: { log: () => {} },1630          pluginManager: {1631            cliOptions: {},1632            run: command =>1633              new BbPromise(resolve => {1634                expect(command).to.deep.equal(["invoke", "local"]);1635                console.log('[0, {"response": "5"}]'); // eslint-disable-line no-console1636                resolve();1637              })1638          }1639        },1640        { file: "script.py" }1641      );1642      var sandbox = sinon.createSandbox();1643      let consoleSpy = sandbox.spy(console, "log");1644      sandbox.stub(fse, "readFileSync").returns("print(1+4)");1645      plugin.hooks["wsgi:exec:local:exec"]().then(() => {1646        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");1647        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(1648          "app"1649        );1650        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(1651          '{"_serverless-wsgi":{"command":"exec","data":"print(1+4)"}}'1652        );1653        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(1654          '{"_serverless-wsgi":{"command":"exec","data":"print(1+4)"}}'1655        );1656        expect(consoleSpy.calledWith({ response: "5" })).to.be.true;1657        sandbox.restore();1658      });1659    });1660  });1661  describe("command", () => {1662    it("fails when no wsgi handler is set", () => {1663      var plugin = new Plugin(1664        {1665          config: { servicePath: "/tmp" },1666          service: {1667            provider: { runtime: "python2.7" },1668            custom: { wsgi: { app: "api.app" } },1669            functions: { app: { handler: "other.handler" } }1670          },1671          classes: { Error: Error },1672          cli: { log: () => {} }1673        },1674        { command: "pwd" }1675      );1676      expect(plugin.hooks["wsgi:command:command"]()).to.be.rejectedWith(1677        "No functions were found with handler: wsgi_handler.handler"1678      );1679    });1680    it("fails when invoked without command or file", () => {1681      var plugin = new Plugin(1682        {1683          config: { servicePath: "/tmp" },1684          service: {1685            provider: { runtime: "python2.7" },1686            custom: { wsgi: { app: "api.app" } }1687          },1688          classes: { Error: Error },1689          cli: { log: () => {} }1690        },1691        {}1692      );1693      expect(plugin.hooks["wsgi:command:command"]()).to.be.rejectedWith(1694        "Please provide either a command (-c) or a file (-f)"1695      );1696    });1697    it("calls handler to execute commands remotely from argument", () => {1698      var plugin = new Plugin(1699        {1700          config: { servicePath: "/tmp" },1701          service: {1702            provider: { runtime: "python2.7" },1703            custom: { wsgi: { app: "api.app" } },1704            functions: { app: { handler: "wsgi_handler.handler" } }1705          },1706          classes: { Error: Error },1707          cli: { log: () => {} },1708          pluginManager: {1709            cliOptions: {},1710            run: command =>1711              new BbPromise(resolve => {1712                expect(command).to.deep.equal(["invoke"]);1713                console.log("non-json output"); // eslint-disable-line no-console1714                resolve();1715              })1716          }1717        },1718        { command: "pwd" }1719      );1720      var sandbox = sinon.createSandbox();1721      let consoleSpy = sandbox.spy(console, "log");1722      plugin.hooks["wsgi:command:command"]().then(() => {1723        expect(plugin.serverless.pluginManager.cliOptions.c).to.be.undefined;1724        expect(plugin.serverless.pluginManager.cliOptions.context).to.be1725          .undefined;1726        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");1727        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(1728          "app"1729        );1730        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(1731          '{"_serverless-wsgi":{"command":"command","data":"pwd"}}'1732        );1733        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(1734          '{"_serverless-wsgi":{"command":"command","data":"pwd"}}'1735        );1736        expect(consoleSpy.calledWith("non-json output")).to.be.true;1737        sandbox.restore();1738      });1739    });1740    it("calls handler to execute commands remotely from file", () => {1741      var plugin = new Plugin(1742        {1743          config: { servicePath: "/tmp" },1744          service: {1745            provider: { runtime: "python2.7" },1746            custom: { wsgi: { app: "api.app" } },1747            functions: { app: { handler: "wsgi_handler.handler" } }1748          },1749          classes: { Error: Error },1750          cli: { log: () => {} },1751          pluginManager: {1752            cliOptions: {},1753            run: command =>1754              new BbPromise(resolve => {1755                expect(command).to.deep.equal(["invoke"]);1756                console.log('[0, "/var/task"]'); // eslint-disable-line no-console1757                resolve();1758              })1759          }1760        },1761        { file: "script.sh" }1762      );1763      var sandbox = sinon.createSandbox();1764      let consoleSpy = sandbox.spy(console, "log");1765      sandbox.stub(fse, "readFileSync").returns("pwd");1766      plugin.hooks["wsgi:command:command"]().then(() => {1767        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");1768        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(1769          "app"1770        );1771        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(1772          '{"_serverless-wsgi":{"command":"command","data":"pwd"}}'1773        );1774        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(1775          '{"_serverless-wsgi":{"command":"command","data":"pwd"}}'1776        );1777        expect(consoleSpy.calledWith("/var/task")).to.be.true;1778        sandbox.restore();1779      });1780    });1781  });1782  describe("command local", () => {1783    it("fails when no wsgi handler is set", () => {1784      var plugin = new Plugin(1785        {1786          config: { servicePath: "/tmp" },1787          service: {1788            provider: { runtime: "python2.7" },1789            custom: { wsgi: { app: "api.app" } },1790            functions: { app: { handler: "other.handler" } }1791          },1792          classes: { Error: Error },1793          cli: { log: () => {} }1794        },1795        { command: "pwd" }1796      );1797      expect(plugin.hooks["wsgi:command:local:command"]()).to.be.rejectedWith(1798        "No functions were found with handler: wsgi_handler.handler"1799      );1800    });1801    it("fails when invoked without command or file", () => {1802      var plugin = new Plugin(1803        {1804          config: { servicePath: "/tmp" },1805          service: {1806            provider: { runtime: "python2.7" },1807            custom: { wsgi: { app: "api.app" } }1808          },1809          classes: { Error: Error },1810          cli: { log: () => {} }1811        },1812        {}1813      );1814      expect(plugin.hooks["wsgi:command:local:command"]()).to.be.rejectedWith(1815        "Please provide either a command (-c) or a file (-f)"1816      );1817    });1818    it("calls handler to execute commands remotely from argument", () => {1819      var plugin = new Plugin(1820        {1821          config: { servicePath: "/tmp" },1822          service: {1823            provider: { runtime: "python2.7" },1824            custom: { wsgi: { app: "api.app" } },1825            functions: { app: { handler: "wsgi_handler.handler" } }1826          },1827          classes: { Error: Error },1828          cli: { log: () => {} },1829          pluginManager: {1830            cliOptions: {},1831            run: command =>1832              new BbPromise(resolve => {1833                expect(command).to.deep.equal(["invoke", "local"]);1834                console.log("non-json output"); // eslint-disable-line no-console1835                resolve();1836              })1837          }1838        },1839        { command: "pwd" }1840      );1841      var sandbox = sinon.createSandbox();1842      let consoleSpy = sandbox.spy(console, "log");1843      plugin.hooks["wsgi:command:local:command"]().then(() => {1844        expect(plugin.serverless.pluginManager.cliOptions.c).to.be.undefined;1845        expect(plugin.serverless.pluginManager.cliOptions.context).to.be1846          .undefined;1847        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");1848        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(1849          "app"1850        );1851        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(1852          '{"_serverless-wsgi":{"command":"command","data":"pwd"}}'1853        );1854        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(1855          '{"_serverless-wsgi":{"command":"command","data":"pwd"}}'1856        );1857        expect(consoleSpy.calledWith("non-json output")).to.be.true;1858        sandbox.restore();1859      });1860    });1861    it("calls handler to execute commands remotely from file", () => {1862      var plugin = new Plugin(1863        {1864          config: { servicePath: "/tmp" },1865          service: {1866            provider: { runtime: "python2.7" },1867            custom: { wsgi: { app: "api.app" } },1868            functions: { app: { handler: "wsgi_handler.handler" } }1869          },1870          classes: { Error: Error },1871          cli: { log: () => {} },1872          pluginManager: {1873            cliOptions: {},1874            run: command =>1875              new BbPromise(resolve => {1876                expect(command).to.deep.equal(["invoke", "local"]);1877                console.log('[0, "/var/task"]'); // eslint-disable-line no-console1878                resolve();1879              })1880          }1881        },1882        { file: "script.sh" }1883      );1884      var sandbox = sinon.createSandbox();1885      let consoleSpy = sandbox.spy(console, "log");1886      sandbox.stub(fse, "readFileSync").returns("pwd");1887      plugin.hooks["wsgi:command:local:command"]().then(() => {1888        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");1889        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(1890          "app"1891        );1892        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(1893          '{"_serverless-wsgi":{"command":"command","data":"pwd"}}'1894        );1895        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(1896          '{"_serverless-wsgi":{"command":"command","data":"pwd"}}'1897        );1898        expect(consoleSpy.calledWith("/var/task")).to.be.true;1899        sandbox.restore();1900      });1901    });1902  });1903  describe("manage", () => {1904    it("calls handler to execute manage commands remotely from argument", () => {1905      var plugin = new Plugin(1906        {1907          config: { servicePath: "/tmp" },1908          service: {1909            provider: { runtime: "python2.7" },1910            custom: { wsgi: { app: "api.app" } },1911            functions: { app: { handler: "wsgi_handler.handler" } }1912          },1913          classes: { Error: Error },1914          cli: { log: () => {} },1915          pluginManager: {1916            cliOptions: {},1917            run: command =>1918              new BbPromise(resolve => {1919                expect(command).to.deep.equal(["invoke"]);1920                console.log('[0, "manage command output"]'); // eslint-disable-line no-console1921                resolve();1922              })1923          }1924        },1925        { command: "check" }1926      );1927      var sandbox = sinon.createSandbox();1928      let consoleSpy = sandbox.spy(console, "log");1929      plugin.hooks["wsgi:manage:manage"]().then(() => {1930        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");1931        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(1932          "app"1933        );1934        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(1935          '{"_serverless-wsgi":{"command":"manage","data":"check"}}'1936        );1937        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(1938          '{"_serverless-wsgi":{"command":"manage","data":"check"}}'1939        );1940        expect(consoleSpy.calledWith("manage command output")).to.be.true;1941        sandbox.restore();1942      });1943    });1944  });1945  describe("manage local", () => {1946    it("calls handler to execute manage commands locally from argument", () => {1947      var plugin = new Plugin(1948        {1949          config: { servicePath: "/tmp" },1950          service: {1951            provider: { runtime: "python2.7" },1952            custom: { wsgi: { app: "api.app" } },1953            functions: { app: { handler: "wsgi_handler.handler" } }1954          },1955          classes: { Error: Error },1956          cli: { log: () => {} },1957          pluginManager: {1958            cliOptions: {},1959            run: command =>1960              new BbPromise(resolve => {1961                expect(command).to.deep.equal(["invoke", "local"]);1962                console.log('[0, "manage command output"]'); // eslint-disable-line no-console1963                resolve();1964              })1965          }1966        },1967        { command: "check" }1968      );1969      var sandbox = sinon.createSandbox();1970      let consoleSpy = sandbox.spy(console, "log");1971      plugin.hooks["wsgi:manage:local:manage"]().then(() => {1972        expect(plugin.serverless.pluginManager.cliOptions.c).to.be.undefined;1973        expect(plugin.serverless.pluginManager.cliOptions.context).to.be1974          .undefined;1975        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");1976        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(1977          "app"1978        );1979        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(1980          '{"_serverless-wsgi":{"command":"manage","data":"check"}}'1981        );1982        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(1983          '{"_serverless-wsgi":{"command":"manage","data":"check"}}'1984        );1985        expect(consoleSpy.calledWith("manage command output")).to.be.true;1986        sandbox.restore();1987      });1988    });1989  });1990  describe("flask", () => {1991    it("calls handler to execute flask commands remotely from argument", () => {1992      var plugin = new Plugin(1993        {1994          config: { servicePath: "/tmp" },1995          service: {1996            provider: { runtime: "python2.7" },1997            custom: { wsgi: { app: "api.app" } },1998            functions: { app: { handler: "wsgi_handler.handler" } }1999          },2000          classes: { Error: Error },2001          cli: { log: () => {} },2002          pluginManager: {2003            cliOptions: {},2004            run: command =>2005              new BbPromise(resolve => {2006                expect(command).to.deep.equal(["invoke"]);2007                console.log('[0, "flask command output"]'); // eslint-disable-line no-console2008                resolve();2009              })2010          }2011        },2012        { command: "check" }2013      );2014      var sandbox = sinon.createSandbox();2015      let consoleSpy = sandbox.spy(console, "log");2016      plugin.hooks["wsgi:flask:flask"]().then(() => {2017        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");2018        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(2019          "app"2020        );2021        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(2022          '{"_serverless-wsgi":{"command":"flask","data":"check"}}'2023        );2024        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(2025          '{"_serverless-wsgi":{"command":"flask","data":"check"}}'2026        );2027        expect(consoleSpy.calledWith("flask command output")).to.be.true;2028        sandbox.restore();2029      });2030    });2031  });2032  describe("flask local", () => {2033    it("calls handler to execute flask commands locally from argument", () => {2034      var plugin = new Plugin(2035        {2036          config: { servicePath: "/tmp" },2037          service: {2038            provider: { runtime: "python2.7" },2039            custom: { wsgi: { app: "api.app" } },2040            functions: { app: { handler: "wsgi_handler.handler" } }2041          },2042          classes: { Error: Error },2043          cli: { log: () => {} },2044          pluginManager: {2045            cliOptions: {},2046            run: command =>2047              new BbPromise(resolve => {2048                expect(command).to.deep.equal(["invoke", "local"]);2049                console.log('[0, "flask command output"]'); // eslint-disable-line no-console2050                resolve();2051              })2052          }2053        },2054        { command: "check" }2055      );2056      var sandbox = sinon.createSandbox();2057      let consoleSpy = sandbox.spy(console, "log");2058      plugin.hooks["wsgi:flask:local:flask"]().then(() => {2059        expect(plugin.serverless.pluginManager.cliOptions.c).to.be.undefined;2060        expect(plugin.serverless.pluginManager.cliOptions.context).to.be2061          .undefined;2062        expect(plugin.serverless.pluginManager.cliOptions.f).to.equal("app");2063        expect(plugin.serverless.pluginManager.cliOptions.function).to.equal(2064          "app"2065        );2066        expect(plugin.serverless.pluginManager.cliOptions.d).to.equal(2067          '{"_serverless-wsgi":{"command":"flask","data":"check"}}'2068        );2069        expect(plugin.serverless.pluginManager.cliOptions.data).to.equal(2070          '{"_serverless-wsgi":{"command":"flask","data":"check"}}'2071        );2072        expect(consoleSpy.calledWith("flask command output")).to.be.true;2073        sandbox.restore();2074      });2075    });2076  });2077  describe("invoke local", () => {2078    it("installs handler before invocation", () => {2079      var functions = {2080        app: { handler: "wsgi.handler" },2081        other: { handler: "other.handler" }2082      };2083      var plugin = new Plugin(2084        {2085          config: { servicePath: "/tmp" },2086          service: {2087            provider: { runtime: "python2.7" },2088            custom: { wsgi: { app: "api.app" } },2089            functions: functions,2090            getFunction: name => functions[name]2091          },2092          classes: { Error: Error },2093          cli: { log: () => {} }2094        },2095        { function: "other" }2096      );2097      // Test invocation for non-WSGI function, should do nothing2098      expect(plugin.hooks["before:invoke:local:invoke"]()).to.be.fulfilled;2099      plugin.options.function = "app";2100      var sandbox = sinon.createSandbox();2101      var copyStub = sandbox.stub(fse, "copyAsync");2102      var writeStub = sandbox.stub(fse, "writeFileAsync");2103      plugin.hooks["before:invoke:local:invoke"]().then(() => {2104        expect(2105          copyStub.calledWith(2106            path.resolve(__dirname, "wsgi_handler.py"),2107            "/tmp/wsgi_handler.py"2108          )2109        ).to.be.true;2110        expect(2111          copyStub.calledWith(2112            path.resolve(__dirname, "serverless_wsgi.py"),2113            "/tmp/serverless_wsgi.py"2114          )2115        ).to.be.true;2116        expect(writeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;2117        expect(JSON.parse(writeStub.lastCall.args[1])).to.deep.equal({2118          app: "api.app"2119        });2120        sandbox.restore();2121      });2122    });2123    it("cleans up after invocation", () => {2124      var plugin = new Plugin(2125        {2126          config: { servicePath: "/tmp" },2127          service: {2128            provider: { runtime: "python2.7" },2129            custom: { wsgi: { app: "api.app" } },2130            functions: {2131              app: { handler: "wsgi_handler.handler" }2132            }2133          },2134          classes: { Error: Error },2135          cli: { log: () => {} }2136        },2137        { function: "app" }2138      );2139      var sandbox = sinon.createSandbox();2140      var removeStub = sandbox.stub(fse, "removeAsync");2141      plugin.hooks["after:invoke:local:invoke"]().then(() => {2142        expect(removeStub.calledWith("/tmp/wsgi_handler.py")).to.be.true;2143        expect(removeStub.calledWith("/tmp/serverless_wsgi.py")).to.be.true;2144        expect(removeStub.calledWith("/tmp/.serverless-wsgi")).to.be.true;2145        sandbox.restore();2146      });2147    });2148  });...blockchain.js
Source:blockchain.js  
...7const mockData = require('./fixtures/blockchain-mock')8describe('#Blockchain', () => {9  describe('#getBestBlockHash', () => {10    let sandbox11    beforeEach(() => (sandbox = sinon.createSandbox()))12    afterEach(() => sandbox.restore())13    it('should get best block hash', done => {14      const resolved = new Promise(resolve =>15        resolve({16          data:17            '0000000000000000005f1f550d3d8b142b684277016ebd00fa29c668606ae52d'18        })19      )20      sandbox.stub(axios, 'get').returns(resolved)21      bchjs.Blockchain.getBestBlockHash()22        .then(result => {23          const hash =24            '0000000000000000005f1f550d3d8b142b684277016ebd00fa29c668606ae52d'25          assert.strictEqual(hash, result)26        })27        .then(done, done)28    })29  })30  describe('#getBlock', () => {31    let sandbox32    beforeEach(() => (sandbox = sinon.createSandbox()))33    afterEach(() => sandbox.restore())34    const data = {35      hash: '00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09',36      confirmations: 526807,37      size: 216,38      height: 1000,39      version: 1,40      versionHex: '00000001',41      merkleroot:42        'fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33',43      tx: ['fe28050b93faea61fa88c4c630f0e1f0a1c24d0082dd0e10d369e13212128f33'],44      time: 1232346882,45      mediantime: 1232344831,46      nonce: 2595206198,47      bits: '1d00ffff',48      difficulty: 1,49      chainwork:50        '000000000000000000000000000000000000000000000000000003e903e903e9',51      previousblockhash:52        '0000000008e647742775a230787d66fdf92c46a48c896bfbc85cdc8acc67e87d',53      nextblockhash:54        '00000000a2887344f8db859e372e7e4bc26b23b9de340f725afbf2edb265b4c6'55    }56    it('should get block by hash', done => {57      const resolved = new Promise(resolve => resolve({ data: data }))58      sandbox.stub(axios, 'post').returns(resolved)59      const blockhash =60        '00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09'61      bchjs.Blockchain.getBlock(blockhash)62        .then(result => {63          assert.deepStrictEqual(data, result)64        })65        .then(done, done)66    })67    it('should throw error if blockhash is not provided', async () => {68      try {69        await bchjs.Blockchain.getBlock()70        assert2.fail('Unexpected result')71      } catch (err) {72        assert2.include(err.message, 'blockhash must be a string')73      }74    })75    it('should handle response error', async () => {76      try {77        const error = new Error()78        error.response = {79          data: 'Test Error'80        }81        sandbox.stub(axios, 'post').throws(error)82        const blockhash =83          '00000000c937983704a73af28acdec37b049d214adbda81d7e2a3dd146f6ed09'84        await bchjs.Blockchain.getBlock(blockhash)85        assert2.fail('Unexpected result')86      } catch (err) {87        assert2.include(err, 'Test Error')88      }89    })90  })91  describe('#getBlockchainInfo', () => {92    let sandbox93    beforeEach(() => (sandbox = sinon.createSandbox()))94    afterEach(() => sandbox.restore())95    const data = {96      chain: 'main',97      blocks: 527810,98      headers: 527810,99      bestblockhash:100        '000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0',101      difficulty: 576023394804.6666,102      mediantime: 1524878499,103      verificationprogress: 0.9999990106793685,104      chainwork:105        '00000000000000000000000000000000000000000096da5b040913fa09249b4e',106      pruned: false,107      softforks: [108        { id: 'bip34', version: 2, reject: [Object] },109        { id: 'bip66', version: 3, reject: [Object] },110        { id: 'bip65', version: 4, reject: [Object] }111      ],112      bip9_softforks: {113        csv: {114          status: 'active',115          startTime: 1462060800,116          timeout: 1493596800,117          since: 419328118        }119      }120    }121    it('should get blockchain info', done => {122      const resolved = new Promise(resolve => resolve({ data: data }))123      sandbox.stub(axios, 'get').returns(resolved)124      bchjs.Blockchain.getBlockchainInfo()125        .then(result => {126          assert.deepStrictEqual(data, result)127        })128        .then(done, done)129    })130  })131  describe('#getBlockCount', () => {132    let sandbox133    beforeEach(() => (sandbox = sinon.createSandbox()))134    afterEach(() => sandbox.restore())135    const data = 527810136    it('should get block count', done => {137      const resolved = new Promise(resolve => resolve({ data: data }))138      sandbox.stub(axios, 'get').returns(resolved)139      bchjs.Blockchain.getBlockCount()140        .then(result => {141          assert.deepStrictEqual(data, result)142        })143        .then(done, done)144    })145  })146  describe('#getBlockHash', () => {147    let sandbox148    beforeEach(() => (sandbox = sinon.createSandbox()))149    afterEach(() => sandbox.restore())150    const data =151      '000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0'152    it('should get block hash by height', done => {153      const resolved = new Promise(resolve => resolve({ data: data }))154      sandbox.stub(axios, 'get').returns(resolved)155      bchjs.Blockchain.getBlockHash(527810)156        .then(result => {157          assert.deepStrictEqual(data, result)158        })159        .then(done, done)160    })161  })162  describe('#getBlockHeader', () => {163    let sandbox164    beforeEach(() => (sandbox = sinon.createSandbox()))165    afterEach(() => sandbox.restore())166    const data = {167      hash: '000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0',168      confirmations: 1,169      height: 527810,170      version: 536870912,171      versionHex: '20000000',172      merkleroot:173        '9298432bbebe4638456aa19cb7ef91639da87668a285d88d0ecd6080424d223b',174      time: 1524881438,175      mediantime: 1524878499,176      nonce: 3326843941,177      bits: '1801e8a5',178      difficulty: 576023394804.6666,179      chainwork:180        '00000000000000000000000000000000000000000096da5b040913fa09249b4e',181      previousblockhash:182        '000000000000000000b33251708bc7a7b4540e61880d8c376e8e2db6a19a4789'183    }184    it('should get block header by hash', done => {185      const resolved = new Promise(resolve => resolve({ data: data }))186      sandbox.stub(axios, 'get').returns(resolved)187      bchjs.Blockchain.getBlockHeader(188        '000000000000000001d127592d091d4c45062504663c9acab27a1b16c028e3c0',189        true190      )191        .then(result => {192          assert.deepStrictEqual(data, result)193        })194        .then(done, done)195    })196  })197  describe('#getDifficulty', () => {198    let sandbox199    beforeEach(() => (sandbox = sinon.createSandbox()))200    afterEach(() => sandbox.restore())201    const data = '577528469277.1339'202    it('should get difficulty', done => {203      const resolved = new Promise(resolve => resolve({ data: data }))204      sandbox.stub(axios, 'get').returns(resolved)205      bchjs.Blockchain.getDifficulty()206        .then(result => {207          assert.deepStrictEqual(data, result)208        })209        .then(done, done)210    })211  })212  describe('#getMempoolAncestors', () => {213    let sandbox214    beforeEach(() => (sandbox = sinon.createSandbox()))215    afterEach(() => sandbox.restore())216    const data = 'Transaction not in mempool'217    it('should get mempool ancestors', done => {218      const resolved = new Promise(resolve => resolve({ data: data }))219      sandbox.stub(axios, 'get').returns(resolved)220      bchjs.Blockchain.getMempoolAncestors(221        'daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88',222        true223      )224        .then(result => {225          assert.deepStrictEqual(data, result)226        })227        .then(done, done)228    })229  })230  describe('#getMempoolDescendants', () => {231    let sandbox232    beforeEach(() => (sandbox = sinon.createSandbox()))233    afterEach(() => sandbox.restore())234    const data = {235      result: 'Transaction not in mempool'236    }237    it('should get mempool descendants', done => {238      const resolved = new Promise(resolve => resolve({ data: data }))239      sandbox.stub(axios, 'get').returns(resolved)240      bchjs.Blockchain.getMempoolDescendants(241        'daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88',242        true243      )244        .then(result => {245          assert.deepStrictEqual(data, result)246        })247        .then(done, done)248    })249  })250  describe('#getMempoolEntry', () => {251    let sandbox252    beforeEach(() => (sandbox = sinon.createSandbox()))253    afterEach(() => sandbox.restore())254    const data = {255      result: 'Transaction not in mempool'256    }257    it('should get mempool entry', done => {258      const resolved = new Promise(resolve => resolve({ data: data }))259      sandbox.stub(axios, 'get').returns(resolved)260      bchjs.Blockchain.getMempoolEntry(261        'daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88'262      )263        .then(result => {264          assert.deepStrictEqual(data, result)265        })266        .then(done, done)267    })268  })269  describe('#getMempoolInfo', () => {270    let sandbox271    beforeEach(() => (sandbox = sinon.createSandbox()))272    afterEach(() => sandbox.restore())273    const data = {274      result: {275        size: 317,276        bytes: 208583,277        usage: 554944,278        maxmempool: 300000000,279        mempoolminfee: 0280      }281    }282    it('should get mempool info', done => {283      const resolved = new Promise(resolve => resolve({ data: data }))284      sandbox.stub(axios, 'get').returns(resolved)285      bchjs.Blockchain.getMempoolInfo()286        .then(result => {287          assert.deepStrictEqual(data, result)288        })289        .then(done, done)290    })291  })292  describe('#getRawMempool', () => {293    let sandbox294    beforeEach(() => (sandbox = sinon.createSandbox()))295    afterEach(() => sandbox.restore())296    const data = {297      result: {298        transactions: [299          {300            txid:301              'ab36d68dd0a618592fe34e4a898e8beeeb4049133547dbb16f9338384084af96',302            size: 191,303            fee: 0.00047703,304            modifiedfee: 0.00047703,305            time: 1524883317,306            height: 527811,307            startingpriority: 5287822727.272727,308            currentpriority: 5287822727.272727,309            descendantcount: 1,310            descendantsize: 191,311            descendantfees: 47703,312            ancestorcount: 1,313            ancestorsize: 191,314            ancestorfees: 47703,315            depends: []316          }317        ]318      }319    }320    it('should get mempool info', done => {321      const resolved = new Promise(resolve => resolve({ data: data }))322      sandbox.stub(axios, 'get').returns(resolved)323      bchjs.Blockchain.getRawMempool()324        .then(result => {325          assert.deepStrictEqual(data, result)326        })327        .then(done, done)328    })329  })330  describe('#getTxOut', () => {331    // TODO finish this test332    let sandbox333    beforeEach(() => (sandbox = sinon.createSandbox()))334    afterEach(() => sandbox.restore())335    // const data = {336    //   result: {}337    // }338    it('should throw an error for improper txid.', async () => {339      try {340        await bchjs.Blockchain.getTxOut('badtxid')341      } catch (err) {342        assert2.include(err.message, 'txid needs to be a proper transaction ID')343      }344    })345    it('should throw an error if no vout value is provided.', async () => {346      try {347        await bchjs.Blockchain.getTxOut(348          'daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88'349        )350      } catch (err) {351        assert2.include(err.message, 'n must be an integer')352      }353    })354    it('should throw an error if include_mempool is not a boolean', async () => {355      try {356        await bchjs.Blockchain.getTxOut(357          'daf58932cb91619304dd4cbd03c7202e89ad7d6cbd6e2209e5f64ce3b6ed7c88',358          0,359          'bad value'360        )361      } catch (err) {362        assert2.include(363          err.message,364          'includeMempool input must be of type boolean'365        )366      }367    })368    it('should get information on an unspent tx', async () => {369      sandbox.stub(axios, 'post').resolves({ data: mockData.txOutUnspent })370      const result = await bchjs.Blockchain.getTxOut(371        '62a3ea958a463a372bc0caf2c374a7f60be9c624be63a0db8db78f05809df6d8',372        0,373        true374      )375      // console.log(`result: ${JSON.stringify(result, null, 2)}`)376      assert2.hasAllKeys(result, [377        'bestblock',378        'confirmations',379        'value',380        'scriptPubKey',381        'coinbase'382      ])383    })384    it('should get information on a spent tx', async () => {385      sandbox.stub(axios, 'post').resolves({ data: null })386      const result = await bchjs.Blockchain.getTxOut(387        '87380e52d151856b23173d6d8a3db01b984c6b50f77ea045a5a1cf4f54497871',388        0,389        true390      )391      // console.log(`result: ${JSON.stringify(result, null, 2)}`)392      assert2.equal(result, null)393    })394  })395  describe('#preciousBlock', () => {396    // TODO finish this test397    let sandbox398    beforeEach(() => (sandbox = sinon.createSandbox()))399    afterEach(() => sandbox.restore())400    const data = {401      result: {}402    }403    it('should get TODO', done => {404      const resolved = new Promise(resolve => resolve({ data: data }))405      sandbox.stub(axios, 'get').returns(resolved)406      bchjs.Blockchain.preciousBlock()407        .then(result => {408          assert.deepStrictEqual(data, result)409        })410        .then(done, done)411    })412  })413  describe('#pruneBlockchain', () => {414    let sandbox415    beforeEach(() => (sandbox = sinon.createSandbox()))416    afterEach(() => sandbox.restore())417    const data = 'Cannot prune blocks because node is not in prune mode.'418    it('should prune blockchain', done => {419      const resolved = new Promise(resolve => resolve({ data: data }))420      sandbox.stub(axios, 'post').returns(resolved)421      bchjs.Blockchain.pruneBlockchain(507)422        .then(result => {423          assert.deepStrictEqual(data, result)424        })425        .then(done, done)426    })427  })428  describe('#verifyChain', () => {429    let sandbox430    beforeEach(() => (sandbox = sinon.createSandbox()))431    afterEach(() => sandbox.restore())432    const data = true433    it('should verify blockchain', done => {434      const resolved = new Promise(resolve => resolve({ data: data }))435      sandbox.stub(axios, 'get').returns(resolved)436      bchjs.Blockchain.verifyChain(3, 6)437        .then(result => {438          assert.deepStrictEqual(data, result)439        })440        .then(done, done)441    })442  })443  describe('#verifyTxOutProof', () => {444    let sandbox445    beforeEach(() => (sandbox = sinon.createSandbox()))446    afterEach(() => sandbox.restore())447    const data = "proof must be hexadecimal string (not '')"448    it('should verify utxo proof', done => {449      const resolved = new Promise(resolve => resolve({ data: data }))450      sandbox.stub(axios, 'get').returns(resolved)451      bchjs.Blockchain.verifyTxOutProof('3')452        .then(result => {453          assert.deepStrictEqual(data, result)454        })455        .then(done, done)456    })457  })...Using AI Code Generation
1const sinon = require('sinon');2const sandbox = sinon.createSandbox();3const chai = require('chai');4const chaiAsPromised = require('chai-as-promised');5chai.use(chaiAsPromised);6const expect = chai.expect;7const stub = sandbox.stub();8const stubValue = 5;9stub.returns(stubValue);10const spy = sandbox.spy();11spy();12const mock = sandbox.mock();13mock.expects('foo').once().withArgs('bar').returns('baz');14const fake = sandbox.fake();15fake();16const fakeReturns = sandbox.fake.returns(5);17fakeReturns();18const fakeYields = sandbox.fake.yields(5);19fakeYields();20const fakeYieldsRight = sandbox.fake.yieldsRight(5);21fakeYieldsRight();22const fakeResolves = sandbox.fake.resolves(5);23fakeResolves();24const fakeRejects = sandbox.fake.rejects(5);25fakeRejects();26const assert = sandbox.assert;27assert.calledOnce(spy);28assert.calledWithExactly(stub, 1, 2, 3);29const match = sinon.match;30const obj = { foo: 'bar' };31const matcher = match(obj);32matcher.test(obj);33matcher.test({ foo: 'bar' });34const matchAny = sinon.match.any;35const matcherAny = matchAny;36matcherAny.test(obj);37matcherAny.test({ foo: 'bar' });38const matchDefined = sinon.match.defined;39const matcherDefined = matchDefined;40matcherDefined.test(obj);41matcherDefined.test({ foo: 'bar' });42const matchTruthy = sinon.match.truthy;43const matcherTruthy = matchTruthy;44matcherTruthy.test(obj);45matcherTruthy.test({ foo: 'barUsing AI Code Generation
1const sinon = require('sinon');2const assert = require('assert');3describe('sinon sandbox test', function() {4  let sandbox;5  beforeEach(function() {6    sandbox = sinon.createSandbox();7  });8  afterEach(function() {9    sandbox.restore();10  });11  it('should call the callback', function() {12    const callback = sandbox.spy();13    const proxy = sandbox.stub().callsFake(callback);14    proxy();15    assert(callback.called);16  });17});18const sinon = require('sinon');19const assert = require('assert');20describe('sinon sandbox test', function() {21  let sandbox;22  beforeEach(function() {23    sandbox = sinon.sandbox.create();24  });25  afterEach(function() {26    sandbox.restore();27  });28  it('should call the callback', function() {29    const callback = sandbox.spy();30    const proxy = sandbox.stub().callsFake(callback);31    proxy();32    assert(callback.called);33  });34});Using AI Code Generation
1const sinon = require("sinon");2const assert = require("assert");3const myModule = require("./myModule");4describe("test myModule", () => {5  let sandbox;6  beforeEach(() => {7    sandbox = sinon.createSandbox();8  });9  afterEach(() => {10    sandbox.restore();11  });12  it("should return true", () => {13    const stub = sandbox.stub(myModule, "myFunction").returns(true);14    const result = myModule.myFunction();15    assert.strictEqual(result, true);16    sinon.assert.calledOnce(stub);17  });18});19exports.myFunction = () => {20  return false;21};Using AI Code Generation
1const sinon = require('sinon');2const sandbox = sinon.createSandbox();3const myStub = sandbox.stub();4sandbox.restore();5const sinon = require('sinon');6const sandbox = sinon.createSandbox();7const myStub = sandbox.stub();8sandbox.restore();9const sinon = require('sinon');10const sandbox = sinon.createSandbox();11const myStub = sandbox.stub();12sandbox.restore();13const sinon = require('sinon');14const sandbox = sinon.createSandbox();15const myStub = sandbox.stub();16sandbox.restore();17const sinon = require('sinon');18const sandbox = sinon.createSandbox();19const myStub = sandbox.stub();20sandbox.restore();21const sinon = require('sinon');22const sandbox = sinon.createSandbox();23const myStub = sandbox.stub();24sandbox.restore();25const sinon = require('sinon');26const sandbox = sinon.createSandbox();27const myStub = sandbox.stub();28sandbox.restore();29const sinon = require('sinon');30const sandbox = sinon.createSandbox();31const myStub = sandbox.stub();32sandbox.restore();33const sinon = require('sinon');34const sandbox = sinon.createSandbox();35const myStub = sandbox.stub();36sandbox.restore();37const sinon = require('sinon');38const sandbox = sinon.createSandbox();39const myStub = sandbox.stub();40sandbox.restore();41const sinon = require('sinon');42const sandbox = sinon.createSandbox();43const myStub = sandbox.stub();44sandbox.restore();45const sinon = require('sinon');46const sandbox = sinon.createSandbox();47const myStub = sandbox.stub();48sandbox.restore();49const sinon = require('sinon');50const sandbox = sinon.createSandbox();51const myStub = sandbox.stub();52sandbox.restore();53const sinon = require('Using AI Code Generation
1const sinon = require('sinon');2const assert = require('assert');3const myObj = require('./myObj.js');4describe('test', function() {5  let sandbox;6  let stub;7  beforeEach(function() {8    sandbox = sinon.createSandbox();9    stub = sandbox.stub(myObj, 'myFunc');10  });11  afterEach(function() {12    sandbox.restore();13  });14  it('should call stub', function() {15    stub.returns('stubbed');16    assert.equal(myObj.myFunc(), 'stubbed');17  });18});19exports.myFunc = function() {20  return 'original';21};22var array = [{a:1, b:2}, {c:3, d:4}];23var string = JSON.stringify(array);24var backToArray = JSON.parse(string);25console.log(array);26console.log(string);27console.log(backToArray);28[ { a: 1, b: 2 }, { c: 3, d: 4 } ]29[{"a":1,"b":2},{"c":3,"d":4}]30[ { a: 1, b: 2 }, { c: 3, d: 4 } ]31var array = {a:1, b:2};32var string = JSON.stringify(array);33var backToArray = JSON.parse(string);34console.log(array);35console.log(string);36console.log(backToArray);37{ a: 1, b: 2 }38{"a":1,"b":2}39{ a: 1, b: 2 }Using AI Code Generation
1const sinon = require('sinon');2const assert = require('assert');3const obj = {4  method: function() {5    return 'called method';6  }7};8describe('obj', function() {9  beforeEach(function() {10    this.sandbox = sinon.createSandbox();11  });12  afterEach(function() {13    this.sandbox.restore();14  });15  it('should call original method', function() {16    const spy = this.sandbox.spy(obj, 'method');17    assert.equal(obj.method(), 'called method');18    assert(spy.calledOnce);19  });20});21const sinon = require('sinon');22const assert = require('assert');23const obj = {24  method: function() {25    return 'called method';26  }27};28describe('obj', function() {29  beforeEach(function() {30    this.sandbox = sinon.createSandbox();31  });32  afterEach(function() {33    this.sandbox.restore();34  });35  it('should call original method', function() {36    const spy = this.sandbox.spy(obj, 'method');37    assert.equal(obj.method(), 'called method');38    assert(spy.calledOnce);39  });40});41const sinon = require('sinon');42const assert = require('assert');43const obj = {44  method: function() {45    return 'called method';46  }47};48describe('obj', function() {49  beforeEach(function() {50    this.sandbox = sinon.createSandbox();51  });52  afterEach(function() {53    this.sandbox.restore();54  });55  it('should call original method', function() {56    const spy = this.sandbox.spy(obj, 'method');57    assert.equal(obj.method(), 'called method');58    assert(spy.calledOnce);59  });60});61const sinon = require('sinon');62const assert = require('assert');63const obj = {64  method: function() {65    return 'called method';66  }67};68describe('obj', function() {69  beforeEach(function() {70    this.sandbox = sinon.createSandbox();71  });72  afterEach(function() {73    this.sandbox.restore();74  });75  it('should call original method', function() {76    const spy = this.sandbox.spy(obj, 'method');Using AI Code Generation
1var sinon = require('sinon');2var sandbox = sinon.createSandbox();3var stub = sandbox.stub();4stub();5sandbox.restore();6var sinon = require('sinon');7var sandbox = sinon.createSandbox();8var stub = sandbox.stub();9stub();10sandbox.restore();11var sinon = require('sinon');12var sandbox = sinon.createSandbox();13var stub = sandbox.stub();14stub();15sandbox.restore();Using AI Code Generation
1const sandbox = sinon.createSandbox();2sandbox.stub();3sandbox.restore();4const stub = sinon.createStubInstance(ClassName);5stub.methodName.returns();6stub.restore();7const stub = sinon.createStubInstance(ClassName);8stub.methodName.returns();9stub.restore();10const stub = sinon.createStubInstance(ClassName);11stub.methodName.returns();12stub.restore();13const stub = sinon.createStubInstance(ClassName);14stub.methodName.returns();15stub.restore();16const stub = sinon.createStubInstance(ClassName);17stub.methodName.returns();18stub.restore();19const stub = sinon.createStubInstance(ClassName);20stub.methodName.returns();21stub.restore();22const stub = sinon.createStubInstance(ClassName);23stub.methodName.returns();24stub.restore();25const stub = sinon.createStubInstance(ClassName);26stub.methodName.returns();27stub.restore();28const stub = sinon.createStubInstance(ClassName);29stub.methodName.returns();30stub.restore();31const stub = sinon.createStubInstance(ClassName);32stub.methodName.returns();33stub.restore();Using AI Code Generation
1const sinon = require('sinon');2const assert = require('assert');3const sandbox = sinon.createSandbox();4const myFuncStub = sandbox.stub().returns('stubbed');5const myOtherFuncMock = sandbox.mock().once();6const mySpyFuncSpy = sandbox.spy();7const myFuncStub2 = sandbox.stub().returns('stubbed2');8const myOtherFuncMock2 = sandbox.mock().once();9const mySpyFuncSpy2 = sandbox.spy();10sandbox.restore();11assert(myFuncStub.restore.called);12assert(myOtherFuncMock.restore.called);13assert(mySpyFuncSpy.restore.called);14assert(myFuncStub2.restore.called);15assert(myOtherFuncMock2.restore.called);16assert(mySpyFuncSpy2.restore.called);17assert(myFuncStub.restore.called);18assert(myOtherFuncMock.restore.called);19assert(mySpyFuncSpy.restore.called);20assert(myFuncStub.restore.called);21assert(myOtherFuncMock.restore.called);22assert(mySpyFuncSpy.restore.called);23assert(myFuncStub.restore.called);24assert(myOtherFuncMock.restore.called);25assert(mySpyFuncSpy.restore.called);26assert(myFuncStub.restore.called);27assert(myOtherFuncMock.restore.called);28assert(mySpyFuncSpy.restore.called);29assert(myFuncStub.restore.called);30assert(myOtherFuncMock.restore.called);31assert(mySpyFuncSpy.restore.called);32assert(myFuncStub.restore.called);33assert(myOtherFuncMock.restore.called);34assert(mySpyFuncSpy.restore.called);35assert(myFuncStub.restore.called);36assert(myOtherFuncMock.restore.called);37assert(myLearn 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!!
