Best Python code snippet using Airtest
test_bot
Source:test_bot
1#!/usr/bin/python2import errno, os, socket, subprocess, sys, time3def clean():4 for path, dir_list, file_list in os.walk('.'):5 for file in file_list:6 # delete *.pyc files so that deleted/moved files can not be imported7 if file[-4:] in ('.pyc', '.pyo'):8 os.remove(os.path.join(path, file))9class GitError(EnvironmentError):10 def __init__(self, err, out, returncode):11 EnvironmentError.__init__(self, err)12 self.stdout = out13 self.returncode = returncode14def _git(*args, **kw):15 p = subprocess.Popen(('git',) + args, **kw)16 out, err = p.communicate()17 if p.returncode:18 raise GitError(err, out, p.returncode)19 return out20def git(*args, **kw):21 out = _git(stdout=subprocess.PIPE, stderr=subprocess.PIPE, *args, **kw)22 return out.strip()23def getRevision(*path):24 return git('log', '-1', '--format=%H', '--', *path)25def main():26 if 'LANG' in os.environ:27 del os.environ['LANG']28 os.environ.setdefault('NEO_TEST_ZODB_FUNCTIONAL', '1')29 arg_count = 130 while arg_count < len(sys.argv):31 arg = sys.argv[arg_count]32 if arg[:2] != '--':33 break34 arg_count += '=' in arg and 1 or 235 branch = git('rev-parse', '--abbrev-ref', 'HEAD')36 test_bot = os.path.realpath(__file__).split(os.getcwd())[1][1:]37 test_bot_revision = getRevision(test_bot)38 revision = 039 clean()40 delay = None41 while True:42 delay = delay and time.sleep(delay) or 180043 s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)44 try:45 while True:46 try:47 s.bind("\0neo.tools.test_bot")48 break49 except socket.error, e:50 if e.errno != errno.EADDRINUSE:51 raise52 time.sleep(60)53 old_revision = revision54 try:55 _git('fetch')56 _git('reset', '--merge', '@{u}')57 except GitError, e:58 continue59 revision = getRevision()60 if revision == old_revision:61 continue62 if test_bot_revision != getRevision(test_bot):63 break64 delay = None65 for test_home in sys.argv[arg_count:]:66 test_home, tasks = test_home.rsplit('=', 1)67 tests = ''.join(x for x in tasks if x in 'fuz')68 bin = os.path.join(test_home, 'bin')69 if subprocess.call((os.path.join(bin, 'buildout'), '-v'),70 cwd=test_home):71 continue72 for backend in 'SQLite', 'MySQL':73 os.environ['NEO_TESTS_ADAPTER'] = backend74 title = '[%s:%s-g%s:%s:%s]' % (branch,75 git('rev-list', '--topo-order', '--count', revision),76 revision[:7], os.path.basename(test_home), backend)77 if tests:78 subprocess.call([os.path.join(bin, 'neotestrunner'),79 '-v' + tests, '--title', 'NEO tests ' + title,80 ] + sys.argv[1:arg_count])81 if 'm' in tasks:82 subprocess.call([os.path.join(bin, 'python'),83 'tools/matrix', '--repeat=2',84 '--min-storages=1', '--max-storages=24',85 '--min-replicas=0', '--max-replicas=3',86 '--title', 'Matrix ' + title,87 ] + sys.argv[1:arg_count])88 finally:89 s.close()90 clean()91 os.execvp(sys.argv[0], sys.argv)92if __name__ == '__main__':...
back_fixtures.py
Source:back_fixtures.py
1import pytest2from django.core.files import File3from wagtail.core.models import Page4from wagtail.images.models import Image5from cabins.back.models import ContinentalPage, HomePage, ListingPage, RegionalPage, StatePage6from .core_fixtures import image_fixture7@pytest.fixture8def wagtail_image(db) -> Image:9 with open(image_fixture["file"], 'rb') as _file:10 file_data = File(_file)11 image = Image(title="test_home")12 image.file.save(13 name="test_home",14 content=file_data15 )16 image.save()17@pytest.fixture18def home_page(db, wagtail_image) -> HomePage:19 image = Image.objects.get(title="test_home")20 root_page = Page.objects.get(depth=1)21 root_page.add_child(22 instance=HomePage(23 title="test_home",24 description="test home description",25 meta_description="test home meta description",26 og_description="test home og description",27 hero_image=image,28 og_image=image29 )30 )31 root_page.save()32@pytest.fixture33def continental_page(db, wagtail_image, home_page) -> ContinentalPage:34 image = Image.objects.get(title="test_home")35 home_page = HomePage.objects.first()36 home_page.add_child(37 instance=ContinentalPage(38 title="test_continental",39 description="test ontinental description",40 meta_description="test ontinental meta description",41 og_description="test ontinental og description",42 hero_image=image,43 og_image=image44 )45 )46 home_page.save()47@pytest.fixture48def state_page(db, wagtail_image, home_page, continental_page) -> StatePage:49 image = Image.objects.get(title="test_home")50 con_page = ContinentalPage.objects.first()51 con_page.add_child(52 instance=StatePage(53 title="test_state",54 description="test ontinental description",55 meta_description="test ontinental meta description",56 og_description="test ontinental og description",57 hero_image=image,58 og_image=image59 )60 )61 con_page.save()62@pytest.fixture63def region_page(db, wagtail_image, home_page, continental_page, state_page) -> RegionalPage:64 image = Image.objects.get(title="test_home")65 state_page = StatePage.objects.first()66 state_page.add_child(67 instance=RegionalPage(68 title="test_region",69 description="test region description",70 meta_description="test region meta description",71 og_description="test region og description",72 hero_image=image,73 og_image=image74 )75 )76 state_page.save()77@pytest.fixture78def listing_page(db, wagtail_image, home_page, continental_page, state_page, region_page) -> ListingPage:79 image = Image.objects.get(title="test_home")80 reg_page = RegionalPage.objects.first()81 reg_page.add_child(82 instance=ListingPage(83 title="test_listing",84 description="test listing description",85 meta_description="test listing meta description",86 og_description="test listing og description",87 hero_image=image,88 og_image=image,89 street="test1",90 street2="ave",91 city="testcity",92 region="ohio",93 country="usa",94 postal_code="44094",95 website="https://test.com"96 )97 )...
tester.py
Source:tester.py
1from pathlib import Path2import os3import re4import subprocess5import shutil6from helpers import *7def positive_test():8 gc_output_file = Path('result')9 tests_bin_file = Path('tests')10 pattern = re.compile(r'//[ ]*expect:(.*)')11 file = open(Path.cwd() / 'tests.g')12 gold = list()13 line = 114 for l in file.readlines():15 mo = pattern.search(l)16 if mo is not None:17 gold.append((line, mo.group(1).strip()))18 line = line + 119 outfile = open(gc_output_file, 'w')20 subprocess.run('./'+str(tests_bin_file), stdout=outfile)21 output = list()22 outfile = open(gc_output_file)23 for l in outfile.readlines():24 output.append(l.rstrip())25 # fill output list so it has the same number of elements as gold standart26 for i in range(len(gold)-len(output)):27 output.append(None)28 error_count = 029 for i in range(len(gold)):30 if gold[i][1] != output[i]:31 error_count = error_count + 132 print(F'error on line {gold[i][0]}: {gold[i][1]} != {output[i]}')33 file.close()34 os.unlink(gc_output_file)35 os.unlink(tests_bin_file)36 return error_count37def negative_test():38 try:39 os.mkdir('tmp')40 except:41 pass42 test_home = Path('tmp')43 break_into_separate_progs('tests_neg.g', test_home)44 error_count = 045 for folderName, subfolder, filenames in os.walk(test_home):46 for filename in filenames:47 msg = subprocess.run(['./gc', (test_home / filename)], capture_output=True)48 if (msg.returncode == 0):49 error_count = error_count + 150 print(F'Error: compilation of {test_home}/{filename} succeeded unexpectedly:')51 test_file = open(test_home / filename)52 print(test_file.read())53 shutil.rmtree(test_home)54 return error_count55def bounds_test():56 try:57 os.mkdir('tmp')58 except:59 pass60 test_home = Path('tmp')61 break_into_separate_progs('tests_bounds.g', test_home)62 error_count = 063 for folderName, subfolder, filenames in os.walk(test_home):64 for filename in filenames:65 msg = subprocess.run(['./gc', (test_home / filename), '-o', (test_home / filename.strip('.g'))], capture_output=True)66 if (msg.returncode != 0):67 print(F'Error: compilation of {test_home}/{filename} failed unexpectedly:')68 test_file = open(test_home / filename)69 print(test_file.read())70 error_count += 171 p = subprocess.Popen(['./'+str(test_home / filename.strip('.g'))], stderr=subprocess.DEVNULL)72 pid, exit_status, res_usage = os.wait4(p.pid, 0)73 if (exit_status == 0):74 error_count += 175 print(F'Error: {test_home}/{filename} executed successfully:')76 test_file = open(test_home / filename.strip())77 print(test_file.read())78 shutil.rmtree(test_home)79 return error_count80def main():81 pos_count = positive_test()82 neg_count = negative_test()83 bounds_count = bounds_test()84 print(F'There were total {pos_count} errors in positive test')85 print(F'There were total {neg_count} errors in negative test')86 print(F'There were total {bounds_count} errors in bounds test')87 88if __name__ == "__main__":...
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!!