Best Python code snippet using slash
tests.ts
Source:tests.ts  
1/// <reference types="mocha" />23require("source-map-support/register");45import weak = require("weak-napi");6import assert = require("assert");7import async = require("async");8import path = require("path");9import util = require("util");10import fs = require("fs");1112const isWeakRef = function(val) {13  try {14    return weak.isWeakRef(val);15  } catch(e) {}16  17  return false;18}1920import LRU = require("../index");2122const gccache = new LRU;23const onemb = new Int8Array(1000000);24const datadir = path.resolve(__dirname, "data");25it("large items", function() {26  gccache.set("1mb", onemb); // 1mb27  gccache.set("5mb", new Int8Array(5000000)); // 5mb28  gccache.set("25mb", new Int8Array(25000000)); // 25mb29  assert.equal(gccache.get("1mb"), onemb);30});31it("capacity", function () {32  const refs = [];33  const cache = new LRU({capacity:5});34  for(var i=0; i<10; i++) {35    const obj = new Object;36    cache.set("item" + i, obj);37    refs.push(obj);38  }39  assert.equal(cache.size, 5);40});41it("timeout", function (cb) {42  const refs = [];43  const cache = new LRU({maxAge:500});44  for(var i=0; i<10; i++) {45    const obj = new Object;46    cache.set("item" + i, obj);47    refs.push(obj);48  }49  assert.equal(cache.size, 10);50  setTimeout(function() {51    assert.equal(cache.size, 0);52    cb();53  }, 550);54});55const generate_tests = [56  ["a", "a", "b", "b", "c", "c", "d", "d", "a", "b", "c", "d"],57  [["a", "b", "c", "d"], "a", "b", "c", "d"],58  ["a", "b", "c", "d", ["a", "b", "c", "d"], "b", "c"],59  ["e", "f", "a", "e", "f"],60  ["g", "h", ["i", "j", "g"], ["k", "l", "m", "e", "f"]],61  [["k", "l", "m", "e", "f"]]62];63const realdata = {64  a: Buffer.from("Sudo\r\n"),65  b: Buffer.from("Su\r\n"),66  c: Buffer.from("Cow\r\n"),67  d: Buffer.from("Bash\r\n")68};69const fslookup = function(key: string, callback: (err?: Error, ret?: Buffer) => void) {70  // console.log("fslookup", key);71  fs.readFile(path.resolve(datadir, key), function(err, data) {72    callback(key > "f" ? err : undefined, data);73  });74}75const fsmulti = function(keys: string[], callback: (err: Error, ret?: {[key: string]: Buffer}) => void) {76  const ret = {};77  async.each(keys, function(key, cb) {78      fslookup(key, function(err, _ret) {79        if(key > "f")80          return cb(err);81        else82          ret[key] = _ret;83        cb();84      });85  }, function(err) {86    callback(err, ret);87  });88}89const doGenerateTests = function(tests: (string[] | string)[][], errorAfter: number, series = false, setInterval?: number, offset = 0) {90  var a = 1;91  tests.forEach(function(test) {92    const i = a ++;93    const captured = {};94    const cache = new LRU<Buffer>({});95    const dotest = function (cb) {96      var setCount = 0;97      var errored: boolean;98      const expectError = i > errorAfter;99      const verify = function(p: string, dat) {100        const cap = captured[p];101        assert.equal(isWeakRef(dat), false, "weak reference snuck through...");102        if(dat) {103          if (cap && dat !== cap)104            console.warn(p + " did not === previously resolved value");105          captured[p] = dat;106        }107        assert.deepEqual(dat, realdata[p], p + " did not match real data, " + util.inspect(dat) + " !== " + util.inspect(realdata[p]));108      };109      (series ? async.eachSeries : async.each)(test, function(part, cb) {110        var returned: string;111        if(Array.isArray(part)) {112          // console.log("generating", part);113          cache.generateMulti(part, fsmulti, function(err, data) {114            // console.log("generated", part);115            if(returned) {116              console.warn(returned);117              throw new Error("Already returned data");118            }119            returned = (new Error).stack.replace(/^Error\n/m, "");120121            if(expectError && err) {122              errored = true;123              cb();124              return;125            }126127            if(err)128              cb(err);129            else {130              part.forEach(function(p) {131                verify(p, data[p]);132              });133              cb();134            }135          });136          if (setInterval && !((setCount++ + offset) % setInterval))137            part.forEach(function(p) {138              const val = realdata[p];139              if (val)140                cache.set(p, captured[p] = val);141            });142        } else {143          // console.log("generating", part);144          cache.generate(part, fslookup, function(err, data) {145            // console.log("generated", part);146            if(returned) {147              console.warn(returned);148              throw new Error("Already returned data");149            }150            returned = (new Error).stack.replace(/^Error\n/m, "");151152            if(expectError && err) {153              errored = true;154              cb();155              return;156            }157158            if(err)159              cb(err);160            else {161              verify(part, data);162              cb();163            }164          });165          if (setInterval && !((setCount++ + offset) % setInterval)) {166            const val = realdata[part];167            if (val)168              cache.set(part, captured[part] = val);169          }170        }171      }, function(err?: Error) {172        if(err)173          cb(err);174        else {175          if(expectError && !errored)176            cb(new Error("Expected error past iteration " + errorAfter));177          else178            cb();179        }180      });181    };182    it("generate test #" + i, dotest);183    it("generate test #" + i + " redo", dotest);184    it("generate test #" + i + " preset", function(cb) {185      cache.clear();186      Object.keys(realdata).forEach(function(key) {187        cache.set(key, captured[key] = realdata[key]);188      });189      dotest(cb);190    });191    it("generate test #" + i + " redo again", dotest);192  });193}194const generate_tests_kinda_compact = [];195for(var i=0; i<generate_tests.length; i+= 2) {196  const compact = [];197  compact.push.apply(compact, generate_tests[i]);198  compact.push.apply(compact, generate_tests[i+1]);199  generate_tests_kinda_compact.push(compact);200}201const generate_tests_more_compact = [];202for(var i=0; i<generate_tests.length; i+=3) {203  const compact = [];204  compact.push.apply(compact, generate_tests[i]);205  compact.push.apply(compact, generate_tests[i+1]);206  compact.push.apply(compact, generate_tests[i+2]);207  generate_tests_more_compact.push(compact);208}209[0, 5, 3, 1].forEach(function(interval) {210  describe("Generate Tests, Interval " + interval, function() {211    [0, 2, 4, 6].forEach(function(offset) {212      describe("Series, Offset " + offset, function() {213        doGenerateTests(generate_tests, 4, true, interval, offset);214      });215      describe("Parallel, Offset " + offset, function() {216        doGenerateTests(generate_tests, 4, false, interval, offset);217      });218      describe("Kinda Compact, Series, Offset " + offset, function() {219        doGenerateTests(generate_tests_kinda_compact, 2, true, interval, offset);220      });221      describe("Kinda Compact, Parallel, Offset " + offset, function() {222        doGenerateTests(generate_tests_kinda_compact, 2, false, interval, offset);223      });224      describe("More Compact, Series, Offset " + offset, function() {225        doGenerateTests(generate_tests_more_compact, 1, true, interval, offset);226      });227      describe("More Compact, Parallel, Offset " + offset, function() {228        doGenerateTests(generate_tests_more_compact, 1, false, interval, offset);229      });230    });231  });232});233describe("Final Generator Tests", function() {234  const cache = new LRU<Buffer>();235  const err = new Error("Toasted Wheats");236  const _a = Buffer.from("Mixture");237  const _b = Buffer.from("Farmers");238  it("generate cancel error", function(cb) {239    cache.generate("a", fslookup, function(_err, data) {240      assert.equal(_err, err);241      cb();242    })(err);243  });244  it("generateMulti cancel error", function(cb) {245    cache.generateMulti(["a", "b", "c", "d"], fsmulti, function(_err, data) {246      assert.equal(_err, err);247      cb();248    })(err);249  });250  it("generateMulti cancel", function(cb) {251    const data = {a:_a,b:_b,e:Buffer.from("Ignored")};252    cache.generateMulti(["a", "b", "c", "d"], fsmulti, function(err, _data) {253      assert.deepEqual(_data, data);254      cb(err);255    })(data);256  });257  it("generate to generateMulti cancel error", function(cb) {258    cache.clear();259    var total = 3;260    cache.generate("a", fslookup, function(_err) {261      assert.equal(_err, err);262      if (!--total)263        cb();264    });265    cache.generate("b", fslookup, function(_err) {266      assert.equal(_err, err);267      if (!--total)268        cb();269    });270    cache.generateMulti(["a", "b", "c", "d"], fsmulti, function(_err) {271      assert.equal(_err, err);272      if (!--total)273        cb();274    })(err);275  });276  it("generate to generateMulti cancel", function(cb) {277    var total = 3;278    const a = cache.generate("a", fslookup, function(err, data) {279      if (err)280        cb(err);281      else {282        assert.strictEqual(data, _a);283        if (!--total)284          cb();285      }286    });287    const b = cache.generate("b", fslookup, function(err, data) {288      if (err)289        cb(err);290      else {291        assert.strictEqual(data, _b);292        if (!--total)293          cb();294      }295    });296    const data = {a:_a,b:_b};297    cache.generateMulti(["a", "b", "c", "d"], fsmulti, function(err, _data) {298      if (err)299        cb(err);300      else {301        assert.deepEqual(_data, data);302        if (!--total)303          cb();304      }305    })(data)306  });307  it("generateMulti set", function(cb) {308    cache.clear();309    const empty = new Buffer(0);310    const data = {a:_a,b:_b,c:empty,d:empty};311    cache.generateMulti(["a", "b", "c", "d"], fsmulti, function(err, data) {312      assert.deepEqual(data, data);313      cb(err);314    });315    cache.set("a", _a);316    cache.set("b", _b);317    cache.set("c", empty);318    cache.set("d", empty);319  });320  it("generateMulti generate error", function(cb) {321    cache.clear();322    var total = 2;323    cache.generateMulti(["a", "b", "c", "d"], fsmulti, function(_err, data) {324      assert.equal(_err, err);325      if (!--total)326        cb();327    });328    cache.generate("a", fslookup, function(_err, data) {329      assert.equal(_err, err);330      if (!--total)331        cb();332    })(err);333  });334  it("generate generateMulti cancel error", function(cb) {335    cache.clear();336    var total = 3;337    cache.generate("a", fslookup, function(_err, data) {338      assert.equal(_err, err);339      if (!--total)340        cb();341    });342    cache.generate("b", fslookup, function(_err, data) {343      assert.equal(_err, err);344      if (!--total)345        cb();346    });347    cache.generateMulti(["a", "b"], fsmulti, function(_err, data) {348      assert.equal(_err, err);349      if (!--total)350        cb();351    })(err);352  });353});354describe("Final Stuff", function() {355  it("iterators", function() {356    const val = new Object;357    const cache = new LRU;358    cache.set("item", val);359    cache.forEach(function(v, key) {360      assert.equal(v, val);361      assert.equal(key, "item");362    });363    const vit = cache.values();364    assert.equal(vit.next().value, val);365    assert.equal(vit.next().done, true);366    const eit = cache.entries();367    assert.equal(eit.next().value[1], val);368    assert.equal(eit.next().done, true);369  });370  it("lifetime", function(cb) {371    const refs = [];372    const cache = new LRU({maxAge:500,minAge:400,resetTimersOnAccess:true});373    for(var i=0; i<10; i++) {374      const obj = new Int8Array(100000);375      cache.set("item" + i, obj);376      refs.push(obj);377    }378    assert.equal(cache.size, 10);379    setTimeout(function() {380      assert.equal(cache.size, 10);381    }, 350);382    assert.equal(cache.size, 10);383    setTimeout(function() {384      for(var i=0; i<10; i++) {385        cache.get("item" + i);386      }387      setTimeout(function() {388        assert.equal(cache.size, 10);389      }, 200);390      setTimeout(function() {391        assert.equal(cache.size, 0);392        cb();393      }, 550);394    }, 450);395  });396  // Test if 25mb weak item was gc'd397  it("gc", function(cb) {398    assert.equal(gccache.get("1mb"), onemb);399    if(gccache.size < 3)400      cb();401    else402      setTimeout(function() {403        if(gccache.size >= 3)404          console.warn("31mb of data was not cleared during this run, weak references may not be working");405        cb();406      }, 1900);407  })
...tests.js
Source:tests.js  
1/*2 * 	BSD 3-Clause License3 *4 * Copyright (c) 2019, NTT Ltd.5 * All rights reserved.6 *7 * Redistribution and use in source and binary forms, with or without8 * modification, are permitted provided that the following conditions are met:9 *10 *  Redistributions of source code must retain the above copyright notice, this11 *   list of conditions and the following disclaimer.12 *13 *  Redistributions in binary form must reproduce the above copyright notice,14 *   this list of conditions and the following disclaimer in the documentation15 *   and/or other materials provided with the distribution.16 *17 *  Neither the name of the copyright holder nor the names of its18 *   contributors may be used to endorse or promote products derived from19 *   this software without specific prior written permission.20 *21 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE24 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR27 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER28 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE30 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.31 */3233const chai = require("chai");34const fs = require("fs");35const yaml = require("js-yaml");36const chaiSubset = require('chai-subset');37const generatePrefixes = require('../../src/generatePrefixesList');38const expect = chai.expect;39const asyncTimeout = 120000;40chai.use(chaiSubset);4142global.EXTERNAL_CONFIG_FILE = "tests/generate_tests/config.test.yml";4344describe("Prefix List", function() {4546    it("generate file - default group - exclude 1 prefix", function (done) {47        const asns = ["3333"];48        const outputFile = "tests/generate_tests/prefixes.yml";49        const originalFile = "tests/generate_tests/prefixes.final.default.yml";5051        const inputParameters = {52            asnList: asns,53            outputFile,54            exclude: ["2001:67c:2e8::/48"],55            excludeDelegated: true,56            prefixes: null,57            monitoredASes: asns,58            httpProxy: null,59            debug: false,60            historical: true,61            group: null,62            append: false,63            logger: () => {}64        }65        generatePrefixes(inputParameters)66            .then(content => {67                fs.writeFileSync(outputFile, yaml.dump(content));68            })69            .then(() => {70                const result = fs.readFileSync(outputFile, 'utf8');71                fs.unlinkSync(outputFile);72                const original = fs.readFileSync(originalFile, 'utf8');73                const resultJson = yaml.load(result) || {};74                const originalJson = yaml.load(original) || {};7576                expect(resultJson).to.contain.keys(Object.keys(originalJson));77                expect(Object.keys(resultJson).length).to.equal(Object.keys(originalJson).length);7879                expect(resultJson).to.containSubset(originalJson);80                done();81            });82    }).timeout(asyncTimeout);8384    it("generate file - specific group - no exclude", function (done) {85        const asns = ["3333"];86        const outputFile = "tests/generate_tests/prefixes.yml";87        const originalFile = "tests/generate_tests/prefixes.final.group.yml";8889        const inputParameters = {90            asnList: asns,91            outputFile,92            exclude: [],93            excludeDelegated: true,94            prefixes: null,95            monitoredASes: asns,96            httpProxy: null,97            debug: false,98            historical: true,99            group: "test",100            append: false,101            logger: () => {}102        }103104        generatePrefixes(inputParameters)105            .then(content => {106                fs.writeFileSync(outputFile, yaml.dump(content));107            })108            .then(() => {109                const result = fs.readFileSync(outputFile, 'utf8');110                fs.unlinkSync(outputFile);111                const original = fs.readFileSync(originalFile, 'utf8');112                const resultJson = yaml.load(result) || {};113                const originalJson = yaml.load(original) || {};114115                expect(resultJson).to.contain.keys(Object.keys(originalJson));116                expect(Object.keys(resultJson).length).to.equal(Object.keys(originalJson).length);117118                expect(resultJson).to.containSubset(originalJson);119                done();120            });121    }).timeout(asyncTimeout);122123    it("generate file - append - no exclude", function (done) {124        const asns = ["3333"];125        const outputFile = "tests/generate_tests/prefixes.yml";126        const initialFile = "tests/generate_tests/prefixes.initial.append.yml";127        fs.copyFileSync(initialFile, outputFile);128        const originalFile = "tests/generate_tests/prefixes.final.append.yml";129130        const inputParameters = {131            asnList: asns,132            outputFile,133            exclude: [],134            excludeDelegated: true,135            prefixes: null,136            monitoredASes: asns,137            httpProxy: null,138            debug: false,139            historical: true,140            group: "test",141            append: true,142            logger: () => {},143            getCurrentPrefixesList: () => {144                const content = yaml.load(fs.readFileSync(outputFile, "utf8"));145                return Promise.resolve(content);146            }147        }148149        generatePrefixes(inputParameters)150            .then(content => {151                fs.writeFileSync(outputFile, yaml.dump(content));152            })153            .then(() => {154                const result = fs.readFileSync(outputFile, 'utf8');155                fs.unlinkSync(outputFile);156                const original = fs.readFileSync(originalFile, 'utf8');157                const resultJson = yaml.load(result) || {};158                const originalJson = yaml.load(original) || {};159160                expect(resultJson).to.contain.keys(Object.keys(originalJson));161                expect(Object.keys(resultJson).length).to.equal(Object.keys(originalJson).length);162163                expect(resultJson).to.containSubset(originalJson);164                done();165            });166    }).timeout(asyncTimeout);
...test_verify.py
Source:test_verify.py  
...13F3 = b"A\nB\n\xfc"14F4 = b"A\r\nB\nC"15MULTILINE_MATCH = b".*"16TestFile = collections.namedtuple('TestFile', 'value path')17def generate_tests(multiline=False):18    files = []19    for b, ext in [(F1, '.txt'), (F2, '.txt'), (F3, '.pdf'), (F4, '.txt'), (MULTILINE_MATCH, '.txt')]:20        fd, path = tempfile.mkstemp(suffix=ext)21        with os.fdopen(fd, 'wb') as out:22            out.write(b)23        files.append(TestFile(b, path))24    f1, f2, f3, f4, multiline_match = files25    if multiline:26        tests = [(multiline_match, f1, {'lines_diff': 0, 'sort': True}, None)]27    else:28        tests = [(f1, f1, {'lines_diff': 0, 'sort': True}, None)]29    tests.extend([30        (f1, f2, {'lines_diff': 0, 'sort': True}, AssertionError),31        (f1, f3, None, AssertionError),32        (f1, f4, None, None),33    ])34    return tests35@pytest.mark.parametrize('file1,file2,attributes,expect', generate_tests())36def test_files_contains(file1, file2, attributes, expect):37    if expect is not None:38        with pytest.raises(expect):39            files_contains(file1.path, file2.path, attributes)40    else:41        files_contains(file2.path, file2.path, attributes)42@pytest.mark.parametrize('file1,file2,attributes,expect', generate_tests())43def test_files_diff(file1, file2, attributes, expect):44    if expect is not None:45        with pytest.raises(expect):46            files_diff(file1.path, file2.path, attributes)47    else:48        files_diff(file1.path, file2.path, attributes)49@pytest.mark.parametrize('file1,file2,attributes,expect', generate_tests())50def test_files_re_match(file1, file2, attributes, expect):51    if expect is not None:52        with pytest.raises(expect):53            files_re_match(file1.path, file2.path, attributes)54    else:55        files_re_match(file1.path, file2.path, attributes)56@pytest.mark.parametrize('file1,file2,attributes,expect', generate_tests(multiline=True))57def test_files_re_match_multiline(file1, file2, attributes, expect):58    if expect is not None:59        with pytest.raises(expect):60            files_re_match_multiline(file1.path, file2.path, attributes)61    else:...app.py
Source:app.py  
...6    args.append(arg)7if "python" in args:8    python_code_generator = CodeGenerator("python")9    if "tests" in args:10        print python_code_generator.generate_tests()11    if "usage" in args:12        print python_code_generator.generate_docs()13    if "examples" in args:14        python_code_generator.generate_examples()15if "php" in args:16    php_code_generator = CodeGenerator("php")17    if "tests" in args:18        print php_code_generator.generate_tests()19    if "usage" in args:20        print php_code_generator.generate_docs()21    if "examples" in args:22        php_code_generator.generate_examples()23if "ruby" in args:24    ruby_code_generator = CodeGenerator("ruby")25    if "tests" in args:26        print ruby_code_generator.generate_tests()27    if "usage" in args:28        print ruby_code_generator.generate_docs()29    if "examples" in args:30        ruby_code_generator.generate_examples()31if "java" in args:32    java_code_generator = CodeGenerator("java")33    if "tests" in args:34        print java_code_generator.generate_tests()35    if "usage" in args:36        print java_code_generator.generate_docs()37    if "examples" in args:38        java_code_generator.generate_examples()39if "nodejs" in args:40    nodejs_code_generator = CodeGenerator("nodejs")41    if "tests" in args:42        print nodejs_code_generator.generate_tests()43    if "usage" in args:44        print nodejs_code_generator.generate_docs()45    if "examples" in args:46        nodejs_code_generator.generate_examples()47if "csharp" in args:48    csharp_code_generator = CodeGenerator("csharp")49    if "tests" in args:50        print csharp_code_generator.generate_tests()51    if "usage" in args:52        print csharp_code_generator.generate_docs()53    if "examples" in args:54        csharp_code_generator.generate_examples()55if "go" in args:56    go_code_generator = CodeGenerator("go")57    if "tests" in args:58        print go_code_generator.generate_tests()59    if "usage" in args:60        print go_code_generator.generate_docs()61    if "examples" in args:...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
