Best Python code snippet using pytest-django_python
decorators.py
Source:decorators.py
...51 }52 """)53 if multi_process_browser:54 raise SkipTest(reason)55 return test_item(self, *args, **kwargs)56 return skip_wrapper57 return decorator58def run_if_manage_instance(reason):59 """Decorator which runs a test if Marionette manages the application instance."""60 def decorator(test_item):61 if not isinstance(test_item, types.FunctionType):62 raise Exception('Decorator only supported for functions')63 @functools.wraps(test_item)64 def skip_wrapper(self, *args, **kwargs):65 if self.marionette.instance is None:66 raise SkipTest(reason)67 return test_item(self, *args, **kwargs)68 return skip_wrapper69 return decorator70def skip_if_chrome(reason):71 """Decorator which skips a test if chrome context is active."""72 def decorator(test_item):73 if not isinstance(test_item, types.FunctionType):74 raise Exception('Decorator only supported for functions')75 @functools.wraps(test_item)76 def skip_wrapper(self, *args, **kwargs):77 if self.marionette._send_message('getContext', key='value') == 'chrome':78 raise SkipTest(reason)79 return test_item(self, *args, **kwargs)80 return skip_wrapper81 return decorator82def skip_if_desktop(reason):83 """Decorator which skips a test if run on desktop."""84 def decorator(test_item):85 if not isinstance(test_item, types.FunctionType):86 raise Exception('Decorator only supported for functions')87 @functools.wraps(test_item)88 def skip_wrapper(self, *args, **kwargs):89 if self.marionette.session_capabilities.get('browserName') == 'firefox':90 raise SkipTest(reason)91 return test_item(self, *args, **kwargs)92 return skip_wrapper93 return decorator94def skip_if_e10s(reason):95 """Decorator which skips a test if e10s mode is active."""96 def decorator(test_item):97 if not isinstance(test_item, types.FunctionType):98 raise Exception('Decorator only supported for functions')99 @functools.wraps(test_item)100 def skip_wrapper(self, *args, **kwargs):101 with self.marionette.using_context('chrome'):102 multi_process_browser = self.marionette.execute_script("""103 try {104 return Services.appinfo.browserTabsRemoteAutostart;105 } catch (e) {106 return false;107 }108 """)109 if multi_process_browser:110 raise SkipTest(reason)111 return test_item(self, *args, **kwargs)112 return skip_wrapper113 return decorator114def skip_if_mobile(reason):115 """Decorator which skips a test if run on mobile."""116 def decorator(test_item):117 if not isinstance(test_item, types.FunctionType):118 raise Exception('Decorator only supported for functions')119 @functools.wraps(test_item)120 def skip_wrapper(self, *args, **kwargs):121 if self.marionette.session_capabilities.get('browserName') == 'fennec':122 raise SkipTest(reason)123 return test_item(self, *args, **kwargs)124 return skip_wrapper125 return decorator126def skip_unless_browser_pref(reason, pref, predicate=bool):127 """Decorator which skips a test based on the value of a browser preference.128 :param reason: Message describing why the test need to be skipped.129 :param pref: the preference name130 :param predicate: a function that should return false to skip the test.131 The function takes one parameter, the preference value.132 Defaults to the python built-in bool function.133 Note that the preference must exist, else a failure is raised.134 Example: ::135 class TestSomething(MarionetteTestCase):136 @skip_unless_browser_pref("Sessionstore needs to be enabled for crashes",137 "browser.sessionstore.resume_from_crash",138 lambda value: value is True,139 )140 def test_foo(self):141 pass # test implementation here142 """143 def decorator(test_item):144 if not isinstance(test_item, types.FunctionType):145 raise Exception('Decorator only supported for functions')146 if not callable(predicate):147 raise ValueError('predicate must be callable')148 @functools.wraps(test_item)149 def skip_wrapper(self, *args, **kwargs):150 value = self.marionette.get_pref(pref)151 if value is None:152 self.fail("No such browser preference: {0!r}".format(pref))153 if not predicate(value):154 raise SkipTest(reason)155 return test_item(self, *args, **kwargs)156 return skip_wrapper157 return decorator158def skip_unless_protocol(reason, predicate):159 """Decorator which skips a test if the predicate does not match the current protocol level."""160 def decorator(test_item):161 if not isinstance(test_item, types.FunctionType):162 raise Exception('Decorator only supported for functions')163 if not callable(predicate):164 raise ValueError('predicate must be callable')165 @functools.wraps(test_item)166 def skip_wrapper(self, *args, **kwargs):167 level = self.marionette.client.protocol168 if not predicate(level):169 raise SkipTest(reason)170 return test_item(self, *args, **kwargs)171 return skip_wrapper172 return decorator173def with_parameters(parameters):174 """Decorator which generates methods given a base method and some data.175 Acts like :func:`parameterized`, but define all methods in one call.176 Example::177 # This example will generate two methods:178 #179 # - MyTestCase.test_it_1180 # - MyTestCase.test_it_2181 #182 DATA = [("1", [5], {'named':'name'}), ("2", [6], {'named':'name2'})]183 class MyTestCase(MarionetteTestCase):184 @with_parameters(DATA)...
tree_test.py
Source:tree_test.py
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3#---------------------------------------------------------------------------------4# file: tree_test5# desc: This tests the tree functionality.6#7# author: Peter Antoine8# date: 15/03/20149#---------------------------------------------------------------------------------10# Copyright (c) 2014 Peter Antoine11# All rights Reserved.12# Released Under the MIT Licence13#---------------------------------------------------------------------------------14import os15import unittest16from beorn_lib.tree_item import TreeItem17#---------------------------------------------------------------------------------18# Helper Class19#---------------------------------------------------------------------------------20class TestClass(object):21 def __init__(self, item):22 self.item = item23 def updateTreeItem(self, item):24 item.updateTree([])25 def getTree(self, parent = None):26 new_item = TreeItem('item_' + str(self.item), parent, payload = self)27 return new_item28#---------------------------------------------------------------------------------29# Test Class30#---------------------------------------------------------------------------------31class TestTree(unittest.TestCase):32 """ User Tests """33 def __init__(self, testname = 'runTest', test_data = None, temp_data = None):34 self.test_data = test_data35 self.temp_data = temp_data36 # initialise the test framework37 super(TestTree, self).__init__(testname)38 #---------------------------------------------------------------------------------39 # Test Data40 #---------------------------------------------------------------------------------41 test_item = [ TestClass('0'),42 TestClass('1'),43 TestClass('2'),44 TestClass('3'),45 TestClass('4'),46 TestClass('5'),47 TestClass('6'),48 TestClass('7'),49 TestClass('8'),50 TestClass('9'),51 TestClass('10'),52 TestClass('11'),53 TestClass('12'),54 TestClass('13'),55 TestClass('14'),56 TestClass('15'),57 TestClass('16'),58 TestClass('17'),59 TestClass('18'),60 TestClass('19')61 ]62 #---------------------------------------------------------------------------------63 # Helper Functions64 #---------------------------------------------------------------------------------65 def buildTree(self, tree_list, entry = None):66 """ Build Tree """67 if entry is None:68 result = TreeItem('base', None)69 else:70 result = entry71 # Ok, two identical lists72 for item in tree_list:73 new_item = TreeItem('item_' + str(item), result, payload = TestTree.test_item[item])74 result.appendEntry(new_item)75 return result76 def compareLists(self, item, item_list):77 """ Compare Lists """78 result = False79 if len(item.item_list) == len(item_list):80 for index in range(0, len(item.item_list)):81 if item.item_list[index].payload != item_list[index]:82 break83 else:84 result = True85 return result86 #---------------------------------------------------------------------------------87 # Test Functions88 #---------------------------------------------------------------------------------89 def test_TestUpdateTree(self):90 """ Test Update Tree """91 base = self.buildTree(list(range(1, 7)))92 object_list = [TestTree.test_item[1], TestTree.test_item[2], TestTree.test_item[3], TestTree.test_item[4], TestTree.test_item[5], TestTree.test_item[6]]93 base.updateTree(object_list)94 self.assertTrue(self.compareLists(base, object_list))95 # Ok, b is longer than a96 base = self.buildTree([1, 2, 3, 4, 5, 6])97 object_list = [ TestTree.test_item[1],98 TestTree.test_item[2],99 TestTree.test_item[3],100 TestTree.test_item[4],101 TestTree.test_item[5],102 TestTree.test_item[6],103 TestTree.test_item[7]]104 base.updateTree(object_list)105 self.assertTrue(self.compareLists(base, object_list))106 #Ok, b is longer then a, in the middle107 base = self.buildTree([1, 2, 3, 4, 5, 6])108 object_list = [ TestTree.test_item[1],109 TestTree.test_item[8],110 TestTree.test_item[2],111 TestTree.test_item[3],112 TestTree.test_item[7],113 TestTree.test_item[4],114 TestTree.test_item[5],115 TestTree.test_item[6]]116 base.updateTree(object_list)117 self.assertTrue(self.compareLists(base, object_list))118 #Ok, b is shorter then a, in the middle119 base = self.buildTree([1, 2, 3, 4, 5, 6])120 object_list = [TestTree.test_item[1], TestTree.test_item[2], TestTree.test_item[5], TestTree.test_item[6]]121 base.updateTree(object_list)122 self.assertTrue(self.compareLists(base, object_list))123 #Ok, b is shorter then a, in the middle with a new element124 base = self.buildTree([1, 2, 3, 4, 5, 6])125 object_list = [TestTree.test_item[1], TestTree.test_item[2], TestTree.test_item[7], TestTree.test_item[5], TestTree.test_item[6]]126 base.updateTree(object_list)127 self.assertTrue(self.compareLists(base, object_list))128 #Ok, a is short then b at the front129 base = self.buildTree([1, 2, 3, 4, 5, 6])130 object_list = [ TestTree.test_item[1],131 TestTree.test_item[2],132 TestTree.test_item[3],133 TestTree.test_item[4],134 TestTree.test_item[5],135 TestTree.test_item[6]]136 base.updateTree(object_list)137 self.assertTrue(self.compareLists(base, object_list))138 #Ok, a is short then b at the front, with a new element at the end139 base = self.buildTree([2, 3, 4, 5, 6, 7])140 object_list = [ TestTree.test_item[1],141 TestTree.test_item[2],142 TestTree.test_item[3],143 TestTree.test_item[4],144 TestTree.test_item[5],145 TestTree.test_item[6]]146 base.updateTree(object_list)147 self.assertTrue(self.compareLists(base, object_list))148 #Ok, deleted elements at the end and the middle for a.149 base = self.buildTree([2, 3, 4, 8, 9, 10, 5, 6, 7])150 object_list = [ TestTree.test_item[1],151 TestTree.test_item[2],152 TestTree.test_item[3],153 TestTree.test_item[4],154 TestTree.test_item[5],155 TestTree.test_item[6]]156 base.updateTree(object_list)157 self.assertTrue(self.compareLists(base, object_list))...
utils.py
Source:utils.py
1# -*- coding: utf-8 -*-2from __future__ import absolute_import3from unittest import TestCase4from functools import wraps5from nose.plugins.skip import SkipTest6from nltk.util import py267def skip(reason):8 """9 Unconditionally skip a test.10 """11 def decorator(test_item):12 is_test_class = isinstance(test_item, type) and issubclass(test_item, TestCase)13 if is_test_class and py26():14 # Patch all test_ methods to raise SkipText exception.15 # This is necessary for Python 2.6 because its unittest16 # doesn't understand __unittest_skip__.17 for meth_name in (m for m in dir(test_item) if m.startswith('test_')):18 patched_method = skip(reason)(getattr(test_item, meth_name))19 setattr(test_item, meth_name, patched_method)20 if not is_test_class:21 @wraps(test_item)22 def skip_wrapper(*args, **kwargs):23 raise SkipTest(reason)24 skip_wrapper.__name__ = test_item.__name__25 test_item = skip_wrapper26 test_item.__unittest_skip__ = True27 test_item.__unittest_skip_why__ = reason28 return test_item29 return decorator30def skipIf(condition, reason):31 """32 Skip a test if the condition is true.33 """34 if condition:35 return skip(reason)...
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!!