Best Python code snippet using avocado_python
profile.py
Source:profile.py
...292 iter_ = et.iterparse(f, events=(b'start', ))293 for _, elem in iter_:294 if elem.tag == 'PiglitTestList':295 return int(elem.attrib['count'])296 return sum(1 for _ in self.itertests())297 def setup(self):298 pass299 def teardown(self):300 pass301 def _itertests(self):302 """Always iterates tests instead of using the forced test_list."""303 def _iter():304 with gzip.open(self.filename, 'rt') as f:305 doc = et.iterparse(f, events=(b'end', ))306 _, root = next(doc) # get the root so we can keep clearing it307 for _, e in doc:308 if e.tag != 'Test':309 continue310 k = e.attrib['name']311 v = make_test(e)312 yield k, v313 root.clear()314 for k, v in self.filters.run(_iter()):315 yield k, v316 def itertests(self):317 if self.forced_test_list:318 alltests = dict(self._itertests())319 opts = collections.OrderedDict()320 for n in self.forced_test_list:321 if self.options['ignore_missing'] and n not in alltests:322 opts[n] = DummyTest(n, status.NOTRUN)323 else:324 opts[n] = alltests[n]325 return six.iteritems(opts)326 else:327 return iter(self._itertests())328class MetaProfile(object):329 """Holds multiple profiles but acts like one.330 This is meant to allow classic profiles like all to exist after being331 split.332 """333 def __init__(self, filename):334 self.forced_test_list = []335 self.filters = Filters()336 self.options = {337 'dmesg': get_dmesg(False),338 'monitor': Monitoring(False),339 'ignore_missing': False,340 }341 tree = et.parse(filename)342 root = tree.getroot()343 self._profiles = [load_test_profile(p.text)344 for p in root.findall('.//Profile')]345 for p in self._profiles:346 p.options = self.options347 def __len__(self):348 if self.forced_test_list or self.filters:349 return sum(1 for _ in self.itertests())350 return sum(len(p) for p in self._profiles)351 def setup(self):352 pass353 def teardown(self):354 pass355 def _itertests(self):356 def _iter():357 for p in self._profiles:358 for k, v in p.itertests():359 yield k, v360 for k, v in self.filters.run(_iter()):361 yield k, v362 def itertests(self):363 if self.forced_test_list:364 alltests = dict(self._itertests())365 opts = collections.OrderedDict()366 for n in self.forced_test_list:367 if self.options['ignore_missing'] and n not in alltests:368 opts[n] = DummyTest(n, status.NOTRUN)369 else:370 opts[n] = alltests[n]371 return six.iteritems(opts)372 else:373 return iter(self._itertests())374class TestProfile(object):375 """Class that holds a list of tests for execution.376 This class represents a single testsuite, it has a mapping (dictionary-like377 object) of tests attached (TestDict). This is a mapping of <str>:<Test>378 (python 3 str, python 2 unicode), and the key is delimited by379 grouptools.SEPARATOR.380 The group_manager method provides a context_manager to make adding test to381 the test_list easier, by doing more validation and enforcement.382 >>> t = TestProfile()383 >>> with t.group_manager(Test, 'foo@bar') as g:384 ... g(['foo'])385 This class does not provide a way to execute itself, instead that is386 handled by the run function in this module, which is able to process and387 run multiple TestProfile objects at once.388 """389 def __init__(self):390 self.test_list = TestDict()391 self.forced_test_list = []392 self.filters = Filters()393 self.options = {394 'dmesg': get_dmesg(False),395 'monitor': Monitoring(False),396 'ignore_missing': False,397 }398 def __len__(self):399 return sum(1 for _ in self.itertests())400 def setup(self):401 """Method to do pre-run setup."""402 def teardown(self):403 """Method to do post-run teardown."""404 def copy(self):405 """Create a copy of the TestProfile.406 This method creates a copy with references to the original instance407 using copy.copy. This allows profiles to be "subclassed" by other408 profiles, without modifying the original.409 copy.deepcopy is used for the filters so the original is410 actually not modified in this case.411 """412 new = copy.copy(self)413 new.test_list = copy.copy(self.test_list)414 new.forced_test_list = copy.copy(self.forced_test_list)415 new.filters = copy.deepcopy(self.filters)416 return new417 def itertests(self):418 """Iterate over tests while filtering.419 This iterator is non-destructive.420 """421 if self.forced_test_list:422 opts = collections.OrderedDict()423 for n in self.forced_test_list:424 if self.options['ignore_missing'] and n not in self.test_list:425 opts[n] = DummyTest(n, status.NOTRUN)426 else:427 opts[n] = self.test_list[n]428 else:429 opts = self.test_list # pylint: disable=redefined-variable-type430 for k, v in self.filters.run(six.iteritems(opts)):431 yield k, v432def load_test_profile(filename, python=None):433 """Load a python module and return it's profile attribute.434 All of the python test files provide a profile attribute which is a435 TestProfile instance. This loads that module and returns it or raises an436 error.437 This method doesn't care about file extensions as a way to be backwards438 compatible with script wrapping piglit. 'tests/quick', 'tests/quick.tests',439 'tests/quick.py', and 'quick' are all equally valid for filename.440 This will raise a FatalError if the module doesn't exist, or if the module441 doesn't have a profile attribute.442 Raises:443 PiglitFatalError -- if the module cannot be imported for any reason, or if444 the module lacks a "profile" attribute.445 Arguments:446 filename -- the name of a python module to get a 'profile' from447 Keyword Arguments:448 python -- If this is None (the default) XML is tried, and then a python449 module. If True, then only python is tried, if False then only450 XML is tried.451 """452 name, ext = os.path.splitext(os.path.basename(filename))453 if ext == '.no_isolation':454 name = filename455 if not python:456 # If process-isolation is false then try to load a profile named457 # {name}.no_isolation instead. This is only valid for xml based458 # profiles.459 if ext != '.no_isolation' and not OPTIONS.process_isolation:460 try:461 return load_test_profile(name + '.no_isolation' + ext, python)462 except exceptions.PiglitFatalError:463 # There might not be a .no_isolation version, try to load the464 # regular version in that case.465 pass466 meta = os.path.join(ROOT_DIR, 'tests', name + '.meta.xml')467 if os.path.exists(meta):468 return MetaProfile(meta)469 xml = os.path.join(ROOT_DIR, 'tests', name + '.xml.gz')470 if os.path.exists(xml):471 return XMLProfile(xml)472 if python is False:473 raise exceptions.PiglitFatalError(474 'Cannot open "tests/{0}.xml.gz" or "tests/{0}.meta.xml"'.format(name))475 try:476 mod = importlib.import_module('tests.{0}'.format(name))477 except ImportError:478 raise exceptions.PiglitFatalError(479 'Failed to import "{}", there is either something wrong with the '480 'module or it doesn\'t exist. Check your spelling?'.format(481 filename))482 try:483 return mod.profile484 except AttributeError:485 raise exceptions.PiglitFatalError(486 'There is no "profile" attribute in module {}.\n'487 'Did you specify the right file?'.format(filename))488def run(profiles, logger, backend, concurrency, jobs):489 """Runs all tests using Thread pool.490 When called this method will flatten out self.tests into self.test_list,491 then will prepare a logger, and begin executing tests through it's Thread492 pools.493 Based on the value of concurrency it will either run all the tests494 concurrently, all serially, or first the thread safe tests then the495 serial tests.496 Finally it will print a final summary of the tests.497 Arguments:498 profiles -- a list of Profile instances.499 logger -- a log.LogManager instance.500 backend -- a results.Backend derived instance.501 jobs -- maximum number of concurrent jobs. Use os.cpu_count() by default502 """503 chunksize = 1504 profiles = [(p, p.itertests()) for p in profiles]505 log = LogManager(logger, sum(len(p) for p, _ in profiles))506 # check that after the filters are run there are actually tests to run.507 # if not any(l for _, l in profiles):508 # raise exceptions.PiglitUserError('no matching tests')509 def test(name, test, profile, this_pool=None):510 """Function to call test.execute from map"""511 with backend.write_test(name) as w:512 test.execute(name, log.get(), profile.options)513 w(test.result)514 if profile.options['monitor'].abort_needed:515 this_pool.terminate()516 def run_threads(pool, profile, test_list, filterby=None):517 """ Open a pool, close it, and join it """518 if filterby:...
testArticleConvert.py
Source:testArticleConvert.py
1# Copyright: Krzysztof Kowalczyk2# Owner: Krzysztof Kowalczyk3#4# Purpose:5# Automated unit testing of Wikipedia article conversion routines6# Usage:7# testFileName : file with tests to use8#9from __future__ import generators # for 2.2 compatibility10import sys,os,os.path,string,time,md5,bz211import arsutils,articleconvert12try:13 import psyco14 psyco.full()15except:16 print "psyco not available. You should consider using it (http://psyco.sourceforge.net/)"17def usageAndExit():18 print "Usage: testArticleConvert.py testFileName"19 sys.exit(0)20class ConvertTest:21 def __init__(self,name,orig,expected):22 self.name = name23 self.orig = orig24 self.expected = expected25 def setConverted(self,converted):26 self.converted = converted27def fShortTest(line):28 if len(line)>2 and line[:2]=="@s":29 return True30 return False31# short test is in the form:32# @s2 orig*expected33# i.e.: "@s", name of the test (everything up to a space),34# original text and expected text separated by a "*"35def parseShortTest(line):36 assert line[:2] == "@s"37 line = line[2:]38 parts = line.split(" ",1)39 assert len(parts)==240 name = parts[0]41 txt = parts[1]42 (orig,expected) = txt.split("*") 43 return (name,orig,expected)44def iterTests(fileName):45 fo = open(fileName,"rb")46 # skip comments and empty lines at the beginning of the file47 while True:48 line = fo.readline()49 if len(line) == 0:50 print "File with no tests in it!"51 return52 if len(line.strip())==0:53 continue54 if line[0] == '#':55 continue56 break57 # we skip comments (lines beginning with '#') if they appear58 # right after new test mark (line beginning with '@')59 fSkipComments = False60 while len(line) != 0:61 # we have a line to process from the code above62 if line[0] != '@':63 print "! line should start with '@' (line: '%s')" % line64 assert line[0] == '@'65 line = line.strip()66 if fShortTest(line):67 (name,orig,expected) = parseShortTest(line)68 test = ConvertTest(name,orig,expected)69 yield test70 line = fo.readline()71 continue72 name = line[1:]73 # read the text before conversion and expected result of conversion74 orig = ""75 expected = ""76 fReadingOrig = True77 line = fo.readline()78 fSkipComments = True79 while True:80 if len(line)==0:81 if fReadingOrig:82 print "Test with name '%s' interrupted in the middle" % name83 assert len(line)!=084 else:85 # this is the end of file86 test = ConvertTest(name,orig,expected)87 yield test88 fo.close()89 return90 if line[0] == '@':91 if fReadingOrig:92 fReadingOrig = False93 else:94 # this is a beginning of a new test95 test = ConvertTest(name,orig,expected)96 yield test97 break98 else:99 if fSkipComments and line[0]=='#':100 #do nothing101 pass102 else:103 fSkipComments = False104 if fReadingOrig:105 orig += line106 else:107 expected += line108 line = fo.readline()109 # and end of iterTests110failedList = []111def dumpFailed():112 for test in failedList:113 print "Test with name '%s' failed" % test.name114 print "orig : '%s'" % test.orig.strip()115 print "expected: '%s'" % test.expected.strip()116 print "got : '%s'" % test.converted.strip()117def diffFirstFailed():118 if len(failedList)==0:119 return120 test = failedList[0]121 arsutils.showTxtDiff(test.expected.strip(),test.converted.strip())122def testTests(fileName):123 for test in iterTests(fileName):124 print "name: '%s'" % test.name125 print "orig: '%s'" % test.orig126 print "expe: '%s'" % test.expected127def runTests(fileName):128 redirects = {}129 articleTitles = {}130 testCount = 0131 failedCount = 0132 for test in iterTests(fileName):133 orig = test.orig134 expected = test.expected135 converted = articleconvert.convertArticle(test.name,orig)136 expected = arsutils.normalizeNewlines(expected)137 converted = arsutils.normalizeNewlines(converted)138 if converted != expected:139 failedCount += 1140 test.setConverted(converted)141 failedList.append(test)142 sys.stdout.write("-")143 else:144 sys.stdout.write(".")145 noLinks = articleconvert.removeInvalidLinks(converted,redirects,articleTitles)146 testCount += 1147 print148 print "Total tests: %d" % testCount149 print "Failed tests: %d" % failedCount150 dumpFailed()151 diffFirstFailed()152if __name__=="__main__":153 # now we should only have file name154 if len(sys.argv) != 2:155 usageAndExit()156 fileName = sys.argv[1]157 runTests(fileName)...
run_tests.py
Source:run_tests.py
...7import sys8import unittest9self_path = os.path.abspath(__file__)10base = os.path.dirname(self_path)11def itertests(suite):12 stack = [suite]13 while stack:14 suite = stack.pop()15 for test in suite:16 if isinstance(test, unittest.TestSuite):17 stack.append(test)18 continue19 if test.__class__.__name__ == 'ModuleImportFailure':20 raise Exception('Failed to import a test module: %s' % test)21 yield test22def filter_tests(suite, test_ok):23 ans = unittest.TestSuite()24 added = set()25 for test in itertests(suite):26 if test_ok(test) and test not in added:27 ans.addTest(test)28 added.add(test)29 return ans30def filter_tests_by_name(suite, name):31 if not name.startswith('test_'):32 name = 'test_' + name33 if name.endswith('_'):34 def q(test):35 return test._testMethodName.startswith(name)36 else:37 def q(test):38 return test._testMethodName == name39 return filter_tests(suite, q)...
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!!