Best Python code snippet using unittest-xml-reporting_python
suite.py
Source:suite.py
1"""TestSuite"""2import sys3from . import case4from . import util5__unittest = True6def _call_if_exists(parent, attr):7 func = getattr(parent, attr, lambda: None)8 func()9class BaseTestSuite(object):10 """A simple test suite that doesn't provide class or module shared fixtures.11 """12 def __init__(self, tests=()):13 self._tests = []14 self.addTests(tests)15 def __repr__(self):16 return "<%s tests=%s>" % (util.strclass(self.__class__), list(self))17 def __eq__(self, other):18 if not isinstance(other, self.__class__):19 return NotImplemented20 return list(self) == list(other)21 def __ne__(self, other):22 return not self == other23 # Can't guarantee hash invariant, so flag as unhashable24 __hash__ = None25 def __iter__(self):26 return iter(self._tests)27 def countTestCases(self):28 cases = 029 for test in self:30 cases += test.countTestCases()31 return cases32 def addTest(self, test):33 # sanity checks34 if not hasattr(test, '__call__'):35 raise TypeError("{} is not callable".format(repr(test)))36 if isinstance(test, type) and issubclass(test,37 (case.TestCase, TestSuite)):38 raise TypeError("TestCases and TestSuites must be instantiated "39 "before passing them to addTest()")40 self._tests.append(test)41 def addTests(self, tests):42 if isinstance(tests, basestring):43 raise TypeError("tests must be an iterable of tests, not a string")44 for test in tests:45 self.addTest(test)46 def run(self, result):47 for test in self:48 if result.shouldStop:49 break50 test(result)51 return result52 def __call__(self, *args, **kwds):53 return self.run(*args, **kwds)54 def debug(self):55 """Run the tests without collecting errors in a TestResult"""56 for test in self:57 test.debug()58class TestSuite(BaseTestSuite):59 """A test suite is a composite test consisting of a number of TestCases.60 For use, create an instance of TestSuite, then add test case instances.61 When all tests have been added, the suite can be passed to a test62 runner, such as TextTestRunner. It will run the individual test cases63 in the order in which they were added, aggregating the results. When64 subclassing, do not forget to call the base class constructor.65 """66 def run(self, result, debug=False):67 topLevel = False68 if getattr(result, '_testRunEntered', False) is False:69 result._testRunEntered = topLevel = True70 for test in self:71 if result.shouldStop:72 break73 if _isnotsuite(test):74 self._tearDownPreviousClass(test, result)75 self._handleModuleFixture(test, result)76 self._handleClassSetUp(test, result)77 result._previousTestClass = test.__class__78 if (getattr(test.__class__, '_classSetupFailed', False) or79 getattr(result, '_moduleSetUpFailed', False)):80 continue81 if not debug:82 test(result)83 else:84 test.debug()85 if topLevel:86 self._tearDownPreviousClass(None, result)87 self._handleModuleTearDown(result)88 result._testRunEntered = False89 return result90 def debug(self):91 """Run the tests without collecting errors in a TestResult"""92 debug = _DebugResult()93 self.run(debug, True)94 ################################95 def _handleClassSetUp(self, test, result):96 previousClass = getattr(result, '_previousTestClass', None)97 currentClass = test.__class__98 if currentClass == previousClass:99 return100 if result._moduleSetUpFailed:101 return102 if getattr(currentClass, "__unittest_skip__", False):103 return104 try:105 currentClass._classSetupFailed = False106 except TypeError:107 # test may actually be a function108 # so its class will be a builtin-type109 pass110 setUpClass = getattr(currentClass, 'setUpClass', None)111 if setUpClass is not None:112 _call_if_exists(result, '_setupStdout')113 try:114 setUpClass()115 except Exception as e:116 if isinstance(result, _DebugResult):117 raise118 currentClass._classSetupFailed = True119 className = util.strclass(currentClass)120 errorName = 'setUpClass (%s)' % className121 self._addClassOrModuleLevelException(result, e, errorName)122 finally:123 _call_if_exists(result, '_restoreStdout')124 def _get_previous_module(self, result):125 previousModule = None126 previousClass = getattr(result, '_previousTestClass', None)127 if previousClass is not None:128 previousModule = previousClass.__module__129 return previousModule130 def _handleModuleFixture(self, test, result):131 previousModule = self._get_previous_module(result)132 currentModule = test.__class__.__module__133 if currentModule == previousModule:134 return135 self._handleModuleTearDown(result)136 result._moduleSetUpFailed = False137 try:138 module = sys.modules[currentModule]139 except KeyError:140 return141 setUpModule = getattr(module, 'setUpModule', None)142 if setUpModule is not None:143 _call_if_exists(result, '_setupStdout')144 try:145 setUpModule()146 except Exception, e:147 if isinstance(result, _DebugResult):148 raise149 result._moduleSetUpFailed = True150 errorName = 'setUpModule (%s)' % currentModule151 self._addClassOrModuleLevelException(result, e, errorName)152 finally:153 _call_if_exists(result, '_restoreStdout')154 def _addClassOrModuleLevelException(self, result, exception, errorName):155 error = _ErrorHolder(errorName)156 addSkip = getattr(result, 'addSkip', None)157 if addSkip is not None and isinstance(exception, case.SkipTest):158 addSkip(error, str(exception))159 else:160 result.addError(error, sys.exc_info())161 def _handleModuleTearDown(self, result):162 previousModule = self._get_previous_module(result)163 if previousModule is None:164 return165 if result._moduleSetUpFailed:166 return167 try:168 module = sys.modules[previousModule]169 except KeyError:170 return171 tearDownModule = getattr(module, 'tearDownModule', None)172 if tearDownModule is not None:173 _call_if_exists(result, '_setupStdout')174 try:175 tearDownModule()176 except Exception as e:177 if isinstance(result, _DebugResult):178 raise179 errorName = 'tearDownModule (%s)' % previousModule180 self._addClassOrModuleLevelException(result, e, errorName)181 finally:182 _call_if_exists(result, '_restoreStdout')183 def _tearDownPreviousClass(self, test, result):184 previousClass = getattr(result, '_previousTestClass', None)185 currentClass = test.__class__186 if currentClass == previousClass:187 return188 if getattr(previousClass, '_classSetupFailed', False):189 return190 if getattr(result, '_moduleSetUpFailed', False):191 return192 if getattr(previousClass, "__unittest_skip__", False):193 return194 tearDownClass = getattr(previousClass, 'tearDownClass', None)195 if tearDownClass is not None:196 _call_if_exists(result, '_setupStdout')197 try:198 tearDownClass()199 except Exception, e:200 if isinstance(result, _DebugResult):201 raise202 className = util.strclass(previousClass)203 errorName = 'tearDownClass (%s)' % className204 self._addClassOrModuleLevelException(result, e, errorName)205 finally:206 _call_if_exists(result, '_restoreStdout')207class _ErrorHolder(object):208 """209 Placeholder for a TestCase inside a result. As far as a TestResult210 is concerned, this looks exactly like a unit test. Used to insert211 arbitrary errors into a test suite run.212 """213 # Inspired by the ErrorHolder from Twisted:214 # http://twistedmatrix.com/trac/browser/trunk/twisted/trial/runner.py215 # attribute used by TestResult._exc_info_to_string216 failureException = None217 def __init__(self, description):218 self.description = description219 def id(self):220 return self.description221 def shortDescription(self):222 return None223 def __repr__(self):224 return "<ErrorHolder description=%r>" % (self.description,)225 def __str__(self):226 return self.id()227 def run(self, result):228 # could call result.addError(...) - but this test-like object229 # shouldn't be run anyway230 pass231 def __call__(self, result):232 return self.run(result)233 def countTestCases(self):234 return 0235def _isnotsuite(test):236 "A crude way to tell apart testcases and suites with duck-typing"237 try:238 iter(test)239 except TypeError:240 return True241 return False242class _DebugResult(object):243 "Used by the TestSuite to hold previous class when running in debug."244 _previousTestClass = None245 _moduleSetUpFailed = False...
uio_test.py
Source:uio_test.py
...22 pass23 def _grabStdOut(self):24 self._orgStdout = sys.stdout25 sys.stdout = open(UIOTester.TMP_FILE, 'w')26 def _restoreStdout(self):27 sys.stdout.close()28 sys.stdout = self._orgStdout29 def _grabStdIn(self):30 self._orgStdin = sys.stdin31 sys.stdin = open(UIOTester.TMP_FILE, 'r')32 def _setTmpText(self, text):33 fd = open(UIOTester.TMP_FILE, 'w')34 fd.write(text)35 fd.close()36 def _restoreStdin(self):37 sys.stdin.close()38 sys.stdin = self._orgStdin39 def test0_info(self):40 self._uio = UIO(debug=True, colour=True)41 self._uio.info("An info level message")42 self._uio.warn("An warn level message")43 self._uio.error("An error level message")44 self._uio.debug("An debug level message")45 def test1_info(self):46 self._grabStdOut()47 self._uio.info("An info level message")48 self._restoreStdout()49 lines = UIOTester.GetStdoutLines()50 self.assertTrue(len(lines) == 1)51 self.assertTrue( lines[0] == "INFO: An info level message\n")52 def test2_warn(self):53 self._grabStdOut()54 self._uio.warn("An warn level message")55 self._restoreStdout()56 lines = UIOTester.GetStdoutLines()57 self.assertTrue(len(lines) == 1)58 self.assertTrue( lines[0] == "WARN: An warn level message\n")59 def test3_error(self):60 self._grabStdOut()61 self._uio.error("An error level message")62 self._restoreStdout()63 lines = UIOTester.GetStdoutLines()64 self.assertTrue(len(lines) == 1)65 self.assertTrue( lines[0] == "ERROR: An error level message\n")66 def test4_debugOff(self):67 self._grabStdOut()68 self._uio.enableDebug(False)69 self._uio.debug("An debug level message")70 self._restoreStdout()71 lines = UIOTester.GetStdoutLines()72 self.assertTrue(len(lines) == 0)73 def test5_debugOn(self):74 self._grabStdOut()75 self._uio.enableDebug(True)76 self._uio.debug("A debug level message")77 self._restoreStdout()78 lines = UIOTester.GetStdoutLines()79 self.assertTrue(len(lines) == 1)80 self.assertTrue(lines[0] == "DEBUG: A debug level message\n")81 def test6_getInput(self):82 self._setTmpText("0123456789\n")83 self._grabStdIn()84 self._uio.getInput("Enter a string")85 self._restoreStdin()86 lines = UIOTester.GetStdoutLines()87 self.assertTrue(len(lines) == 1)88 self.assertTrue(lines[0] == "0123456789\n")89 def test7_getBoolInput_y(self):90 self._setTmpText("y\n")91 self._grabStdIn()92 response = self._uio.getBoolInput("Enter y/n")93 self._restoreStdin()94 self.assertTrue( response )95 def test7_getBoolInput_n(self):96 self._setTmpText("n\n")97 self._grabStdIn()98 response = self._uio.getBoolInput("Enter y/n")99 self._restoreStdin()100 self.assertTrue( not response )101 def test8_getBoolInput_q(self, allowQuit=True):102 self._setTmpText("q\n")103 try:104 self._grabStdIn()105 self._uio.getBoolInput("Enter y/n or q")106 raise Exception("SystemExit not raised")107 except SystemExit:108 self._restoreStdin()109 def test9_errorException(self):110 self._uio.enableDebug(True)111 self._grabStdOut()112 try:113 raise Exception("An error occurred")114 except Exception:115 self._uio.errorException()116 self._restoreStdout()117 lines = UIOTester.GetStdoutLines()118 self.assertTrue(len(lines) == 5)119 self.assertTrue(lines[0] == "ERROR: Traceback (most recent call last):\n")120 #Not checking for exact text here as line numbers may change in uio.py as it's updated over time.121 self.assertTrue( lines[1].find("uio_test.py") != -1 and lines[1].endswith(", in test9_errorException\n") )122 self.assertTrue(lines[2] == "ERROR: raise Exception(\"An error occurred\")\n")123 self.assertTrue(lines[3] == "ERROR: Exception: An error occurred\n")124 self.assertTrue(lines[4] == "ERROR: \n")125 #!!! getPassword() not tested as redirect does not work.126def main():127 """@brief Unit tests for the UIO class"""128 suite = unittest.TestLoader().loadTestsFromTestCase(UIOTester)129 unittest.TextTestRunner(verbosity=2).run(suite)130if __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!!