Best Python code snippet using Testify_python
test_suite.py
Source:test_suite.py
1# -*- coding: utf-8 -*-2# Copyright (c) 2013-2014 Simon Jagoe3# All rights reserved.4#5# This software may be modified and distributed under the terms6# of the 3-clause BSD license. See the LICENSE.txt file for details.7from __future__ import absolute_import, unicode_literals8from contextlib import contextmanager9from itertools import count10import sys11from ._test_cases import TestCase12from ..result import ResultCollector13from ..suite import TestSuite, _TestSuiteState14from ..testing import unittest15class MockModule(object):16 def __init__(self, setup_raise=False, teardown_raise=False):17 self.setup = False18 self.teardown = False19 self.setup_raise = setup_raise20 self.teardown_raise = teardown_raise21class MockModuleSetup(MockModule):22 def setUpModule(self):23 self.setup = True24 if self.setup_raise:25 raise Exception('Error in setUpModule')26class MockModuleTeardown(MockModule):27 def tearDownModule(self):28 self.teardown = True29 if self.teardown_raise:30 raise Exception('Error in tearDownModule')31class MockModuleSetupTeardown(MockModuleSetup, MockModuleTeardown):32 pass33class MockTestCase(object):34 setup = False35 teardown = False36 setup_raise = False37 teardown_raise = False38 setup_count = 039 teardown_count = 040 def __init__(self):41 self.was_run = False42 @classmethod43 def reset(cls):44 cls.setup = False45 cls.teardown = False46 cls.setup_raise = False47 cls.teardown_raise = False48 cls.setup_count = 049 cls.teardown_count = 050 if hasattr(cls, '__unittest_skip__'):51 del cls.__unittest_skip__52 def run(self, result, _state=None):53 self.was_run = True54 return result55 def __call__(self, *args, **kwargs):56 return self.run(*args, **kwargs)57class MockTestCaseSetup(MockTestCase):58 @classmethod59 def setUpClass(cls):60 cls.setup = True61 cls.setup_count += 162 if cls.setup_raise:63 raise Exception('Error in setUpClass')64class MockTestCaseTeardown(MockTestCase):65 @classmethod66 def tearDownClass(cls):67 cls.teardown = True68 cls.teardown_count += 169 if cls.setup_raise:70 raise Exception('Error in tearDownClass')71class MockTestCaseSetupTeardown(MockTestCaseSetup, MockTestCaseTeardown):72 pass73class ResetClassStateMixin(object):74 def setUp(self):75 for klass in (MockTestCase, MockTestCaseSetup,76 MockTestCaseTeardown, MockTestCaseSetupTeardown):77 klass.reset()78 self.assertStateReset()79 def tearDown(self):80 for klass in (MockTestCase, MockTestCaseSetup,81 MockTestCaseTeardown, MockTestCaseSetupTeardown):82 klass.reset()83 self.assertStateReset()84 def assertStateReset(self):85 for klass in (MockTestCase, MockTestCaseSetup,86 MockTestCaseTeardown, MockTestCaseSetupTeardown):87 self.assertFalse(klass.setup)88 self.assertFalse(klass.teardown)89 self.assertFalse(klass.setup_raise)90 self.assertFalse(klass.teardown_raise)91 self.assertFalse(hasattr(klass, '__unittest_skip__'))92class TestTestSuiteState(ResetClassStateMixin, unittest.TestCase):93 def setUp(self):94 self.state = _TestSuiteState(ResultCollector())95 self._name_count = count(0)96 ResetClassStateMixin.setUp(self)97 def tearDown(self):98 ResetClassStateMixin.tearDown(self)99 del self.state100 def test_setup_none(self):101 self.assertTrue(self.state.setup(None))102 def test_teardown_no_prior_setup_does_not_raise(self):103 self.state.teardown()104 @contextmanager105 def _temporary_module(self, klass, module):106 module_name = 'haas_test_module_{0}'.format(next(self._name_count))107 self.assertNotIn(module_name, sys.modules)108 sys.modules[module_name] = module109 old_module = klass.__module__110 klass.__module__ = module_name111 try:112 yield113 finally:114 klass.__module__ = old_module115 del sys.modules[module_name]116 def _prepare_test(self, klass, module_factory, setup_raise,117 teardown_raise):118 klass.setup_raise = setup_raise119 klass.teardown_raise = teardown_raise120 test = klass()121 if module_factory is not None:122 module = module_factory(123 setup_raise=setup_raise,124 teardown_raise=teardown_raise,125 )126 else:127 module = None128 return test, module129 @contextmanager130 def _run_test_context(self, klass, module_factory, setup_raise,131 teardown_raise, class_setup, class_teardown,132 module_setup, module_teardown):133 test, module = self._prepare_test(134 klass, module_factory, setup_raise, teardown_raise)135 with self._temporary_module(klass, module):136 self.assertEqual(self.state.setup(test), not setup_raise)137 self.assertEqual(klass.setup, class_setup)138 self.assertFalse(klass.teardown)139 if module is not None:140 self.assertEqual(module.setup, module_setup)141 self.assertFalse(module.teardown)142 yield test143 self.state.teardown()144 self.assertEqual(klass.setup, class_setup)145 self.assertEqual(klass.teardown, class_teardown)146 if module is not None:147 self.assertEqual(module.setup, module_setup)148 self.assertEqual(module.teardown, module_teardown)149 def _run_test(self, klass, module_factory, setup_raise, teardown_raise,150 class_setup, class_teardown, module_setup, module_teardown):151 with self._run_test_context(152 klass, module_factory, setup_raise, teardown_raise,153 class_setup, class_teardown, module_setup, module_teardown):154 pass155 def test_call_setup_without_setup_or_teardown(self):156 self._run_test(157 klass=MockTestCase,158 module_factory=MockModule,159 setup_raise=False,160 teardown_raise=False,161 class_setup=False,162 class_teardown=False,163 module_setup=False,164 module_teardown=False,165 )166 def test_setup_skip(self):167 MockTestCaseSetupTeardown.__unittest_skip__ = True168 self._run_test(169 klass=MockTestCaseSetupTeardown,170 module_factory=MockModule,171 setup_raise=False,172 teardown_raise=False,173 class_setup=False,174 class_teardown=False,175 module_setup=False,176 module_teardown=False,177 )178 def test_setup_case_setup(self):179 self._run_test(180 klass=MockTestCaseSetup,181 module_factory=MockModule,182 setup_raise=False,183 teardown_raise=False,184 class_setup=True,185 class_teardown=False,186 module_setup=False,187 module_teardown=False,188 )189 def test_setup_case_teardown(self):190 self._run_test(191 klass=MockTestCaseTeardown,192 module_factory=MockModule,193 setup_raise=False,194 teardown_raise=False,195 class_setup=False,196 class_teardown=True,197 module_setup=False,198 module_teardown=False,199 )200 def test_setup_case_setup_and_teardown(self):201 self._run_test(202 klass=MockTestCaseSetupTeardown,203 module_factory=MockModule,204 setup_raise=False,205 teardown_raise=False,206 class_setup=True,207 class_teardown=True,208 module_setup=False,209 module_teardown=False,210 )211 def test_setup_case_setup_raises_and_teardown(self):212 self._run_test(213 klass=MockTestCaseSetupTeardown,214 module_factory=MockModule,215 setup_raise=True,216 teardown_raise=False,217 class_setup=True,218 class_teardown=False,219 module_setup=False,220 module_teardown=False,221 )222 def test_setup_case_setup_and_teardown_raises(self):223 self._run_test(224 klass=MockTestCaseSetupTeardown,225 module_factory=MockModule,226 setup_raise=False,227 teardown_raise=True,228 class_setup=True,229 class_teardown=True,230 module_setup=False,231 module_teardown=False,232 )233 def test_setup_module_setup(self):234 self._run_test(235 klass=MockTestCase,236 module_factory=MockModuleSetup,237 setup_raise=False,238 teardown_raise=False,239 class_setup=False,240 class_teardown=False,241 module_setup=True,242 module_teardown=False,243 )244 def test_setup_module_teardown(self):245 self._run_test(246 klass=MockTestCase,247 module_factory=MockModuleTeardown,248 setup_raise=False,249 teardown_raise=False,250 class_setup=False,251 class_teardown=False,252 module_setup=False,253 module_teardown=True,254 )255 def test_setup_module_setup_and_teardown(self):256 self._run_test(257 klass=MockTestCase,258 module_factory=MockModuleSetupTeardown,259 setup_raise=False,260 teardown_raise=False,261 class_setup=False,262 class_teardown=False,263 module_setup=True,264 module_teardown=True,265 )266 def test_setup_module_setup_raises_and_teardown(self):267 self._run_test(268 klass=MockTestCase,269 module_factory=MockModuleSetupTeardown,270 setup_raise=True,271 teardown_raise=False,272 class_setup=False,273 class_teardown=False,274 module_setup=True,275 module_teardown=False,276 )277 def test_setup_module_setup_and_teardown_raises(self):278 self._run_test(279 klass=MockTestCase,280 module_factory=MockModuleSetupTeardown,281 setup_raise=False,282 teardown_raise=True,283 class_setup=False,284 class_teardown=False,285 module_setup=True,286 module_teardown=True,287 )288 def test_setup_module_none(self):289 self._run_test(290 klass=MockTestCase,291 module_factory=None,292 setup_raise=False,293 teardown_raise=False,294 class_setup=False,295 class_teardown=False,296 module_setup=False,297 module_teardown=False,298 )299 def test_multiple_setup_teardown_different_class_module(self):300 with self._run_test_context(301 klass=MockTestCaseSetupTeardown,302 module_factory=MockModuleSetupTeardown,303 setup_raise=False,304 teardown_raise=False,305 class_setup=True,306 class_teardown=True,307 module_setup=True,308 module_teardown=True):309 klass = MockTestCaseSetup310 module_factory = MockModuleSetup311 setup_raise = False312 teardown_raise = False313 test, module = self._prepare_test(314 klass=klass,315 module_factory=module_factory,316 setup_raise=setup_raise,317 teardown_raise=teardown_raise,318 )319 with self._temporary_module(klass, module):320 self.assertEqual(self.state.setup(test), not setup_raise)321 self.assertTrue(klass.setup)322 self.assertFalse(klass.teardown)323 self.assertTrue(module.setup)324 self.assertFalse(module.teardown)325 # Top-level tear down has occurred326 self.assertTrue(klass.setup)327 self.assertFalse(klass.teardown)328 self.assertTrue(module.setup)329 self.assertFalse(module.teardown)330 def test_multiple_setup_teardown_same_class_module(self):331 with self._run_test_context(332 klass=MockTestCaseSetupTeardown,333 module_factory=MockModuleSetupTeardown,334 setup_raise=False,335 teardown_raise=False,336 class_setup=True,337 class_teardown=True,338 module_setup=True,339 module_teardown=True) as first_test:340 klass = MockTestCaseSetupTeardown341 setup_raise = False342 teardown_raise = False343 test, _ = self._prepare_test(344 klass=klass,345 module_factory=None,346 setup_raise=setup_raise,347 teardown_raise=teardown_raise,348 )349 module_name = first_test.__class__.__module__350 module = sys.modules[module_name]351 self.assertEqual(self.state.setup(test), not setup_raise)352 self.assertTrue(klass.setup)353 self.assertFalse(klass.teardown)354 self.assertTrue(module.setup)355 self.assertFalse(module.teardown)356 # Top-level tear down has occurred357 self.assertTrue(klass.setup)358 self.assertTrue(klass.teardown)359 self.assertTrue(module.setup)360 self.assertTrue(module.teardown)361class TestTestSuiteCount(unittest.TestCase):362 def test_count_empty(self):363 suite = TestSuite()364 self.assertEqual(suite.countTestCases(), 0)365 def test_one_level(self):366 suite = TestSuite(tests=[TestCase('test_method'), TestSuite()])367 self.assertEqual(suite.countTestCases(), 1)368 def test_suite_not_included_in_count(self):369 suite = TestSuite(370 tests=[371 TestSuite(tests=[TestSuite(), TestSuite(), TestSuite()]),372 TestSuite(),373 TestSuite(),374 ],375 )376 self.assertEqual(suite.countTestCases(), 0)377 def test_cases_included_in_count(self):378 suite = TestSuite(379 tests=[380 TestSuite(381 tests=[382 TestCase('test_method'),383 TestSuite(),384 TestSuite(),385 ],386 ),387 TestCase('test_method'),388 TestSuite(),389 ],390 )391 self.assertEqual(suite.countTestCases(), 2)392class TestTestSuiteEquality(unittest.TestCase):393 def test_equal_to_itself_empty(self):394 suite = TestSuite()395 self.assertEqual(suite, suite)396 def test_not_equal_to_empty_list(self):397 suite = TestSuite()398 self.assertNotEqual(suite, [])399 def test_equal_to_itself_nested(self):400 suite = TestSuite(401 tests=[402 TestSuite(403 tests=[404 TestCase('test_method'),405 TestSuite(),406 TestSuite(),407 ],408 ),409 TestCase('test_method'),410 TestSuite(),411 ],412 )413 self.assertEqual(suite, suite)414 def test_equal_to_other_nested(self):415 suite = TestSuite(416 tests=[417 TestSuite(418 tests=[419 TestCase('test_method'),420 TestSuite(),421 TestSuite(),422 ],423 ),424 TestCase('test_method'),425 TestSuite(),426 ],427 )428 suite2 = TestSuite(429 tests=[430 TestSuite(431 tests=[432 TestCase('test_method'),433 TestSuite(),434 TestSuite(),435 ],436 ),437 TestCase('test_method'),438 TestSuite(),439 ],440 )441 self.assertEqual(suite, suite2)442class TestRunningTestSuite(ResetClassStateMixin, unittest.TestCase):443 def setUp(self):444 ResetClassStateMixin.setUp(self)445 self.case_1 = MockTestCaseSetupTeardown()446 self.case_2 = MockTestCase()447 self.suite = TestSuite(448 tests=[449 TestSuite(450 tests=[451 self.case_1,452 TestSuite(),453 TestSuite(),454 ],455 ),456 self.case_2,457 TestSuite(),458 ],459 )460 def tearDown(self):461 del self.suite462 del self.case_1463 del self.case_2464 ResetClassStateMixin.tearDown(self)465 def test_run_suite_run(self):466 result = ResultCollector()467 returned_result = self.suite.run(result)468 self.assertIs(result, returned_result)469 self.assertTrue(self.case_1.was_run)470 self.assertTrue(self.case_2.was_run)471 def test_run_suite_call(self):472 result = ResultCollector()473 returned_result = self.suite(result)474 self.assertIs(result, returned_result)475 self.assertTrue(self.case_1.was_run)476 self.assertTrue(self.case_2.was_run)477 def test_run_suite_setup_error(self):478 self.case_1.__class__.setup_raise = True479 result = ResultCollector()480 returned_result = self.suite.run(result)481 self.assertIs(result, returned_result)482 self.assertFalse(self.case_1.was_run)483 self.assertTrue(self.case_2.was_run)484 def test_same_class_multiple_suites(self):485 case_1 = MockTestCaseSetupTeardown()486 case_2 = MockTestCaseSetupTeardown()487 suite = TestSuite(488 tests=[489 TestSuite(490 tests=[491 case_1,492 ],493 ),494 TestSuite(495 tests=[496 case_2,497 ],498 ),499 ],500 )501 result = ResultCollector()502 suite.run(result)503 self.assertEqual(MockTestCaseSetupTeardown.setup_count, 1)...
test.py
Source:test.py
1# Library import2import unittest3import importlib4# Project imports5import sigbox6class TestClass(sigbox.SignalBoxClass):7 def __init__(self):8 super().__init__(["apple", "banana", "cherry"])9 @sigbox.SignalDecorator("apple")10 def apple(self, val):11 return val12 @sigbox.SignalDecorator()13 def banana(self, val):14 return val15 def cherry(self, val):16 self.signals.trigger("cherry", {"cherry": val*2})17 return val18class Testing(unittest.TestCase):19 def setUp(self) -> None:20 importlib.reload(sigbox)21 self.sigbox = sigbox.SigBox()22 self.callback_result = []23 def tearDown(self) -> None:24 pass25 def callback(self, data):26 self.callback_result.append(data)27 def test_dual_signal_box(self):28 """29 Test docstring30 """31 def callback(data):32 pass33 sb1 = sigbox.SignalBox()34 sb1.add("box1_sig1")35 sb1.add("box1_sig2")36 sb1.bind("box1_sig1", self.callback)37 sb1.bind("box1_sig2", self.callback)38 sb1.trigger("box1_sig1", {"fruit": "orange"})39 sb1.trigger("box1_sig2", {"fruit": "apple"})40 sb2 = sigbox.SignalBox()41 sb2.add("box2_sig1")42 sb2.add("box2_sig2")43 sb2.bind("box2_sig1", self.callback)44 sb2.bind("box2_sig2", self.callback)45 sb2.trigger("box2_sig1", {"fruit": "pear"})46 sb2.trigger("box2_sig2", {"fruit": "kiwi"})47 self.sigbox.pump()48 check = {"box1_sig1": "orange",49 "box1_sig2": "apple",50 "box2_sig1": "pear",51 "box2_sig2": "kiwi"}52 results = {data.signal.name: data.fruit for data in self.callback_result}53 self.assertDictEqual(check, results)54 def class_setUp(self):55 self.tc1 = TestClass()56 self.tc1.signals.bind("apple", self.callback)57 self.tc1.signals.bind("banana", self.callback)58 self.tc1.signals.bind("cherry", self.callback)59 self.tc2 = TestClass()60 self.tc2.signals.bind("apple", self.callback)61 self.tc2.signals.bind("banana", self.callback)62 self.tc2.signals.bind("cherry", self.callback)63 def class_tearDown(self):64 self.tc1 = None65 self.tc2 = None66 def test_class_decorator_named(self):67 self.class_setUp()68 self.tc1.apple(10)69 self.tc2.apple(20)70 self.sigbox.pump()71 check = {hash(self.tc1.signals): 10, hash(self.tc2.signals): 20}72 results = {}73 for data in self.callback_result:74 results[hash(data.signal.signal_box)] = data.decorator_return75 self.class_tearDown()76 self.assertDictEqual(check, results)77 def test_class_decorator_unnamed(self):78 self.class_setUp()79 self.tc1.banana(11)80 self.tc2.banana(22)81 self.sigbox.pump()82 check = {hash(self.tc1.signals): 11, hash(self.tc2.signals): 22}83 results = {}84 for data in self.callback_result:85 results[hash(data.signal.signal_box)] = data.decorator_return86 self.class_tearDown()87 self.assertDictEqual(check, results)88 def test_class_manual(self):89 self.class_setUp()90 self.tc1.cherry(3)91 self.tc2.cherry(7)92 self.sigbox.pump()93 check = {hash(self.tc1.signals): 6, hash(self.tc2.signals): 14}94 results = {}95 for data in self.callback_result:96 results[hash(data.signal.signal_box)] = data.cherry97 self.class_tearDown()...
testing.py
Source:testing.py
...50 except AssertionError:51 print("--> " + string.colored(f"Test {method.__name__}() failed!", "bright_red"))52 print(string.colored(traceback.format_exc(), "bright_red"))53 except BaseException:54 self.class_teardown()55 raise56 finally:57 self.each_teardown()58 def __call__(self, method):59 print(f"Run test class {method.__name__}:")60 self.class_setup()61 obj = method()62 for test_method_name in [m for m in dir(obj) if m.startswith("test_")]:63 self.do_test(getattr(obj, test_method_name))64 self.class_teardown()65class test_must_except():66 """67 Use a with statement to run a block of code that must raise an exception.68 The exception must be of the specified type.969 """70 def __init__(self, exception_type: Type[Exception]):71 self.exception_type = exception_type72 def __enter__(self):73 pass74 def __exit__(self, exc_type, exc_value, traceback):75 if not exc_type:76 raise TypeError(f"Expected an exception of type {self.exception_type}")77 if not issubclass(exc_type, self.exception_type):78 raise TypeError(f"Expected an exception of type {self.exception_type}, got {exc_type}")...
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!!