Best Python code snippet using green
runtestlist.py
Source:runtestlist.py  
1#!/usr/bin/env python2# This Source Code Form is subject to the terms of the Mozilla Public3# License, v. 2.0. If a copy of the MPL was not distributed with this4# file, You can obtain one at http://mozilla.org/MPL/2.0/.5import glob6import optparse7import sys8import os9import subprocess10import logging11SCRIPT_DIRECTORY = os.path.abspath(os.path.realpath(os.path.dirname(sys.argv[0])))12class RunTestListOptions(optparse.OptionParser):13    """Parsed run test list command line options."""14    def __init__(self, **kwargs):15        optparse.OptionParser.__init__(self, **kwargs)16        defaults = {}17        self.add_option("--binary",18                        action="store", type="string", dest="binary",19                        help="Binary to be run")20        defaults["binary"] = ""21        self.add_option("--list",22                        action="store", type="string", dest="list",23                        help="List of tests to be run")24        defaults["list"] = ""25        self.add_option("--dir",26                        action="store", type="string", dest="dir",27                        help="Directory of the tests, leave blank for current directory")28        defaults["dir"] = ""29        self.add_option("--symbols-path",30                        action="store", type="string", dest="symbols",31                        help="The path to the symbol files from build_symbols")32        defaults["symbols"] = ""33        self.add_option("--total-chunks",34                        action="store", type="int", dest="total_chunks",35                        help="how many chunks to split the tests up into")36        defaults["total_chunks"] = 137        self.add_option("--this-chunk",38                        action="store", type="int", dest="this_chunk",39                        help="which chunk to run between 1 and --total-chunks")40        defaults["this_chunk"] = 141        self.add_option("--plugins-path",42                        action="store", type="string", dest="plugins",43                        help="The path to the plugins folder for the test profiles")44        self.add_option("--testing-modules-dir",45                        action="store", type="string", dest="testingmodules",46                        help="The path to the testing modules directory")47        defaults["testingmodules"] = ""48        self.set_defaults(**defaults)49        usage = """\50Usage instructions for runtestlist.py51"""52        self.set_usage(usage)53log = logging.getLogger()54handler = logging.StreamHandler(sys.stdout)55log.setLevel(logging.INFO)56log.addHandler(handler)57parser = RunTestListOptions()58options, args = parser.parse_args()59if options.binary == "" or options.list == "":60    parser.print_help()61    sys.exit(1)62totalTestErrors = 063totalTestPasses = 064totalDirectories = 065tests = [t.strip() for t in open(options.list, "rt").readlines()]66if options.total_chunks > 1:67    test_counts = {}68    total_test_count = 069    for t in tests:70        if os.path.isdir(os.path.join(SCRIPT_DIRECTORY, t)):71            test_counts[t] = len(glob.glob(os.path.join(SCRIPT_DIRECTORY, t, "test*.js")))72        else:73            test_counts[t] = 174        total_test_count += test_counts[t]75    tests_per_chunk = float(total_test_count) / options.total_chunks76    start = int(round((options.this_chunk - 1) * tests_per_chunk))77    end = int(round(options.this_chunk * tests_per_chunk))78    chunk_tests = []79    cumulative_test_count = 080    for t in tests:81        if cumulative_test_count >= end:82            break83        if cumulative_test_count >= start:84            chunk_tests.append(t)85        cumulative_test_count += test_counts[t]86    tests = chunk_tests87for directory in tests:88    log.info("INFO | (runtestlist.py) | Running directory: %s",89             directory.rstrip())90    if options.dir != "":91        testDirectory = os.path.join(options.dir, directory.rstrip())92    else:93        testDirectory = directory.rstrip()94    args = [sys.executable, "runtest.py", "-t", testDirectory,95            "--binary", os.path.abspath(options.binary), "--symbols-path", options.symbols]96    if options.plugins:97        args.append("--plugins-path")98        args.append(options.plugins)99    if options.testingmodules:100        args.append("--testing-modules-dir")101        args.append(os.path.abspath(options.testingmodules))102    print args103    outputPipe = subprocess.PIPE104    proc = subprocess.Popen(args, cwd=SCRIPT_DIRECTORY, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)105    testErrors = 0106    testPasses = 0107    line = proc.stdout.readline()108    while line != "":109        log.info(line.rstrip())110        if line.find("TEST-UNEXPECTED-") != -1:111            testErrors += 1112        if line.find("TEST-PASS") != -1:113            testPasses += 1114        line = proc.stdout.readline()115    result = proc.wait()116    if result != 0:117        log.info("TEST-UNEXPECTED-FAIL | (runtestlist.py) | Exited with code %d during directory run", result)118        totalTestErrors += 1119    else:120        totalTestPasses += 1121    log.info("INFO | (runtestlist.py) | %s: %d passed, %d failed",122             directory.rstrip(), testPasses, testErrors)123    totalTestErrors += testErrors124    totalTestPasses += testPasses125    totalDirectories += 1126log.info("INFO | (runtestlist.py) | Directories Run: %d, Passed: %d, Failed: %d",127         totalDirectories, totalTestPasses, totalTestErrors)128if totalTestErrors:...apiTest.py
Source:apiTest.py  
1from src.task_b.api.apiRESTful import ApiRESTful as api2from sense_hat import SenseHat3from res.container import Container as c4import sqlite35import json6import time7# auto8class ApiTest():9   def __init__(self):10      self.sense = SenseHat()11      self.api = api()12      self.testPasses = [False, False, False, False]13   def writeTestLog(self, message):14      with open ("api_test_log.txt", 'a') as file:15         file.write(message + "\n")16   def testGetAllData(self):17      conn = sqlite3.connect(c.dbname)18      curs=conn.cursor()19      count = curs.execute("SELECT count(*) FROM sense_table").fetchone()[0]20      conn.close()21      data = json.loads(self.api.getAllData())22      if (len(data) == count):23         self.writeTestLog("getAllData passed !")24         self.testPasses[0] = True25         return True26      return False27   def testGetLastData (self):28      conn = sqlite3.connect(c.dbname)29      curs=conn.cursor()30      count = curs.execute("SELECT count(*) FROM sense_table").fetchone()[0]31      conn.close()32      data = json.loads(self.api.getLastData())33      if (data[0] == count):34         self.writeTestLog("getLastData passed !")35         self.testPasses[1] = True36         return True37      return False38   39   def testPostData(self):40      self.api.postData(9999,9999)41      42      if (self.testGetLastData() == False): return False43      newData = json.loads(self.api.getLastData())44      if (newData[2] == 9999 and newData[3] == 9999):45         self.writeTestLog("postData passed !")46         self.testPasses[2] = True47         return True48      return False49      50   def testUpdateLastData(self):51      self.api.updateLastData(6666, 8888)52      lastData = json.loads(self.api.getLastData())53      if (lastData[2] == 6666 and lastData[3] == 8888):54         self.writeTestLog("updateLastData passed !")55         self.testPasses[3] = True56         return True57         58      return False59   60   def execute(self):61      with open('api_test_log.txt', 'w'):62         pass63      self.testGetAllData()64      time.sleep(0.2)65      self.testGetLastData()66      time.sleep(0.2)67      self.testPostData()68      time.sleep(0.2)69      self.testUpdateLastData()70      time.sleep(0.2)71      count = 072      for i in range (len(self.testPasses)):73         if (self.testPasses[i] is True):74            count += 175      ...admin.spec.js
Source:admin.spec.js  
1import { shallowMount, createLocalVue } from '@vue/test-utils'2import Admin from './../../../resources/js/views/Admin.vue'3import Vuex from 'vuex'4const localVue = createLocalVue()5localVue.use(Vuex)6describe('Admin.vue', () => {7  const store = new Vuex.Store({8    modules: {9      User: {10        getters: {11          participantsWereSubmitted: () => null12        }13      }14    }15  })16  const $route = {17    meta: {18      title: 'ISTART'19    }20  }21  const wrapper = shallowMount(Admin, {22    store,23    mocks: { $route },24    localVue25  })26  it('should parse the json version of the excel file to an object format when parseFile is called', () => {27    const excelSheetJSON = [28      ['email', 'participant_id'],29      ['liad.golan.736@my.csun.edu', 689679],30      ['brian.linggadjaja.785@my.csun.edu', 41210],31      ['joshua.magdaleno.472@my.csun.edu', 5784],32      ['mbenda.ndour.487@my.csun.edu', 11137],33      ['edgar.canozelaya.6@my.csun.edu', 43466]34    ]35    const parsedExcelSheet = [36      {37        email: 'liad.golan.736@my.csun.edu',38        participant_id: 68967939      },40      {41        email: 'brian.linggadjaja.785@my.csun.edu',42        participant_id: 4121043      },44      {45        email: 'joshua.magdaleno.472@my.csun.edu',46        participant_id: 578447      },48      {49        email: 'mbenda.ndour.487@my.csun.edu',50        participant_id: 1113751      },52      {53        email: 'edgar.canozelaya.6@my.csun.edu',54        participant_id: 4346655      }56    ]57    expect(wrapper.vm.parseFile(excelSheetJSON)).toEqual(parsedExcelSheet)58  })59  it('should return true when checkFileType is called', () => {60    var filesToTest = ['excelSheet.xls', 'excel.xlsb', 'excel.xlsm', 'sheet.xls', 'excelsheet34.csv']61    var testPasses = false62    filesToTest.forEach(file => {63      if (wrapper.vm.checkFileType(file)) {64        testPasses = true65      }66    })67    expect(testPasses).toBe(true)68  })69  it('should return false when checkFileType is called', () => {70    var faultyFilesToTest = ['word.word', 'coolPowerPoint.ppt', 'mywebsite.html', 'uhhhhh.uhhhh']71    var testPasses = true72    faultyFilesToTest.forEach(file => {73      if (!wrapper.vm.checkFileType(file)) {74        testPasses = false75      }76    })77    expect(testPasses).toBe(false)78  })...password.test.ts
Source:password.test.ts  
1import { passwordRegex } from '../../../helpers/validationSchemas';2describe('Password requirements', () => {3  const isPasswordValid = (password: string) => passwordRegex.test(password);4  it('Must be min length', () => {5    expect(isPasswordValid('Passwor')).toBe(false);6  });7  it('Must not exceed max length', () => {8    const longPassword: any = 'p' * 129;9    expect(isPasswordValid(longPassword)).toBe(false);10  });11  it('Must Need a number or special char', () => {12    expect(isPasswordValid('Password')).toBe(false);13    expect(isPasswordValid('password')).toBe(false);14  });15  it('Accepts valid passwords', () => {16    const testPasses = [17      'Password123',18      'Password!',19      'password!',20      'Passworddddddddd!',21      'dddddddddddddddddds!',22      '1234567890123456789D',23    ];24    testPasses.forEach((pass) => expect(isPasswordValid(pass)).toBe(true));25  });26  it('All special chars make a valid password', () => {27    // Make a password for every valid special character28    const chars: string = '!"#$£%&\'()*+,-.:;<=>?@[]^_`{|}~';29    const testPasses = [];30    for (let char of chars) {31      testPasses.push('Password' + char);32    }33    // All special chars passwords34    testPasses.forEach((pass) => expect(isPasswordValid(pass)).toBe(true));35  });...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!!
