How to use __set__ method in rewire

Best JavaScript code snippet using rewire

testTools.js

Source:testTools.js Github

copy

Full Screen

...8 test(".listSteps()", () => {9 let getStepNames, getStepsData, learnClassifier, filterSteps;10 beforeChunk(() => {11 getStepNames = sinon.stub();12 tools.__set__("getStepNames", getStepNames);13 getStepsData = sinon.stub();14 tools.__set__("getStepsData", getStepsData);15 learnClassifier = sinon.stub();16 tools.__set__("learnClassifier", learnClassifier);17 filterSteps = sinon.stub();18 tools.__set__("filterSteps", filterSteps);19 });20 chunk("gets cached steps", () => {21 tools.__set__("stepsCache", ["my-step"]);22 expect(tools.listSteps()).to.be.eql(["my-step"]);23 expect(getStepNames).to.not.be.called;24 expect(getStepsData).to.not.be.called;25 expect(learnClassifier).to.not.be.called;26 expect(filterSteps).to.not.be.called;27 });28 chunk("gets steps with cache population", () => {29 getStepsData.returns(["my-step"]);30 tools.__set__("stepsCache", null);31 expect(tools.listSteps()).to.be.eql(["my-step"]);32 expect(tools.__get__("stepsCache")).to.be.eql(["my-step"]);33 expect(getStepNames).to.be.calledOnce;34 expect(getStepsData).to.be.calledOnce;35 expect(learnClassifier).to.be.calledOnce;36 expect(learnClassifier.args[0][0]).to.be.eql(["my-step"]);37 expect(filterSteps).to.not.be.called;38 });39 chunk("gets filtered steps", () => {40 filterSteps.returns(["my-another-step"]);41 tools.__set__("stepsCache", ["my-step"]);42 expect(tools.listSteps("another")).to.be.eql(["my-another-step"]);43 expect(filterSteps).to.be.calledOnce;44 expect(filterSteps.args[0]).to.be.eql([["my-step"], "another", false]);45 });46 });47 test(".printSteps()", () => {48 let listSteps, console_, d, highlight;49 beforeChunk(() => {50 listSteps = sinon.stub();51 tools.__set__("listSteps", listSteps);52 console_ = {53 log: sinon.stub(),54 };55 tools.__set__("console", console_);56 d = sinon.stub();57 tools.__set__("d", d);58 highlight = sinon.stub();59 tools.__set__("highlight", highlight);60 });61 chunk("print no steps message", () => {62 listSteps.returns([]);63 tools.printSteps();64 expect(listSteps).to.be.calledOnce;65 expect(listSteps.args[0]).to.be.eql([undefined, false]);66 expect(console_.log).to.be.calledOnce;67 expect(console_.log.args[0][0]).to.include("No steps are found");68 expect(d).to.not.be.called;69 });70 chunk("print steps", () => {71 listSteps.returns([{ name: "my step", description: "my description" }]);72 tools.printSteps();73 expect(console_.log).to.be.calledTwice;74 expect(d).to.be.calledTwice;75 expect(d.args[0][0]).to.include("1. my step:");76 expect(d.args[1][0]).to.include("my description");77 expect(highlight).to.not.be.called;78 });79 chunk("print steps with docs", () => {80 listSteps.returns([{ name: "my step", description: "my description", doc: "/* step docs */" }]);81 tools.printSteps();82 expect(console_.log).to.be.calledThrice;83 expect(highlight).to.be.calledOnce;84 expect(highlight.args[0][0]).to.be.equal("/* step docs */");85 expect(highlight.args[0][1]).to.be.eql({ language: "js" });86 });87 });88 test(".printTests()", () => {89 let fakeLoad, conf, console_;90 beforeChunk(() => {91 fakeLoad = sinon.stub();92 tools.__set__("fakeLoad", fakeLoad);93 conf = {94 test: { cases: [] },95 };96 tools.__set__("CONF", conf);97 console_ = {98 log: sinon.stub(),99 };100 tools.__set__("console", console_);101 });102 chunk("prints no tests message if no tests", () => {103 tools.printTests();104 expect(fakeLoad).to.be.calledOnce;105 expect(console_.log).to.be.calledOnce;106 expect(console_.log.args[0][0]).to.include("No tests are found");107 });108 chunk("prints no tests message if no filtered tests", () => {109 conf.test.cases = [{ name: "my test" }];110 tools.printTests("another test");111 expect(console_.log).to.be.calledOnce;112 expect(console_.log.args[0][0]).to.include("No tests are found");113 });114 chunk("prints tests", () => {115 conf.test.cases = [{ name: "my test" }, { name: "another test" }];116 tools.printTests("my test");117 expect(console_.log).to.be.calledOnce;118 expect(console_.log.args[0][0]).to.include("1. my test");119 });120 });121 test(".printPlugins()", () => {122 let plugins, console_;123 beforeChunk(() => {124 plugins = {125 get: sinon.stub(),126 };127 tools.__set__("plugins", plugins);128 console_ = {129 log: sinon.stub(),130 };131 tools.__set__("console", console_);132 });133 chunk("prints no plugins message", () => {134 plugins.get.returns([]);135 tools.printPlugins();136 expect(console_.log).to.be.calledOnce;137 expect(console_.log.args[0][0]).to.include("No plugins are detected");138 });139 chunk("prints plugins list", () => {140 plugins.get.returns([{ name: "my plugin", path: "/path/to/my/plugin" }]);141 tools.printPlugins();142 expect(console_.log).to.be.calledOnce;143 expect(console_.log.args[0][0]).to.include("1. my plugin");144 expect(console_.log.args[0][1]).to.include("/path/to/my/plugin");145 });146 });147 test(".listFixtures()", () => {148 let fakeLoad, getFixtures, filterFixtures;149 beforeChunk(() => {150 fakeLoad = sinon.stub();151 tools.__set__("fakeLoad", fakeLoad);152 getFixtures = sinon.stub().returns(["my fixture"]);153 tools.__set__("getFixtures", getFixtures);154 filterFixtures = sinon.stub().returns(["another fixture"]);155 tools.__set__("filterFixtures", filterFixtures);156 });157 chunk("gets list of all fixtures", () => {158 expect(tools.listFixtures()).to.be.eql(["my fixture"]);159 expect(fakeLoad).to.be.calledOnce;160 expect(filterFixtures).to.not.be.called;161 });162 chunk("gets list of filtered fixtures", () => {163 expect(tools.listFixtures("another")).to.be.eql(["another fixture"]);164 expect(filterFixtures.args[0]).to.be.eql([["my fixture"], "another", false]);165 });166 });167 test(".printFixtures()", () => {168 let listFixtures, console_, d, highlight;169 beforeChunk(() => {170 listFixtures = sinon.stub();171 tools.__set__("listFixtures", listFixtures);172 console_ = {173 log: sinon.stub(),174 };175 tools.__set__("console", console_);176 d = sinon.stub();177 tools.__set__("d", d);178 highlight = sinon.stub();179 tools.__set__("highlight", highlight);180 });181 chunk("prints no fixtures message", () => {182 listFixtures.returns([]);183 tools.printFixtures();184 expect(console_.log).to.be.calledOnce;185 expect(console_.log.args[0][0]).to.include("No fixtures are found");186 });187 chunk("prints list of fixtures", () => {188 listFixtures.returns([{ name: "my fixture" }]);189 tools.printFixtures();190 191 expect(console_.log).to.be.calledOnce;192 expect(d).to.be.calledOnce;193 expect(d.args[0][0]).to.include("1. my fixture");194 });195 chunk("prints list of fixtures with docs", () => {196 listFixtures.returns([{ name: "my fixture", doc: "/* fixture doc */" }]);197 tools.printFixtures();198 199 expect(console_.log).to.be.calledTwice;200 expect(d).to.be.calledOnce;201 expect(d.args[0][0]).to.include("1. my fixture");202 expect(highlight).to.be.calledOnce;203 expect(highlight.args[0][0]).to.be.equal("/* fixture doc */");204 expect(highlight.args[0][1]).to.be.eql({ language: "js" });205 });206 });207 test(".fakeLoad()", () => {208 let global_, require_;209 beforeChunk(() => {210 global_ = {};211 tools.__set__("global", global_);212 require_ = sinon.stub();213 tools.__set__("require", require_);214 });215 chunk(() => {216 tools.fakeLoad();217 expect(global_.before).to.be.a("function");218 expect(global_.after).to.be.a("function");219 expect(global_.beforeEach).to.be.a("function");220 expect(global_.afterEach).to.be.a("function");221 expect(global_.it).to.be.a("function");222 expect(global_.describe).to.be.a("function");223 expect(require_).to.be.calledTwice;224 expect(require_.args[0][0]).to.be.equal("./globals");225 expect(require_.args[1][0]).to.be.equal("./loader");226 });227 });228 test(".checkTestrail()", () => {229 let checkTestrailOpts, fakeLoad, conf, checkTestrailCases;230 beforeChunk(() => {231 checkTestrailOpts = sinon.stub();232 tools.__set__("checkTestrailOpts", checkTestrailOpts);233 fakeLoad = sinon.stub();234 tools.__set__("fakeLoad", fakeLoad);235 conf = {236 testrail: {237 host: "http://testrail",238 user: "user@example.com",239 token: "1234asdf",240 },241 };242 tools.__set__("CONF", conf);243 checkTestrailCases = sinon.stub();244 tools.__set__("checkTestrailCases", checkTestrailCases);245 });246 chunk(() => {247 const cb = () => {};248 tools.checkTestrail(cb);249 expect(checkTestrailOpts).to.be.calledOnce;250 expect(fakeLoad).to.be.calledOnce;251 expect(checkTestrailCases).to.be.calledOnce;252 expect(checkTestrailCases.args[0][1]).to.be.equal(cb);253 const client = checkTestrailCases.args[0][0];254 expect(client).to.be.an.instanceof(Testrail);255 expect(client.host).to.be.equal("http://testrail");256 expect(client.user).to.be.equal("user@example.com");257 expect(client.password).to.be.equal("1234asdf");258 });259 });260 test("checkTestrailOpts()", () => {261 let checkTestrailOpts, conf;262 before(() => {263 checkTestrailOpts = tools.__get__("checkTestrailOpts");264 conf = {265 testrail: {266 host: "http://testrail",267 },268 };269 tools.__set__("CONF", conf);270 });271 chunk("passes if options exist", () => {272 checkTestrailOpts();273 });274 chunk("throws if options don't exist", () => {275 conf.testrail.host = null;276 expect(checkTestrailOpts).to.throw(277 "TestRail option 'host' isn't specified in config");278 });279 });280 test("checkTestrailMissed()", () => {281 let checkTestrailMissed, console_, conf;282 beforeChunk(() => {283 checkTestrailMissed = tools.__get__("checkTestrailMissed");284 console_ = {285 log: sinon.stub(),286 };287 tools.__set__("console", console_);288 conf = {289 test: {290 cases: [{ name: "my case" }],291 },292 };293 tools.__set__("CONF", conf);294 });295 chunk("returns 0 if no missed cases", () => {296 expect(checkTestrailMissed([{ title: "my case" }])).to.be.equal(0);297 expect(console_.log).to.not.be.called;298 });299 chunk("returns 1 if there are missed cases", () => {300 expect(checkTestrailMissed([{ title: "another case" }])).to.be.equal(1);301 expect(console_.log).to.be.calledTwice;302 expect(console_.log.args[0][0]).to.include("Missed TestRail cases");303 expect(console_.log.args[1][0]).to.include("1. my case");304 });305 });306 test("checkTestrailNotImplemented()", () => {307 let checkTestrailNotImplemented, console_, conf;308 beforeChunk(() => {309 checkTestrailNotImplemented = tools.__get__("checkTestrailNotImplemented");310 console_ = {311 log: sinon.stub(),312 };313 tools.__set__("console", console_);314 conf = {315 test: {316 cases: [{ name: "my case" }],317 },318 };319 tools.__set__("CONF", conf);320 });321 chunk("returns 0 if all cases are implemented", () => {322 expect(checkTestrailNotImplemented([{ title: "my case" }])).to.be.equal(0);323 expect(console_.log).to.not.be.called;324 });325 chunk("returns 1 if there are not implemented cases", () => {326 expect(checkTestrailNotImplemented([{ title: "another case" }])).to.be.equal(1);327 expect(console_.log).to.be.calledTwice;328 expect(console_.log.args[0][0]).to.include("Not implemented TestRail cases");329 expect(console_.log.args[1][0]).to.include("1. another case");330 });331 });332 test("checkTestrailDuplicates()", () => {333 let checkTestrailDuplicates, console_;334 beforeChunk(() => {335 checkTestrailDuplicates = tools.__get__("checkTestrailDuplicates");336 console_ = {337 log: sinon.stub(),338 };339 tools.__set__("console", console_);340 });341 chunk("returns 0 if no missed cases", () => {342 expect(checkTestrailDuplicates([{ title: "my case" }, { title: "another case" }])).to.be.equal(0);343 expect(console_.log).to.not.be.called;344 });345 chunk("returns 1 if there are missed cases", () => {346 expect(checkTestrailDuplicates([{ title: "my case" }, { title: "my case" }])).to.be.equal(1);347 expect(console_.log).to.be.calledTwice;348 expect(console_.log.args[0][0]).to.include("TestRail duplicated cases");349 expect(console_.log.args[1][0]).to.include("1. my case");350 });351 });352 test("checkTestrailCases()", () => {353 let checkTestrailCases, conf, client, console_;354 beforeChunk(() => {355 checkTestrailCases = tools.__get__("checkTestrailCases");356 conf = {357 testrail: {358 projectId: 1,359 suiteId: 2,360 host: "http://testrail",361 },362 };363 tools.__set__("CONF", conf);364 client = {365 getCases: sinon.stub(),366 };367 console_ = {368 log: sinon.stub(),369 };370 tools.__set__("console", console_);371 });372 chunk("calls testrail client", () => {373 checkTestrailCases(client);374 expect(client.getCases).to.be.calledOnce;375 expect(client.getCases.args[0][0]).to.be.equal(1);376 expect(client.getCases.args[0][1]).to.be.eql({ suite_id: 2 });377 });378 scope("callback", () => {379 let cb, callback, checkTestrailDuplicates,380 checkTestrailNotImplemented, checkTestrailMissed;381 beforeChunk(() => {382 cb = sinon.stub();383 checkTestrailCases(client, cb);384 callback = client.getCases.args[0][2];385 checkTestrailDuplicates = sinon.stub();386 tools.__set__("checkTestrailDuplicates", checkTestrailDuplicates);387 checkTestrailNotImplemented = sinon.stub();388 tools.__set__("checkTestrailNotImplemented", checkTestrailNotImplemented);389 checkTestrailMissed = sinon.stub();390 tools.__set__("checkTestrailMissed", checkTestrailMissed);391 });392 chunk("fails if error response", () => {393 callback("response error");394 expect(cb).to.be.calledOnce;395 expect(cb.args[0][0]).to.be.equal(1);396 expect(console_.log).to.be.calledOnce;397 expect(console_.log.args[0][0]).to.be.equal("response error");398 });399 chunk("fails if cases check is failed", () => {400 checkTestrailDuplicates.returns(1);401 checkTestrailNotImplemented.returns(1);402 checkTestrailMissed.returns(1);403 callback();404 expect(cb).to.be.calledOnce;405 expect(cb.args[0][0]).to.be.equal(3);406 expect(console_.log).to.be.calledOnce;407 expect(console_.log.args[0][0]).to.include("TestRail suite is");408 });409 chunk("passes if cases check is passed", () => {410 checkTestrailDuplicates.returns(0);411 checkTestrailNotImplemented.returns(0);412 checkTestrailMissed.returns(0);413 callback();414 expect(cb).to.be.calledOnce;415 expect(cb.args[0][0]).to.be.equal(0);416 expect(console_.log).to.be.calledTwice;417 expect(console_.log.args[0][0]).to.include("cases correspond");418 expect(console_.log.args[1][0]).to.include("TestRail suite is");419 });420 });421 });422 test("getFixtures()", () => {423 let getFixtures;424 beforeChunk(() => {425 getFixtures = tools.__get__("getFixtures");426 const global_ = {427 fxMyFixture: () => {},428 myFixture: () => {},429 fxSomeVar: 5,430 };431 tools.__set__("global", global_);432 tools.__set__("utils", { getDoc: () => "/** fixture docs */" });433 });434 chunk(() => {435 expect(getFixtures()).to.be.eql([{436 name: "fxMyFixture",437 doc: "/** fixture docs */",438 }]);439 });440 });441 test("filterFixtures()", () => {442 let filterFixtures, fixtures;443 beforeChunk(() => {444 filterFixtures = tools.__get__("filterFixtures");445 fixtures = [{446 name: "fx1",447 doc: "doc of fixture 1",448 }, {449 name: "fx2",450 doc: "doc of fixture 2",451 }];452 });453 chunk("returns nothing if filter is mismatched", () => {454 expect(filterFixtures(fixtures, "fixture 1", true)).to.be.eql([]);455 });456 chunk("returns fixtures filtered by name", () => {457 expect(filterFixtures(fixtures, "fx1", true)).to.be.eql([{458 name: "fx1",459 doc: "doc of fixture 1",460 }]);461 });462 chunk("returns fixtures filtered by doc", () => {463 expect(filterFixtures(fixtures, "fixture 1")).to.be.eql([{464 name: "fx1",465 doc: "doc of fixture 1",466 }]);467 });468 });469 test("getStepNames()", () => {470 let getStepNames, global_, fakeLoad;471 beforeChunk(() => {472 getStepNames = tools.__get__("getStepNames");473 global_ = {};474 tools.__set__("global", global_);475 tools.__set__("$", {476 launchBrowser: null,477 closeBrowser: null,478 constructor: null,479 _start: null,480 0: null481 });482 fakeLoad = sinon.stub();483 tools.__set__("fakeLoad", fakeLoad);484 });485 chunk(() => {486 expect(getStepNames()).to.be.eql(["closeBrowser", "launchBrowser"]);487 expect(fakeLoad).to.be.calledOnce;488 });489 });490 test("getStepsData()", () => {491 let getStepsData;492 beforeChunk(() => {493 getStepsData = tools.__get__("getStepsData");494 tools.__set__("$", {495 "my step": () => {},496 "some step": 5,497 "some func": () => {},498 });499 tools.__set__("funcDescription", () => "my step description");500 tools.__set__("utils", { getDoc: () => "my step doc" });501 });502 chunk(() => {503 expect(getStepsData(["my step", "some step"])).to.be.eql([{504 name: "my step",505 description: "my step description",506 doc: "my step doc",507 }]);508 });509 });510 test("filterSteps()", () => {511 let filterSteps, steps, classifySteps, mergeSteps;512 beforeChunk(() => {513 filterSteps = tools.__get__("filterSteps");514 classifySteps = sinon.stub();515 tools.__set__("classifySteps", classifySteps);516 mergeSteps = sinon.stub();517 tools.__set__("mergeSteps", mergeSteps);518 steps = [{519 name: "step1",520 doc: "doc of step 1",521 description: "function () {...}",522 }, {523 name: "step2",524 doc: "doc of step 2",525 description: "function () {...}",526 }];527 });528 chunk("returns nothing if filter is mismatched", () => {529 expect(filterSteps(steps, "doc of step 1", true)).to.be.eql([]);530 });531 chunk("returns steps filtered by name", () => {532 expect(filterSteps(steps, "step1", true)).to.be.eql([{533 name: "step1",534 doc: "doc of step 1",535 description: "function () {...}",536 }]);537 });538 chunk("returns steps filtered by doc", () => {539 mergeSteps.returns([{540 name: "classified step",541 doc: "doc of classified step",542 description: "function () {...}",543 }]);544 expect(filterSteps(steps, "step 1")).to.be.eql([{545 name: "classified step",546 doc: "doc of classified step",547 description: "function () {...}",548 }]);549 });550 });551 test("learnClassifier()", () => {552 let learnClassifier, classifier;553 beforeChunk(() => {554 learnClassifier = tools.__get__("learnClassifier");555 classifier = {556 learn: sinon.stub(),557 };558 tools.__set__("classifier", classifier);559 });560 chunk(() => {561 const steps = [{562 name: "step 1",563 doc: "doc 1",564 }, {565 name: "step 2",566 doc: "doc 2",567 }];568 learnClassifier(steps);569 expect(classifier.learn).to.be.calledTwice;570 expect(classifier.learn.args[0]).to.be.eql(["doc 1", "step 1"]);571 expect(classifier.learn.args[1]).to.be.eql(["doc 2", "step 2"]);572 });573 });574 test("classifySteps()", () => {575 let classifySteps, classifier;576 beforeChunk(() => {577 classifySteps = tools.__get__("classifySteps");578 classifier = {579 classify: sinon.stub(),580 };581 tools.__set__("classifier", classifier);582 });583 chunk(() => {584 const steps = [{585 name: "step 1",586 }, {587 name: "step 2",588 }, {589 name: "step 3",590 }];591 classifier.classify.returns([{ label: "step 2" }]);592 expect(classifySteps(steps, "step 2")).to.be.eql([{593 name: "step 2",594 }]);595 });...

Full Screen

Full Screen

testReporterStdout.js

Source:testReporterStdout.js Github

copy

Full Screen

...4 let conf, stdout;5 beforeChunk(() => {6 conf = {};7 conf.report = { dir: "/path/to/report" };8 stdoutReporter.__set__("CONF", conf);9 stdout = sinon.stub();10 });11 afterChunk(() => {12 stdoutReporter.__reset__();13 });14 test(".start()", () => {15 let fs, fse;16 beforeChunk(() => {17 fs = {18 createWriteStream: sinon.spy(),19 };20 stdoutReporter.__set__("fs", fs);21 fse = {22 mkdirsSync: sinon.spy(),23 };24 stdoutReporter.__set__("fse", fse);25 });26 chunk("activates stream", () => {27 stdoutReporter.start();28 expect(fse.mkdirsSync).to.be.calledOnce;29 expect(fse.mkdirsSync.args[0][0]).to.be.equal("/path/to/report");30 expect(fs.createWriteStream).to.be.calledOnce;31 expect(fs.createWriteStream.args[0][0]).to.be.equal("/path/to/report/stdout.log");32 expect(fs.createWriteStream.args[0][1]).to.be.eql({ flags: "w" });33 });34 });35 test(".end()", () => {36 let epilogue;37 beforeChunk(() => {38 epilogue = sinon.stub();39 stdoutReporter.__set__("epilogue", epilogue);40 stdoutReporter.__set__("stdout", stdout);41 });42 chunk("finalizes report", () => {43 stdoutReporter.end();44 expect(epilogue).to.be.calledOnce;45 expect(stdout).to.be.calledThrice;46 expect(stdout.args[2][0]).to.include("Local report is /path/to/report");47 });48 });49 test(".scope()", () => {50 beforeChunk(() => {51 stdoutReporter.__set__("stdout", stdout);52 stdoutReporter.__set__("indents", 0);53 });54 chunk("prints scope details", () => {55 stdoutReporter.scope({ title: "my scope" });56 expect(stdout).to.be.calledTwice;57 expect(stdout.args[1][0]).to.be.include("scope: my scope");58 });59 chunk("prints nothing", () => {60 stdoutReporter.__set__("indents", -1);61 stdoutReporter.scope({ title: "my scope" });62 expect(stdout).to.not.be.called;63 });64 });65 test(".scopeEnd()", () => {66 beforeChunk(() => {67 stdoutReporter.__set__("stdout", stdout);68 stdoutReporter.__set__("indents", 1);69 });70 chunk(() => {71 stdoutReporter.scopeEnd();72 expect(stdout).to.be.calledOnce;73 });74 });75 test(".suite()", () => {76 beforeChunk(() => {77 stdoutReporter.__set__("stdout", stdout);78 stdoutReporter.__set__("indents", 0);79 });80 chunk("prints suite details", () => {81 stdoutReporter.suite({ title: "my suite" });82 expect(stdout).to.be.calledTwice;83 expect(stdout.args[1][0]).to.be.include("suite: my suite");84 });85 chunk("prints nothing", () => {86 stdoutReporter.__set__("indents", -1);87 stdoutReporter.suite({ title: "my suite" });88 expect(stdout).to.not.be.called;89 });90 });91 test(".suiteEnd()", () => {92 beforeChunk(() => {93 stdoutReporter.__set__("stdout", stdout);94 stdoutReporter.__set__("indents", 1);95 });96 chunk(() => {97 stdoutReporter.suiteEnd();98 expect(stdout).to.be.calledOnce;99 });100 });101 test(".test()", () => {102 beforeChunk(() => {103 stdoutReporter.__set__("stdout", stdout);104 stdoutReporter.__set__("indents", 0);105 });106 chunk("prints test details", () => {107 stdoutReporter.test({ title: "my test" });108 expect(stdout).to.be.calledTwice;109 expect(stdout.args[1][0]).to.be.include("test: my test");110 });111 chunk("prints nothing", () => {112 stdoutReporter.__set__("indents", -1);113 stdoutReporter.test({ title: "my test" });114 expect(stdout).to.not.be.called;115 });116 });117 test(".testEnd()", () => {118 beforeChunk(() => {119 stdoutReporter.__set__("stdout", stdout);120 stdoutReporter.__set__("indents", 1);121 });122 chunk(() => {123 stdoutReporter.testEnd();124 expect(stdout).to.be.calledOnce;125 });126 });127 test(".pass()", () => {128 beforeChunk(() => {129 stdoutReporter.__set__("stdout", stdout);130 });131 chunk("prints chunk with name", () => {132 stdoutReporter.pass({ title: "my chunk" });133 expect(stdout).to.be.calledOnce;134 expect(stdout.args[0][0]).to.include("✓ chunk: my chunk");135 });136 chunk("prints chunk without name", () => {137 stdoutReporter.pass({});138 expect(stdout).to.be.calledOnce;139 expect(stdout.args[0][0]).to.include("✓ chunk");140 expect(stdout.args[0][0]).to.not.include("✓ chunk:");141 });142 });143 test(".skip()", () => {144 beforeChunk(() => {145 stdoutReporter.__set__("stdout", stdout);146 });147 chunk("prints chunk with name", () => {148 stdoutReporter.skip({ title: "my chunk" });149 expect(stdout).to.be.calledOnce;150 expect(stdout.args[0][0]).to.include("# chunk: my chunk");151 });152 chunk("prints chunk without name", () => {153 stdoutReporter.skip({});154 expect(stdout).to.be.calledOnce;155 expect(stdout.args[0][0]).to.include("# chunk");156 expect(stdout.args[0][0]).to.not.include("# chunk:");157 });158 });159 test(".fail()", () => {160 beforeChunk(() => {161 stdoutReporter.__set__("stdout", stdout);162 });163 chunk("prints chunk with name", () => {164 stdoutReporter.fail({ title: "my chunk" });165 expect(stdout).to.be.calledOnce;166 expect(stdout.args[0][0]).to.include("✖ chunk: my chunk");167 });168 chunk("prints chunk without name", () => {169 stdoutReporter.fail({});170 expect(stdout).to.be.calledOnce;171 expect(stdout.args[0][0]).to.include("✖ chunk");172 expect(stdout.args[0][0]).to.not.include("✖ chunk:");173 });174 chunk("prints chunk without name", () => {175 stdoutReporter.fail({ type: "hook" });176 expect(stdout).to.be.calledOnce;177 expect(stdout.args[0][0]).to.include("✖ hook");178 expect(stdout.args[0][0]).to.not.include("✖ hook:");179 });180 chunk("prints test error", () => {181 conf.report.errorsNow = true;182 conf.test = { curCase: { errors: ["test error"] }};183 stdoutReporter.fail({});184 expect(stdout).to.be.calledTwice;185 expect(stdout.args[1][0]).to.include("test error");186 });187 chunk("prints session error", () => {188 conf.report.errorsNow = true;189 conf.test = {};190 conf.session = { errors: ["session error"] };191 stdoutReporter.fail({});192 expect(stdout).to.be.calledTwice;193 expect(stdout.args[1][0]).to.include("session error");194 });195 });196 test(".done()", () => {197 let report;198 beforeChunk(() => {199 report = {200 end: sinon.spy(o => o()),201 };202 stdoutReporter.__set__("report", report);203 });204 chunk(async () => {205 await stdoutReporter.done();206 expect(report.end).to.be.calledOnce;207 });208 });209 test("indent()", () => {210 let indent;211 beforeChunk(() => {212 indent = stdoutReporter.__get__("indent");213 });214 [[0, ""], [1, ""], [2, " "], [3, " "]].forEach(([indents, result]) => {215 chunk(`for ${indents} indent(s) it should be '${result}'`, () => {216 stdoutReporter.__set__("indents", indents);217 expect(indent()).to.be.equal(result);218 });219 });220 });221 test("stdout()", () => {222 let console_, report;223 beforeChunk(() => {224 console_ = {225 log: sinon.stub(),226 };227 stdoutReporter.__set__("console", console_);228 report = {229 write: sinon.stub(),230 };231 stdoutReporter.__set__("report", report);232 });233 beforeChunk(() => {234 stdout = stdoutReporter.__get__("stdout");235 });236 chunk(() => {237 stdout("hello", "world");238 expect(report.write).to.be.calledOnce;239 expect(report.write.args[0][0]).to.be.equal("hello world\n");240 expect(console_.log).to.be.calledOnce;241 expect(console_.log.args[0][0]).to.be.equal("hello");242 expect(console_.log.args[0][1]).to.be.equal("world");243 });244 });245 test("epilogue()", () => {246 let epilogue,247 printStatistics,248 printSkippedTests,249 printTestErrors,250 printSessionErrors;251 beforeChunk(() => {252 epilogue = stdoutReporter.__get__("epilogue");253 printStatistics = sinon.stub();254 stdoutReporter.__set__("printStatistics", printStatistics);255 printSkippedTests = sinon.stub();256 stdoutReporter.__set__("printSkippedTests", printSkippedTests);257 printTestErrors = sinon.stub();258 printSessionErrors = sinon.stub();259 stdoutReporter.__set__("utils", {260 printTestErrors, printSessionErrors,261 });262 });263 chunk("prints all test results", () => {264 conf.test = {265 cases: [266 { status: "passed" },267 { status: "skipped" },268 { status: "failed" },269 ],270 };271 epilogue();272 expect(printStatistics).to.be.calledOnce;273 expect(printStatistics.args[0]).to.be.eql([1, 1]);274 expect(printSkippedTests).to.be.calledOnce;275 expect(printSkippedTests.args[0][0]).to.be.eql([{ status: "skipped" }]);276 expect(printTestErrors).to.be.calledOnce;277 expect(printTestErrors.args[0][0]).to.be.eql([{ status: "failed" }]);278 expect(printSessionErrors).to.be.calledOnce;279 });280 chunk("print no results", () => {281 conf.test = {282 cases: [],283 };284 epilogue();285 expect(printStatistics).to.be.calledOnce;286 expect(printStatistics.args[0]).to.be.eql([0, 0]);287 expect(printSkippedTests).to.not.be.called;288 expect(printTestErrors).to.be.calledOnce;289 expect(printSessionErrors).to.be.calledOnce;290 });291 });292 test("printStatistics()", () => {293 let printStatistics;294 beforeChunk(() => {295 printStatistics = stdoutReporter.__get__("printStatistics");296 stdoutReporter.__set__("stdout", stdout);297 });298 chunk("prints full statistics", () => {299 conf.test = {300 cases: [301 { duration: 60000, chunks: ["my chunk"] },302 { duration: 30000, chunks: ["my chunk"] },303 ],304 };305 printStatistics(1, 1);306 expect(stdout).to.have.callCount(5);307 expect(stdout.args[0][0]).to.include("1").and.include("passed test");308 expect(stdout.args[1][0]).to.include("1").and.include("failed test");309 expect(stdout.args[2][0]).to.include("2 executed chunks");310 expect(stdout.args[4][0]).to.include("Summary tests time is");311 expect(stdout.args[4][1]).to.include("1m 30s");312 });313 chunk("prints statistics of one chunk", () => {314 conf.test = {315 cases: [316 { duration: 60000, chunks: ["my chunk"] },317 ],318 };319 printStatistics(0, 2);320 expect(stdout.args[0][0]).to.include("2").and.include("failed tests");321 expect(stdout.args[1][0]).to.include("1 executed chunk");322 });323 chunk("prints nothing", () => {324 conf.test = { cases: [] };325 printStatistics(0, 0);326 expect(stdout).to.not.be.called;327 });328 chunk("prints statistics for multiple passed tests", () => {329 conf.test = {330 cases: [331 { duration: 1000, chunks: ["my chunk"] },332 { duration: 1000, chunks: ["my chunk"] },333 ],334 };335 printStatistics(2, 0);336 expect(stdout.args[0][0]).to.include("2").and.include("passed tests");337 expect(stdout.args[3][1]).to.include("2 sec");338 });339 });340 test("printSkippedTests()", () => {341 let printSkippedTests;342 beforeChunk(() => {343 printSkippedTests = stdoutReporter.__get__("printSkippedTests");344 stdoutReporter.__set__("stdout", stdout);345 });346 chunk("prints info with details", () => {347 const skippedTests = [{ name: "my test", rawInfo: ["due to bug"] }];348 printSkippedTests(skippedTests);349 expect(stdout).to.be.calledThrice;350 expect(stdout.args[1][0]).to.include("skipped test");351 expect(stdout.args[2][0]).to.include("my test").and.include("due to bug");352 });353 chunk("prints info without details", () => {354 const skippedTests = [{ name: "my test", rawInfo: [] }, { name: "other test", rawInfo: [] }];355 printSkippedTests(skippedTests);356 expect(stdout).to.have.callCount(4);357 expect(stdout.args[1][0]).to.include("skipped tests");358 expect(stdout.args[2][0]).to.include("my test");...

Full Screen

Full Screen

testPlugins.js

Source:testPlugins.js Github

copy

Full Screen

...5 plugins.__reset__();6 });7 test(".get()", () => {8 chunk("gets found plugins", () => {9 plugins.__set__("systemPlugins", ["plugin-1", "plugin-2"]);10 plugins.__set__("getNames", () => []);11 plugins.__set__("customPlugins", []);12 expect(plugins.get()).to.be.eql(["plugin-1", "plugin-2"]);13 });14 chunk("loads system plugins if they are not", () => {15 const findPlugins = sinon.stub().returns(["plugin-1", "plugin-2"]),16 getPluginsFromDir = sinon.spy(o => o),17 loadPlugins = sinon.spy(o => o);18 plugins.__set__("findPlugins", findPlugins);19 plugins.__set__("getPluginsFromDir", getPluginsFromDir);20 plugins.__set__("loadPlugins", loadPlugins);21 plugins.__set__("getNames", () => []);22 plugins.__set__("customPlugins", []);23 expect(plugins.get()).to.be.eql(["plugin-1", "plugin-2"]);24 });25 chunk("filters system plugins if they match custom", () => {26 plugins.__set__("systemPlugins", [{ name: "plugin-1" }, { name: "plugin-2" }]);27 plugins.__set__("getNames", () => ["plugin-2"]);28 plugins.__set__("customPlugins", []);29 expect(plugins.get()).to.be.eql([{ name: "plugin-1" }]);30 });31 chunk("concats custom plugins with system", () => {32 plugins.__set__("systemPlugins", ["plugin-1", "plugin-2"]);33 plugins.__set__("getNames", () => []);34 plugins.__set__("customPlugins", ["plugin-3"]);35 expect(plugins.get()).to.be.eql(["plugin-1", "plugin-2", "plugin-3"]);36 });37 });38 test("findPlugins()", () => {39 let findPlugins, conf;40 beforeChunk(() => {41 findPlugins = plugins.__get__("findPlugins");42 conf = { plugins: {}};43 plugins.__set__("CONF", conf);44 });45 chunk("does nothing if default plugins are disabled", () => {46 conf.plugins.disableDefault = true;47 expect(findPlugins(["plugin-1"])).to.be.eql(["plugin-1"]);48 });49 chunk("does nothing if plugin dirs don't exist", () => {50 plugins.__set__("fs", { existsSync: () => false });51 expect(findPlugins(["plugin-1"])).to.be.eql(["plugin-1"]);52 });53 chunk("finds glace plugins", () => {54 plugins.__set__("dirsToSearchPlugins", () => ["/path/to/custom"]);55 plugins.__set__("fs", { existsSync: () => true, readdirSync: () => ["glace-2", "glace-3", "glace-3"] });56 const foundPlugins = findPlugins([57 { name: "glace-1", path: "/path/to/plugin/1" },58 { name: "glace-2", path: "/path/to/plugin/2" },59 ]);60 expect(foundPlugins.map(p => p.name)).to.be.eql(["glace-1", "glace-2", "glace-3"]);61 expect(foundPlugins[1].path).to.be.equal("/path/to/custom/glace-2");62 });63 });64 test("getPluginsFromDir()", () => {65 let getPluginsFromDir, conf;66 beforeChunk(() => {67 getPluginsFromDir = plugins.__get__("getPluginsFromDir");68 conf = { plugins: {}};69 plugins.__set__("CONF", conf);70 });71 chunk("does nothing if no plugins dir", () => {72 conf.plugins.dir = null;73 expect(getPluginsFromDir(["plugin-1"])).to.be.eql(["plugin-1"]);74 });75 chunk("throw error if plugin dir is not a dir", () => {76 conf.plugins.dir = "/path/to/custom";77 plugins.__set__("fs", { existsSync: () => true, statSync: () => { return { isDirectory: () => false }; } });78 expect(() => getPluginsFromDir([])).to.throw("isn't a folder");79 });80 chunk("throw error if plugin dir doesn't exist", () => {81 conf.plugins.dir = "/path/to/custom";82 plugins.__set__("fs", { existsSync: () => false });83 expect(() => getPluginsFromDir([])).to.throw("doesn't exist");84 });85 chunk("gets plugins from custom dir", () => {86 conf.plugins.dir = "/path/to/custom";87 plugins.__set__("fs", {88 existsSync: () => true,89 statSync: () => { return { isDirectory: () => true }; },90 readdirSync: () => ["plugin-2", "plugin-3"],91 });92 const gotPlugins = getPluginsFromDir([93 { name: "plugin-1", path: "/path/to/plugin/1" },94 { name: "plugin-2", path: "/path/to/plugin/2" },95 ]);96 expect(gotPlugins.map(p => p.name)).to.be.eql(["plugin-1", "plugin-2", "plugin-3"]);97 expect(gotPlugins[1].path).to.be.equal("/path/to/custom/plugin-2");98 });99 });100 test("loadPlugins()", () => {101 let loadPlugins, logger;102 beforeChunk(() => {103 loadPlugins = plugins.__get__("loadPlugins");104 logger = { error: sinon.stub() };105 plugins.__set__("LOG", logger);106 });107 chunk("loads plugins", () => {108 plugins.__set__("require", () => Object());109 const loadedPlugins = loadPlugins([{ name: "plugin", path: "/path/to/plugin" }]);110 expect(loadedPlugins).to.have.length(1);111 expect(loadedPlugins[0].module).to.exist;112 expect(() => loadedPlugins[0].name = "glace-plugin").to.throw("read only property");113 });114 chunk("throws error if plugin can't be loaded", () => {115 plugins.__set__("require", () => { throw Error(); });116 const loadedPlugins = loadPlugins([{ name: "plugin", path: "/path/to/plugin" }]);117 expect(loadedPlugins).to.have.length(0);118 expect(logger.error).to.be.calledOnce;119 expect(logger.error.args[0][0]).to.startWith("Can't load plugin");120 });121 });122 test(".getModules()", () => {123 chunk(() => {124 plugins.__set__("get", () => [125 { module: { config: "module-1" }},126 { module: { config: "module-2" }},127 { module: {}},128 ]);129 expect(plugins.getModules("config")).to.be.eql(["module-1", "module-2"]);130 });131 });132 test(".clearCache()", () => {133 chunk(() => {134 plugins.__set__("systemPlugins", ["plugin-1"]);135 expect(plugins.__get__("systemPlugins")).to.be.eql(["plugin-1"]);136 plugins.clearCache();137 expect(plugins.__get__("systemPlugins")).to.be.null;138 });139 });140 test(".register()", () => {141 let require_, logger;142 beforeChunk(() => {143 require_ = sinon.stub();144 require_.resolve = sinon.stub();145 plugins.__set__("require", require_);146 logger = { warn: sinon.stub() };147 plugins.__set__("LOG", logger);148 });149 chunk("does nothing if plugin is registered already", () => {150 plugins.__set__("getNames", () => ["my-plugin"]);151 plugins.register("my-plugin");152 expect(plugins.__get__("customPlugins")).to.have.length(0);153 expect(logger.warn.args[0][0]).to.endWith("is registered already");154 });155 chunk("registers plugin", () => {156 plugins.__set__("getNames", () => []);157 plugins.register("my-plugin");158 const customPlugins = plugins.__get__("customPlugins");159 expect(customPlugins).to.have.length(1);160 expect(customPlugins[0].name).to.be.equal("my-plugin");161 expect(require_.args[0][0]).to.be.equal("my-plugin");162 expect(require_.resolve.args[0][0]).to.be.equal("my-plugin");163 });164 });165 test(".remove()", () => {166 let logger;167 beforeChunk(() => {168 logger = { warn: sinon.stub() };169 plugins.__set__("LOG", logger);170 });171 chunk("does nothing if plugin isn't registered yet", () => {172 plugins.__set__("customPlugins", []);173 plugins.remove("my-plugin");174 expect(plugins.__get__("customPlugins")).to.have.length(0);175 expect(logger.warn.args[0][0]).to.endWith("isn't registered yet");176 });177 chunk("removes plugins from list of registered", () => {178 plugins.__set__("customPlugins", [{ name: "my-plugin" }]);179 plugins.remove("my-plugin");180 expect(plugins.__get__("customPlugins")).to.have.length(0);181 });182 });183 test(".getNames()", () => {184 chunk("get custom plugin names", () => {185 plugins.__set__("customPlugins", [{ name: "plugin-1" }, { name: "plugin-2" }]);186 expect(plugins.getNames({ type: "custom" })).to.be.eql(["plugin-1", "plugin-2"]);187 });188 chunk("get system plugin names", () => {189 plugins.__set__("systemPlugins", [{ name: "plugin-1" }, { name: "plugin-2" }]);190 expect(plugins.getNames({ type: "system" })).to.be.eql(["plugin-1", "plugin-2"]);191 });192 chunk("gets empty list if system plugins are absent", () => {193 plugins.__set__("systemPlugins", null);194 expect(plugins.getNames({ type: "system" })).to.be.eql([]);195 });196 chunk("gets all plugin names", () => {197 plugins.__set__("customPlugins", [{ name: "plugin-1" }]);198 plugins.__set__("systemPlugins", [{ name: "plugin-2" }]);199 expect(plugins.getNames()).to.be.eql(["plugin-1", "plugin-2"]);200 });201 chunk("gets custom plugins names if system plugins are absent", () => {202 plugins.__set__("customPlugins", [{ name: "plugin-1" }, { name: "plugin-2" }]);203 plugins.__set__("systemPlugins", null);204 expect(plugins.getNames()).to.be.eql(["plugin-1", "plugin-2"]);205 });206 });207 test("dirsToSearchPlugins()", () => {208 let dirsToSearchPlugins, require_, u;209 beforeChunk(() => {210 dirsToSearchPlugins = plugins.__get__("dirsToSearchPlugins");211 require_ = {};212 plugins.__set__("require", require_);213 u = { cwd: "/path/to/plugins" };214 plugins.__set__("U", u);215 plugins.__set__("module", { paths: ["/path/to/plugins"]});216 });217 chunk("gets dir to search plugins", () => {218 expect(dirsToSearchPlugins()).to.be.eql(["/path/to/plugins"]);219 });220 chunk("excludes require.main module from search", () => {221 require_.main = { filename: "/path/to/bin/index.js" };222 expect(dirsToSearchPlugins()).to.be.eql(["/path/to/bin", "/path/to/plugins"]);223 });224 chunk("exclude current work directory from search", () => {225 u.cwd = "/path/to/cwd";226 expect(dirsToSearchPlugins()).to.be.eql(["/path/to/cwd", "/path/to/plugins"]);227 });228 chunk("does not inject main dir", () => {229 require_.main = { filename: "/path/to/plugins/index.js" };230 plugins.__set__("module", { paths: ["/path/to/plugins"]});231 expect(dirsToSearchPlugins()).to.be.eql(["/path/to/plugins"]);232 });233 });...

Full Screen

Full Screen

base.py

Source:base.py Github

copy

Full Screen

...11 def __init__(self, name=None, **kw):12 self.name = name13 for k, v in kw.items():14 setattr(self, k, v)15 def __set__(self, instance, value):16 instance.__dict__[self.name] = value17class Typed(Descriptor):18 """Values must of a particular type"""19 expected_type = type(None)20 allow_none = False21 nested = False22 def __init__(self, *args, **kw):23 super(Typed, self).__init__(*args, **kw)24 self.__doc__ = "Values must be of type {0}".format(self.expected_type)25 def __set__(self, instance, value):26 if not isinstance(value, self.expected_type):27 if (not self.allow_none28 or (self.allow_none and value is not None)):29 raise TypeError('expected ' + str(self.expected_type))30 super(Typed, self).__set__(instance, value)31 def __repr__(self):32 return self.__doc__33def _convert(expected_type, value):34 """35 Check value is of or can be converted to expected type.36 """37 if not isinstance(value, expected_type):38 try:39 value = expected_type(value)40 except:41 raise TypeError('expected ' + str(expected_type))42 return value43class Convertible(Typed):44 """Values must be convertible to a particular type"""45 def __set__(self, instance, value):46 if ((self.allow_none and value is not None)47 or not self.allow_none):48 value = _convert(self.expected_type, value)49 super(Convertible, self).__set__(instance, value)50class Max(Convertible):51 """Values must be less than a `max` value"""52 expected_type = float53 allow_none = False54 def __init__(self, **kw):55 if 'max' not in kw and not hasattr(self, 'max'):56 raise TypeError('missing max value')57 super(Max, self).__init__(**kw)58 def __set__(self, instance, value):59 if ((self.allow_none and value is not None)60 or not self.allow_none):61 value = _convert(self.expected_type, value)62 if value > self.max:63 raise ValueError('Max value is {0}'.format(self.max))64 super(Max, self).__set__(instance, value)65class Min(Convertible):66 """Values must be greater than a `min` value"""67 expected_type = float68 allow_none = False69 def __init__(self, **kw):70 if 'min' not in kw and not hasattr(self, 'min'):71 raise TypeError('missing min value')72 super(Min, self).__init__(**kw)73 def __set__(self, instance, value):74 if ((self.allow_none and value is not None)75 or not self.allow_none):76 value = _convert(self.expected_type, value)77 if value < self.min:78 raise ValueError('Min value is {0}'.format(self.min))79 super(Min, self).__set__(instance, value)80class MinMax(Min, Max):81 """Values must be greater than `min` value and less than a `max` one"""82 pass83class Set(Descriptor):84 """Value can only be from a set of know values"""85 def __init__(self, name=None, **kw):86 if not 'values' in kw:87 raise TypeError("missing set of values")88 kw['values'] = set(kw['values'])89 super(Set, self).__init__(name, **kw)90 self.__doc__ = "Value must be one of {0}".format(self.values)91 def __set__(self, instance, value):92 if value not in self.values:93 raise ValueError(self.__doc__)94 super(Set, self).__set__(instance, value)95class NoneSet(Set):96 """'none' will be treated as None"""97 def __init__(self, name=None, **kw):98 super(NoneSet, self).__init__(name, **kw)99 self.values.add(None)100 def __set__(self, instance, value):101 if value == 'none':102 value = None103 super(NoneSet, self).__set__(instance, value)104class Integer(Convertible):105 expected_type = int106class Float(Convertible):107 expected_type = float108class Bool(Convertible):109 expected_type = bool110 def __set__(self, instance, value):111 if isinstance(value, str):112 if value in ('false', 'f', '0'):113 value = False114 super(Bool, self).__set__(instance, value)115class String(Typed):116 expected_type = str117class Text(String, Convertible):118 pass119class ASCII(Typed):120 expected_type = bytes121class Tuple(Typed):122 expected_type = tuple123class Length(Descriptor):124 def __init__(self, name=None, **kw):125 if "length" not in kw:126 raise TypeError("value length must be supplied")127 super(Length, self).__init__(**kw)128 def __set__(self, instance, value):129 if len(value) != self.length:130 raise ValueError("Value must be length {0}".format(self.length))131 super(Length, self).__set__(instance, value)132class Default(Typed):133 """134 When called returns an instance of the expected type.135 Additional default values can be passed in to the descriptor136 """137 def __init__(self, name=None, **kw):138 if "defaults" not in kw:139 kw['defaults'] = {}140 super(Default, self).__init__(**kw)141 def __call__(self):142 return self.expected_type()143class Alias(Descriptor):144 """145 Aliases can be used when either the desired attribute name is not allowed146 or confusing in Python (eg. "type") or a more descriptve name is desired147 (eg. "underline" for "u")148 """149 def __init__(self, alias):150 self.alias = alias151 def __set__(self, instance, value):152 setattr(instance, self.alias, value)153 def __get__(self, instance, cls):154 return getattr(instance, self.alias)155class MatchPattern(Descriptor):156 """Values must match a regex pattern """157 allow_none = False158 def __init__(self, name=None, **kw):159 if 'pattern' not in kw and not hasattr(self, 'pattern'):160 raise TypeError('missing pattern value')161 super(MatchPattern, self).__init__(name, **kw)162 self.test_pattern = re.compile(self.pattern, re.VERBOSE)163 def __set__(self, instance, value):164 if value is None and not self.allow_none:165 raise ValueError("Value must not be none")166 if ((self.allow_none and value is not None)167 or not self.allow_none):168 if not self.test_pattern.match(value):169 raise ValueError('Value does not match pattern {0}'.format(self.pattern))170 super(MatchPattern, self).__set__(instance, value)171class DateTime(Typed):172 expected_type = datetime.datetime173 def __set__(self, instance, value):174 if value is not None and isinstance(value, str):175 try:176 value = from_ISO8601(value)177 except ValueError:178 raise ValueError("Value must be ISO datetime format")...

Full Screen

Full Screen

ex8-13.py

Source:ex8-13.py Github

copy

Full Screen

...4 def __init__(self, name=None, **opts):5 self.name = name6 for key, value in opts.items():7 setattr(self, key, value)8 def __set__(self, instance, value):9 instance.__dict__[self.name] = value10# 타입을 강제하기 위한 디스크립터11class Typed(Descriptor):12 expected_type = type(None)13 def __set__(self, instance, value):14 if not isinstance(value, self.expected_type):15 raise TypeError('expected ' + str(self.expected_type))16 super().__set__(instance, value)17# 값을 강제하기 위한 디스크립터18class Unsigned(Descriptor):19 def __set__(self, instance, value):20 if value < 0:21 raise ValueError('Expected >= 0')22 super().__set__(instance, value)23class MaxSized(Descriptor):24 def __set__(self, name=None, **opts):25 if 'size' not in opts:26 raise TypeError('missing size option')27 super().__init__(name, **opts)28 def __set__(self, instance, value):29 if len(value) >= self.size:30 raise ValueError('size must be < ' + str(self.size))31 super().__set__(instance, value)32class Integer(Typed):33 expected_type = int34class UnsignedInteger(Integer, Unsigned):35 pass36class Float(Typed):37 expected_type = float38class UnsignedFloat(Float, Unsigned):39 pass40class String(Typed):41 expected_type = str42class SizedString(String, MaxSized):43 pass44class Stock:45 # 제약 명시46 name = SizedString('name',size=8)47 shares = UnsignedInteger('shares')48 price = UnsignedFloat('price')49 def __init__(self, name, shares, price):50 self.name = name51 self.shares = shares52 self.price = price53s = Stock('ACME', 50, 91.1)54s.name55# 'ACME'56s.shares = 7557s.shares = -1058# Traceback (most recent call last):59# File "<stdin>", line 1, in <module>60# File "example.py", line 17, in __set__61# super().__set__(instance, value)62# File "example.py", line 23, in __set__63# raise ValueError('Expected >= 0')64# ValueError: Expected >= 065s.price = 'a lot'66# Traceback (most recent call last):67# File "<stdin>", line 1, in <module>68# File "example.py", line 16, in __set__69# raise TypeError('expected ' + str(self.expected_type))70# TypeError: expected <class 'float'>71s.name = 'ABRACADABRA'72# Traceback (most recent call last):73# File "<stdin>", line 1, in <module>74# File "example.py", line 20, in __set__75# super().__set__(instance, value)76# File "example.py", line 37, in __set__77# raise ValueError('size must be < ' + str(self.size))78# ValueError: size must be < 879# 제약을 위한 클래스 데코레이터80def check_attributes(**kwargs):81 def decorate(cls):82 for key, value in kwargs.items():83 if isinstance(value, Descriptor):84 value.name = key85 setattr(cls, key, value)86 else:87 setattr(cls, key, value(key))88 return cls89 return decorate90# 예제91@check_attributes(name=SizedString(size=8),92 shares=UnsignedInteger,93 price=UnsignedFloat)94class Stock:95 def __init__(self, name, shares, price):96 self.name = name97 self.shares = shares98 self.price = price99# 확인을 위한 메타클래스100class checkedmeta(type):101 def __new__(cls, clsname, bases, methods):102 # 디스크립터에 속성 이름 붙이기103 for key, value in methods.items():104 if isinstance(value, Descriptor):105 value.name = key106 return type.__new__(cls, clsname, bases, methods)107# 예제108class Stock(metaclass=checkedmeta):109 name = SizedString(size=8)110 shares = UnsignedInteger()111 price = UnsignedFloat()112 def __init__(self, name, shares, price):113 self.name = name114 self.shares = shares115 self.price = price116# 토론117# 일반118class Point:119 x = Integer('x')120 y = Integer('y')121# 메타클래스122class Point(metaclass=checkedmeta):123 x = Integer()124 y = Integer()125# 베이스 클래스. 값을 설정할 때 디스크립터를 사용126class Descriptor:127 def __init__(self, name=None, **opts):128 self.name = name129 for key, value in opts.items():130 setattr(self, key, value)131 def __set__(self, instance, value):132 instance.__dict__[self.name] = value133# 타입 확인에 데코레이터 사용134def Typed(expected_type, cls=None):135 if cls is None:136 return lambda cls: Typed(expected_type, cls)137 super_set = cls.__set__138 def __set__(self, instance, value):139 if not isinstance(value, expected_type):140 raise TypeError('expected ' + str(expected_type))141 super_set(self, instance, value)142 cls.__set__ = __set__143 return cls144# 언사인드(unsigned) 값에 데코레이터 사용145def Unsigned(cls):146 super_set = cls.__set__147 def __set__(self, instance, value):148 if value < 0:149 raise ValueError('Expected >= 0')150 super_set(self, instance, value)151 cls.__set__ = __set__152 return cls153# 크기 있는 값에 데코레이터 사용154def MaxSized(cls):155 super_init = cls.__init__156 def __init__(self, name=None, **opts):157 if 'size' not in opts:158 raise TypeError('missing size option')159 super_init(self, name, **opts)160 cls.__init__ = __init__161 super_set = cls.__set__162 def __set__(self, instance, value):163 if len(value) >= self.size:164 raise ValueError('size must be < ' + str(self.size))165 super_set(self, instance, value)166 cls.__set__ = __set__167 return cls168# 특별 디스크립터169@Typed(int)170class Integer(Descriptor):171 pass172@Unsigned173class UnsignedInteger(Integer):174 pass175@Typed(float)176class Float(Descriptor):...

Full Screen

Full Screen

p13_implementing_data_model_or_type_system.py

Source:p13_implementing_data_model_or_type_system.py Github

copy

Full Screen

...11 def __init__(self, name=None, **opts):12 self.name = name13 for key, value in opts.items():14 setattr(self, key, value)15 def __set__(self, instance, value):16 instance.__dict__[self.name] = value17# Descriptor for enforcing types18class Typed(Descriptor):19 expected_type = type(None)20 def __set__(self, instance, value):21 if not isinstance(value, self.expected_type):22 raise TypeError('expected ' + str(self.expected_type))23 super().__set__(instance, value)24# Descriptor for enforcing values25class Unsigned(Descriptor):26 def __set__(self, instance, value):27 if value < 0:28 raise ValueError('Expected >= 0')29 super().__set__(instance, value)30class MaxSized(Descriptor):31 def __init__(self, name=None, **opts):32 if 'size' not in opts:33 raise TypeError('missing size option')34 super().__init__(name, **opts)35 def __set__(self, instance, value):36 if len(value) >= self.size:37 raise ValueError('size must be < ' + str(self.size))38 super().__set__(instance, value)39# 实际定义的各种数据类型,继承上面的基类40class Integer(Typed):41 expected_type = int42class UnsignedInteger(Integer, Unsigned):43 pass44class Float(Typed):45 expected_type = float46class UnsignedFloat(Float, Unsigned):47 pass48class String(Typed):49 expected_type = str50class SizedString(String, MaxSized):51 pass52# 使用自定义的数据类型53class Stock:54 # Specify constraints55 name = SizedString('name', size=8)56 shares = UnsignedInteger('shares')57 price = UnsignedFloat('price')58 def __init__(self, name, shares, price):59 self.name = name60 self.shares = shares61 self.price = price62s = Stock('book', 20, 12.0)63# s.name = 'abcdefgh' # ValueError: size must be < 864# s.shares = -10 # ValueError: Expected >= 065# s.price = 'many' # TypeError: expected <class 'float'>66print()67# 使用类装饰器简化上面的代码68def check_attributes(**kwargs):69 def decorate(cls):70 for key, value in kwargs.items():71 if isinstance(value, Descriptor):72 value.name = key73 setattr(cls, key, value)74 else:75 setattr(cls, key, value(key))76 return cls77 return decorate78@check_attributes(name=SizedString(size=8),79 shares=UnsignedInteger,80 price=UnsignedFloat)81class Stock:82 def __init__(self, name, shares, price):83 self.name = name84 self.shares = shares85 self.price = price86s = Stock('book', 20, 12.0)87# s.name = 'abcdefgh' # ValueError: size must be < 888print()89# 使用元类简化上面的代码90class checkedmeta(type):91 def __new__(cls, clsname, bases, methods):92 for key, value in methods.items():93 if isinstance(value, Descriptor):94 value.name = key95 return type.__new__(cls, clsname, bases, methods)96class Stock2(metaclass=checkedmeta):97 name = SizedString(size=8)98 shares = UnsignedInteger()99 price = UnsignedFloat()100 def __init__(self, name, shares, price):101 self.name = name102 self.shares = shares103 self.price = price104s = Stock('book', 20, 12.0)105# s.name = 'abcdefgh' # ValueError: size must be < 8106print()107# 装饰器可以替代混入类,执行速度会比混入类的方式快108def Typed(excepted_type, cls=None):109 if cls is None:110 return lambda cls: Typed(excepted_type, cls)111 super_set = cls.__set__112 def __set__(self, instance, value):113 if not isinstance(value, excepted_type):114 raise TypeError('excepted ' + str(excepted_type))115 super_set(self, instance, value)116 cls.__set__ = __set__117 return cls118def Unsigned(cls):119 super_set = cls.__set__120 def __set__(self, instance, value):121 if value < 0:122 raise ValueError('Excepted >= 0')123 super_set(self, instance, value)124 cls.__set__ = __set__125 return cls126def MaxSized(cls):127 super_init = cls.__init__128 def __init__(self, name=None, **opts):129 if 'size' not in opts:130 raise TypeError('missing size option')131 super_init(self, name, **opts)132 cls.__init__ = __init__133 super_set = cls.__set__134 def __set__(self, instance, value):135 if len(value) >= self.size:136 raise ValueError('size must be < ' + str(self.size))137 super_set(self, instance, value)138 cls.__set__ = __set__139 return cls140@Typed(int)141class Integer(Descriptor):142 pass143@Unsigned144class UnsignedInteger(Integer):145 pass146@Typed(float)147class Float(Descriptor):148 pass...

Full Screen

Full Screen

field_type_check_with_decorator.py

Source:field_type_check_with_decorator.py Github

copy

Full Screen

...11 def __init__(self, name=None, **opt):12 self.name = name13 for k, v in opt.items():14 setattr(self, k, v)15 def __set__(self, instance, value):16 instance.__dict__[self.name] = value17def typed(expected_type):18 def wrapper(cls):19 super_set = cls.__set__20 def __set__(self, instance, value):21 if not isinstance(value, expected_type):22 raise TypeError('expected ' + str(expected_type))23 super_set(self, instance, value)24 cls.__set__ = __set__25 return cls26 return wrapper27def unsigned(cls):28 super_set = cls.__set__29 def __set__(self, ins, value):30 if value < 0:31 raise ValueError('Expected >= 0')32 super_set(self, ins, value)33 cls.__set__ = __set__34 return cls35def max_size(cls):36 super_init = cls.__init__37 super_set = cls.__set__38 def __init__(self, name=None, **opts):39 if 'size' not in opts:40 raise TypeError('missing size option')41 super_init(self, name, **opts)42 def __set__(self, ins, value):43 if len(value) >= self.size:44 raise ValueError('size must be < ' + str(self.size))45 super_set(self, ins, value)46 cls.__init__ = __init__47 cls.__set__ = __set__48 return cls49@typed(int)50class Integer(Base): pass51@unsigned52class UnsignedInteger(Integer): pass53@typed(float)54class Float(Base): pass55@unsigned56class UnsignedFloat(Float): pass...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var app = require('../src/app');2var rewire = require('rewire');3var app = rewire('../src/app');4var __set__ = app.__set__;5var app = require('express')();6var rewire = require('rewire');7var app = rewire('express')();8var __get__ = app.__get__;9var myModule = require('../src/myModule');10var rewire = require('rewire');11var myModule = rewire('../src/myModule');12var __get__ = myModule.__get__;13var myModule = require('../src/myModule');14var rewire = require('rewire');15var myModule = rewire('../src/myModule');16var __get__ = myModule.__get__;17var myModule = require('../src/myModule');18var rewire = require('rewire');19var myModule = rewire('../src/myModule');20var __get__ = myModule.__get__;21var myModule = require('../src/myModule');22var rewire = require('rewire');23var myModule = rewire('../src/myModule');24var __get__ = myModule.__get__;25var myModule = require('../src/myModule');26var rewire = require('rewire');27var myModule = rewire('../src/myModule');28var __get__ = myModule.__get__;29var myModule = require('../src/myModule');30var rewire = require('rewire');31var myModule = rewire('../src/myModule');32var __get__ = myModule.__get__;33var myModule = require('../src/myModule');34var rewire = require('rewire');35var myModule = rewire('../src/myModule');36var __get__ = myModule.__get__;37var myModule = require('../src/myModule');38var rewire = require('rewire');39var myModule = rewire('../src/myModule');40var __get__ = myModule.__get__;41var myModule = require('../src/myModule');42var rewire = require('rewire');43var myModule = rewire('../src/myModule');44var __get__ = myModule.__get__;45var myModule = require('../src/myModule');46var rewire = require('rewire');47var myModule = rewire('../src/myModule');

Full Screen

Using AI Code Generation

copy

Full Screen

1var rewire = require("rewire");2var test = rewire("./test.js");3test.__set__({4});5var rewire = require("rewire");6var test = rewire("./test.js");7var url = test.__get__('url');8var rewire = require("rewire");9var test = rewire("./test.js");10test.__with__({11})(function() {12});13var rewire = require("rewire");14var test = rewire("./test.js");15var url = test.__get__('url');16var rewire = require("rewire");17var test = rewire("./test.js");18test.__set__({19});20var rewire = require("rewire");21var test = rewire("./test.js");22var url = test.__get__('url');23var rewire = require("rewire");24var test = rewire("./test.js");25test.__with__({26})(function() {27});28var rewire = require("rewire");29var test = rewire("./test.js");30var url = test.__get__('url');31var rewire = require("rewire");32var test = rewire("./test.js");33test.__set__({34});35var rewire = require("rewire");36var test = rewire("./test.js

Full Screen

Using AI Code Generation

copy

Full Screen

1var rewire = require("rewire");2var myModule = rewire("./myModule.js");3myModule.__set__("myMethod", function() {4 console.log("myMethod has been mocked");5});6myModule.someMethod();7exports.someMethod = function() {8 myMethod();9};10function myMethod() {11 console.log("myMethod has been called");12}

Full Screen

Using AI Code Generation

copy

Full Screen

1var rewire = require('rewire');2var test = rewire('./test.js');3var testModule = test.__get__('testModule');4testModule.__set__('test', function() {5 return 'test';6});7var rewire = require('rewire');8var test = rewire('./test.js');9var testModule = test.__get__('testModule');10testModule.__set__('test', function() {11 return 'test';12});13var rewire = require('rewire');14var test = rewire('./test.js');15var testModule = test.__get__('testModule');16testModule.__set__('test', function() {17 return 'test';18});19var rewire = require('rewire');20var test = rewire('./test.js');21var testModule = test.__get__('testModule');22testModule.__set__('test', function() {23 return 'test';24});25var rewire = require('rewire');26var test = rewire('./test.js');27var testModule = test.__get__('testModule');28testModule.__set__('test', function() {29 return 'test';30});31var rewire = require('rewire');32var test = rewire('./test.js');33var testModule = test.__get__('testModule');34testModule.__set__('test', function() {35 return 'test';36});37var rewire = require('rewire');38var test = rewire('./test.js');39var testModule = test.__get__('testModule');40testModule.__set__('test', function() {41 return 'test';42});

Full Screen

Using AI Code Generation

copy

Full Screen

1var rewire = require('rewire');2var test = rewire('./test.js');3test.__set__('name', 'test');4console.log(test.name);5var name = 'test';6module.exports = {7};8var rewire = require('rewire');9var test = rewire('./test.js');10test.__set__('name', 'test');11console.log(test.name);12var name = 'test';13module.exports = {14};15var rewire = require('rewire');16var test = rewire('./test.js');17test.__set__('name', 'test');18console.log(test.name);19var name = 'test';20module.exports = {21};22var rewire = require('rewire');23var test = rewire('./test.js');24test.__set__('name', 'test');25console.log(test.name);26var name = 'test';27module.exports = {28};29var rewire = require('rewire');30var test = rewire('./test.js');31test.__set__('name', 'test');32console.log(test.name);33var name = 'test';34module.exports = {35};36var rewire = require('rewire');37var test = rewire('./test.js');38test.__set__('name', 'test');39console.log(test.name);40var name = 'test';41module.exports = {42};43var rewire = require('rewire');44var test = rewire('./test.js');45test.__set__('name', 'test');46console.log(test.name);

Full Screen

Using AI Code Generation

copy

Full Screen

1var rewire = require('rewire');2var test = rewire('./test.js');3test.__set__('privateVariable', 'new value');4var rewire = require('rewire');5var test = rewire('./test.js');6var rewire = require('rewire');7var test = rewire('./test.js');8test.__with__({9})(function() {10});11var rewire = require('rewire');12var test = rewire('./test.js');13test.__with__({14})(function() {15});16var rewire = require('rewire');17var test = rewire('./test.js');18test.__set__('privateVariable', 'new value');19var rewire = require('rewire');20var test = rewire('./test.js');21var rewire = require('rewire');22var test = rewire('./test.js');23test.__with__({24})(function() {25});26var rewire = require('rewire');27var test = rewire('./test.js');

Full Screen

Using AI Code Generation

copy

Full Screen

1var rewire = require('rewire');2var mock = rewire('../index.js');3mock.__set__('fs', {4 readFileSync: function() {5 return 'test text';6 }7});8var result = mock.readFile();9console.log(result);10var fs = require('fs');11module.exports = {12 readFile: function() {13 return fs.readFileSync('test.txt', 'utf8');14 }15};

Full Screen

Using AI Code Generation

copy

Full Screen

1var rewire = require("rewire");2var test = rewire("./test.js");3test.__set__("myModule", { get: function() { return "mocked"; } });4test.myTest();5var myModule = require("./myModule");6exports.myTest = function() {7 console.log(myModule.get());8};

Full Screen

Using AI Code Generation

copy

Full Screen

1var __rewire__ = require('rewire');2var __set__ = __rewire__.__set__;3var codeToTest = __rewire__('codeToTest.js');4__set__("test", "test");5codeToTest.testVariable();6var test = require('test.js');7exports.testVariable = function() {8 console.log(test);9}

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run rewire automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful