Python unittest.TestCase() Examples

The following are 50 code examples for showing how to use unittest.TestCase(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: core-framework   Author: RedhawkSDR   File: unit_test_helpers.py    (license) View Source Project 10 votes vote down vote up
def runTests(self):
        # Setup some globals to pass to the TestCase
        global SOFT_PKG
        global IMPL_ID
        SOFT_PKG = self.spd_file
        spd = SPDParser.parse(self.spd_file)
        
        if self.testRunner is None:
            try:
                import xmlrunner
                self.testRunner = xmlrunner.XMLTestRunner(verbosity=self.verbosity)
            except ImportError:
                self.testRunner = unittest.TextTestRunner(verbosity=self.verbosity)
        
        for implementation in spd.get_implementation():
            IMPL_ID = implementation.get_id()
            if IMPL_ID == self.impl or self.impl is None:
                result = self.testRunner.run(self.test)
                self.results.append(result)
        #sys.exit(not result.wasSuccessful()) 
Example 2
Project: django-performance-testing   Author: PaesslerAG   File: test_worst_report_integrates_with_django_testrunner.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 6 votes vote down vote up
def packaged_runner(db):
    class SampleTestCase(unittest.TestCase):

        def test_whatever_one(self):
            results_collected.send(
                sender=WithId('whatever'), results=[1],
                context={'test': 'one'})

        def test_whatever_two(self):
            results_collected.send(
                sender=WithId('whatever'), results=[2],
                context={'test': 'two'})

        def test_slow_query(self):
            list(Group.objects.all())

    def get_packaged_runner_with_options(options=None):
        options = options or {}
        return run_testcases_with_django_runner(SampleTestCase, nr_of_tests=3,
                                                runner_options=options)
    return get_packaged_runner_with_options 
Example 3
Project: django-override-storage   Author: danifus   File: compat.py    (MIT License) View Source Project 6 votes vote down vote up
def decorate_class(self, cls):
        if issubclass(cls, TestCase):
            decorated_setUp = cls.setUp
            decorated_tearDown = cls.tearDown

            def setUp(inner_self):
                context = self.enable()
                if self.attr_name:
                    setattr(inner_self, self.attr_name, context)
                decorated_setUp(inner_self)

            def tearDown(inner_self):
                decorated_tearDown(inner_self)
                self.disable()

            cls.setUp = setUp
            cls.tearDown = tearDown
            return cls
        raise TypeError('Can only decorate subclasses of unittest.TestCase') 
Example 4
Project: core-framework   Author: RedhawkSDR   File: runtests.py    (license) View Source Project 6 votes vote down vote up
def loadTestsFromTestCase(self, testCaseClass):
        """Return a suite of all tests cases contained in testCaseClass"""
        if issubclass(testCaseClass, unittest.TestSuite):
            raise TypeError("Test cases should not be derived from TestSuite. Maybe you meant to derive from TestCase?")
        testCaseNames = self.getTestCaseNames(testCaseClass)
        if not testCaseNames and hasattr(testCaseClass, 'runTest'):
            testCaseNames = ['runTest']
        if self.PROMPT:
            ans = raw_input("Would you like to execute all tests in %s [Y]/N? " % testCaseClass).upper()
            if ans == "N":
                testCaseNamesToRun = []
                for name in testCaseNames:
                    ans = raw_input("Would you like to execute test %s [Y]/N? " % name).upper()
                    if ans == "N":
                        continue
                    else:
                        testCaseNamesToRun.append(name)
                testCaseNames = testCaseNamesToRun

        return self.suiteClass(map(testCaseClass, testCaseNames)) 
Example 5
Project: core-framework   Author: RedhawkSDR   File: scatest.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, methodName='runTest', orbArgs=[]):
        unittest.TestCase.__init__(self, methodName)
        args = sys.argv
        self.debuglevel = 3
        for arg in args:
            if '--debuglevel' in arg:
                self.debuglevel = arg.split('=')[-1]
        self._orb = CORBA.ORB_init(sys.argv + orbArgs, CORBA.ORB_ID)
        self._poa = self._orb.resolve_initial_references("RootPOA")
        self._poa._get_the_POAManager().activate()
        self._ns = self._orb.resolve_initial_references("NameService")
        self._root = self._ns._narrow(CosNaming.NamingContext)

        # Maintain a registry of the DomainManager (there should normally be just one)
        # and all spawned DeviceManagers, for easy cleanup.
        self._domainBooter = None
        self._domainManager = None

        self._deviceLock = threading.Lock()
        self._deviceBooters = []
        self._deviceManagers = []
        self._execparams = "" 
Example 6
Project: core-framework   Author: RedhawkSDR   File: rhunittest.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, methodName):
        # Pass the method name unmodified to the base class; this ensures that
        # when run in Eclipse's PyDev, the implementation shows up next to the
        # test name. This also means that __getattr__ must be overridden to
        # find the original method.
        unittest.TestCase.__init__(self, methodName)

        # Save the implementation so that it is available in setUp().
        # NOTE: Using type() ensures that the correct class object is queried,
        # so the implementation list is correct--a static call via RHTestCase
        # always returns an un-mangled name.
        name, impl = type(self).splitImpl(methodName)
        if not impl:
            # This should only occur with a single implementation, where name
            # mangling is disabled.
            self.impl = self.__impls__[0]
        else:
            self.impl = impl 
Example 7
Project: core-framework   Author: RedhawkSDR   File: rhunittest.py    (license) View Source Project 6 votes vote down vote up
def __getattr__(self, name):
        # Regular lookup failed, so split off the implementation and try the
        # base name. If it still doesn't exist, __getattribute__ will throw an
        # AttributeError, so it won't get stuck in infinite recursion.
        # NOTE: Using type() ensures that the correct class object is queried,
        # so the implementation list is correct--a static call via RHTestCase
        # always returns an un-mangled name.
        base, impl = type(self).splitImpl(name)
        return unittest.TestCase.__getattribute__(self, base) 
Example 8
Project: core-framework   Author: RedhawkSDR   File: test_python_multiout.py    (license) View Source Project 6 votes vote down vote up
def __init__(
            self,
            methodName='runTest',
            ptype='Int8',
            cname=None,
            srcData=None,
            cmpData=None,
            bio_in_module=bulkio.InCharPort,
            bio_out_module=bulkio.OutCharPort ):
        unittest.TestCase.__init__(self, methodName)
        self.c_dir = 'components'
        self.c_name = cname
        self.ptype = ptype
        self.execparams = {}
        self.c_inport = None
        self.c_outport = None
        self.sink_inport = None
        self.srcData = srcData
        self.cmpData = cmpData
        self.ctx = dict().fromkeys(BaseMultiOut.KEYS)
        self.bio_in_module = bio_in_module
        self.bio_out_module = bio_out_module 
Example 9
Project: core-framework   Author: RedhawkSDR   File: test_short.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, methodName='runTest'):
        unittest.TestCase.__init__(self, methodName)
        ##self.cname = 'CPP_Ports'
        ##self.ptype = 'Int8'
        self.inport = None
        self.outport = None
        self.sink_port_name = None
        self.ctx = dict().fromkeys(BaseVectorPort.KEYS)
        self.setContext() 
Example 10
Project: core-framework   Author: RedhawkSDR   File: test_python_multiout.py    (license) View Source Project 6 votes vote down vote up
def __init__(
            self,
            methodName='runTest',
            ptype='Int8',
            cname=None,
            srcData=None,
            cmpData=None,
            bio_in_module=bulkio.InCharPort,
            bio_out_module=bulkio.OutCharPort ):
        unittest.TestCase.__init__(self, methodName)
        self.c_dir = 'components'
        self.c_name = cname
        self.ptype = ptype
        self.execparams = {}
        self.c_inport = None
        self.c_outport = None
        self.sink_inport = None
        self.srcData = srcData
        self.cmpData = cmpData
        self.ctx = dict().fromkeys(BaseMultiOut.KEYS)
        self.bio_in_module = bio_in_module
        self.bio_out_module = bio_out_module 
Example 11
Project: core-framework   Author: RedhawkSDR   File: base_ports.py    (license) View Source Project 6 votes vote down vote up
def __init__(
            self,
            methodName='runTest',
            ptype='Int8',
            cname=None,
            srcData=None,
            cmpData=None,
            bio_in_module=bulkio.InCharPort,
            bio_out_module=bulkio.OutCharPort ):
        unittest.TestCase.__init__(self, methodName)
        self.c_dir = 'components'
        self.c_name = cname
        self.ptype = ptype
        self.execparams = {}
        self.c_inport = None
        self.c_outport = None
        self.sink_inport = None
        self.srcData = srcData
        self.cmpData = cmpData
        self.ctx = dict().fromkeys(BaseVectorPort.KEYS)
        self.bio_in_module = bio_in_module
        self.bio_out_module = bio_out_module 
Example 12
Project: spoon   Author: SpamExperts   File: test_server.py    (GNU General Public License v2.0) View Source Project 6 votes vote down vote up
def setUp(self):
        unittest.TestCase.setUp(self)
        self.mock_socket = patch("spoon.server.socket", create=True).start()
        self.mock_sock = patch("spoon.server.TCPSpork.socket",
                               create=True).start()
        # self.mock_forever = patch(
        #     "spoon.server.TCPSpork.serve_forever").start()
        self.mock_kill = patch("spoon.server.os.kill", create=True).start()
        patch("spoon.server.socketserver").start()
        patch("spoon.server._eintr_retry").start()
        self.mock_bind = patch("spoon.server.TCPSpork.server_bind").start()
        self.mock_active = patch(
            "spoon.server.TCPSpork.server_activate").start()
        self.mock_signal = patch("spoon.server.signal.signal",
                                 create=True).start()
        self.mock_thread = patch("spoon.server.threading.Thread").start()
        self.mock_fork = patch("spoon.server.os.fork", create=True).start() 
Example 13
Project: speccer   Author: bensimner   File: pset.py    (MIT License) View Source Project 6 votes vote down vote up
def unittest_wrapper(depth):
    def _wrapper(pset):
        class NewPSet(pset, unittest.TestCase):
            pass

        for p in NewPSet.__properties__:
            def _f(self, p=p):
                self.depth = depth
                out = speccer.spec(depth, getattr(self, p), output=False)
                # raise other exceptions out
                if isinstance(out, speccer.UnrelatedException):
                    raise out.reason

                self.assertIsInstance(out, speccer.clauses.Success)

            setattr(NewPSet, 'test_{}'.format(p), _f)

        NewPSet.__name__ = pset.__name__
        NewPSet.__qualname__ = pset.__qualname__
        NewPSet.__module__ = pset.__module__
        return NewPSet
    return _wrapper 
Example 14
Project: Projects   Author: it2school   File: pixelcopy_test.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, *args, **kwds):
        import numpy

        self.dst_types = [numpy.uint8, numpy.uint16, numpy.uint32]
        try:
            self.dst_types.append(numpy.uint64)
        except AttributeError:
            pass
        pygame.display.init()
        try:
            unittest.TestCase.__init__(self, *args, **kwds)
            self.sources = [self._make_src_surface(8),
                            self._make_src_surface(16),
                            self._make_src_surface(16, srcalpha=True),
                            self._make_src_surface(24),
                            self._make_src_surface(32),
                            self._make_src_surface(32, srcalpha=True)]
        finally:
            pygame.display.quit() 
Example 15
Project: functest   Author: opnfv   File: test_odl.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def _test_multiple_suites(self, suites,
                              status=testcase.TestCase.EX_OK, **kwargs):
        odlip = kwargs['odlip'] if 'odlip' in kwargs else '127.0.0.3'
        odlwebport = kwargs['odlwebport'] if 'odlwebport' in kwargs else '8080'
        odlrestconfport = (kwargs['odlrestconfport']
                           if 'odlrestconfport' in kwargs else '8181')
        with mock.patch('functest.utils.openstack_utils.get_endpoint',
                        return_value=ODLTesting._neutron_url):
            self.test.run_suites = mock.Mock(return_value=status)
            self.assertEqual(self.test.run(suites=suites), status)
            self.test.run_suites.assert_called_once_with(
                suites,
                neutronurl=self._neutron_url,
                odlip=odlip, odlpassword=self._odl_password,
                odlrestconfport=odlrestconfport,
                odlusername=self._odl_username, odlwebport=odlwebport,
                osauthurl=self._os_auth_url,
                ospassword=self._os_password,
                osprojectname=self._os_projectname,
                osusername=self._os_username,
                osprojectdomainname=self._os_projectdomainname,
                osuserdomainname=self._os_userdomainname) 
Example 16
Project: functest   Author: opnfv   File: test_robotframework.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def test_ok(self):
        data = {'name': 'foo',
                'parent': 'bar',
                'status': 'PASS',
                'starttime': "20161216 16:00:00.000",
                'endtime': "20161216 16:00:01.000",
                'elapsedtime': 1000,
                'text': 'Hello, World!',
                'critical': True}
        test = model.TestCase(
            name=data['name'], status=data['status'], message=data['text'],
            starttime=data['starttime'], endtime=data['endtime'])
        test.parent = mock.Mock()
        config = {'name': data['parent'],
                  'criticality.test_is_critical.return_value': data[
                      'critical']}
        test.parent.configure_mock(**config)
        self.visitor.visit_test(test)
        self.assertEqual(self.visitor.get_data(), [data]) 
Example 17
Project: functest   Author: opnfv   File: test_vping.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def test_vping_userdata(self, deploy_vm, path_exists, create_flavor,
                            get_port_ip, vm_active):
        with mock.patch('snaps.openstack.utils.deploy_utils.create_image',
                        return_value=OpenStackImage(self.os_creds, None)), \
                mock.patch('snaps.openstack.utils.deploy_utils.create_network',
                           return_value=OpenStackNetwork(
                               self.os_creds, NetworkConfig(name='foo'))), \
                mock.patch('snaps.openstack.utils.deploy_utils.'
                           'create_vm_instance',
                           return_value=OpenStackVmInstance(
                               self.os_creds,
                               VmInstanceConfig(
                                   name='foo', flavor='bar',
                                   port_settings=[PortConfig(
                                       name='foo', network_name='bar')]),
                               None)), \
                mock.patch('snaps.openstack.create_instance.'
                           'OpenStackVmInstance.get_console_output',
                           return_value='vPing OK'):
            self.assertEquals(TestCase.EX_OK, self.vping_userdata.run()) 
Example 18
Project: CodingDojo   Author: ComputerSocietyUNB   File: testcases.py    (license) View Source Project 6 votes vote down vote up
def setUpClass(cls):
        super(TestCase, cls).setUpClass()
        if not connections_support_transactions():
            return
        cls.cls_atomics = cls._enter_atomics()

        if cls.fixtures:
            for db_name in cls._databases_names(include_mirrors=False):
                    try:
                        call_command('loaddata', *cls.fixtures, **{
                            'verbosity': 0,
                            'commit': False,
                            'database': db_name,
                        })
                    except Exception:
                        cls._rollback_atomics(cls.cls_atomics)
                        raise
        try:
            cls.setUpTestData()
        except Exception:
            cls._rollback_atomics(cls.cls_atomics)
            raise 
Example 19
Project: CodingDojo   Author: ComputerSocietyUNB   File: testcases.py    (license) View Source Project 6 votes vote down vote up
def _deferredSkip(condition, reason):
    def decorator(test_func):
        if not (isinstance(test_func, type) and
                issubclass(test_func, unittest.TestCase)):
            @wraps(test_func)
            def skip_wrapper(*args, **kwargs):
                if condition():
                    raise unittest.SkipTest(reason)
                return test_func(*args, **kwargs)
            test_item = skip_wrapper
        else:
            # Assume a class is decorated
            test_item = test_func
            test_item.__unittest_skip__ = CheckCondition(condition)
        test_item.__unittest_skip_why__ = reason
        return test_item
    return decorator 
Example 20
Project: hostapd-mana   Author: adde88   File: test_result.py    (license) View Source Project 6 votes vote down vote up
def test_startTest(self):
        class Foo(unittest.TestCase):
            def test_1(self):
                pass

        test = Foo('test_1')

        result = unittest.TestResult()

        result.startTest(test)

        self.assertTrue(result.wasSuccessful())
        self.assertEqual(len(result.errors), 0)
        self.assertEqual(len(result.failures), 0)
        self.assertEqual(result.testsRun, 1)
        self.assertEqual(result.shouldStop, False)

        result.stopTest(test)

    # "Called after the test case test has been executed, regardless of
    # the outcome. The default implementation does nothing." 
Example 21
Project: hostapd-mana   Author: adde88   File: test_result.py    (license) View Source Project 6 votes vote down vote up
def test_startTestRun_stopTestRun(self):
        result = unittest.TestResult()
        result.startTestRun()
        result.stopTestRun()

    # "addSuccess(test)"
    # ...
    # "Called when the test case test succeeds"
    # ...
    # "wasSuccessful() - Returns True if all tests run so far have passed,
    # otherwise returns False"
    # ...
    # "testsRun - The total number of tests run so far."
    # ...
    # "errors - A list containing 2-tuples of TestCase instances and
    # formatted tracebacks. Each tuple represents a test which raised an
    # unexpected exception. Contains formatted
    # tracebacks instead of sys.exc_info() results."
    # ...
    # "failures - A list containing 2-tuples of TestCase instances and
    # formatted tracebacks. Each tuple represents a test where a failure was
    # explicitly signalled using the TestCase.fail*() or TestCase.assert*()
    # methods. Contains formatted tracebacks instead
    # of sys.exc_info() results." 
Example 22
Project: hostapd-mana   Author: adde88   File: test_result.py    (license) View Source Project 6 votes vote down vote up
def testOldTestResult(self):
        class Test(unittest.TestCase):
            def testSkip(self):
                self.skipTest('foobar')
            @unittest.expectedFailure
            def testExpectedFail(self):
                raise TypeError
            @unittest.expectedFailure
            def testUnexpectedSuccess(self):
                pass

        for test_name, should_pass in (('testSkip', True),
                                       ('testExpectedFail', True),
                                       ('testUnexpectedSuccess', False)):
            test = Test(test_name)
            self.assertOldResultWarning(test, int(not should_pass)) 
Example 23
Project: hostapd-mana   Author: adde88   File: test_result.py    (license) View Source Project 6 votes vote down vote up
def testBufferSetUpModule(self):
        result = unittest.TestResult()
        result.buffer = True

        class Foo(unittest.TestCase):
            def test_foo(self):
                pass
        class Module(object):
            @staticmethod
            def setUpModule():
                1//0

        Foo.__module__ = 'Module'
        sys.modules['Module'] = Module
        self.addCleanup(sys.modules.pop, 'Module')
        suite = unittest.TestSuite([Foo('test_foo')])
        suite(result)
        self.assertEqual(len(result.errors), 1) 
Example 24
Project: hostapd-mana   Author: adde88   File: test_result.py    (license) View Source Project 6 votes vote down vote up
def testBufferTearDownModule(self):
        result = unittest.TestResult()
        result.buffer = True

        class Foo(unittest.TestCase):
            def test_foo(self):
                pass
        class Module(object):
            @staticmethod
            def tearDownModule():
                1//0

        Foo.__module__ = 'Module'
        sys.modules['Module'] = Module
        self.addCleanup(sys.modules.pop, 'Module')
        suite = unittest.TestSuite([Foo('test_foo')])
        suite(result)
        self.assertEqual(len(result.errors), 1) 
Example 25
Project: hostapd-mana   Author: adde88   File: test_skipping.py    (license) View Source Project 6 votes vote down vote up
def test_skipping(self):
        class Foo(unittest.TestCase):
            def test_skip_me(self):
                self.skipTest("skip")
        events = []
        result = LoggingResult(events)
        test = Foo("test_skip_me")
        test.run(result)
        self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
        self.assertEqual(result.skipped, [(test, "skip")])

        # Try letting setUp skip the test now.
        class Foo(unittest.TestCase):
            def setUp(self):
                self.skipTest("testing")
            def test_nothing(self): pass
        events = []
        result = LoggingResult(events)
        test = Foo("test_nothing")
        test.run(result)
        self.assertEqual(events, ['startTest', 'addSkip', 'stopTest'])
        self.assertEqual(result.skipped, [(test, "testing")])
        self.assertEqual(result.testsRun, 1) 
Example 26
Project: hostapd-mana   Author: adde88   File: test_skipping.py    (license) View Source Project 6 votes vote down vote up
def test_skipping_decorators(self):
        op_table = ((unittest.skipUnless, False, True),
                    (unittest.skipIf, True, False))
        for deco, do_skip, dont_skip in op_table:
            class Foo(unittest.TestCase):
                @deco(do_skip, "testing")
                def test_skip(self): pass

                @deco(dont_skip, "testing")
                def test_dont_skip(self): pass
            test_do_skip = Foo("test_skip")
            test_dont_skip = Foo("test_dont_skip")
            suite = unittest.TestSuite([test_do_skip, test_dont_skip])
            events = []
            result = LoggingResult(events)
            suite.run(result)
            self.assertEqual(len(result.skipped), 1)
            expected = ['startTest', 'addSkip', 'stopTest',
                        'startTest', 'addSuccess', 'stopTest']
            self.assertEqual(events, expected)
            self.assertEqual(result.testsRun, 2)
            self.assertEqual(result.skipped, [(test_do_skip, "testing")])
            self.assertTrue(result.wasSuccessful()) 
Example 27
Project: hostapd-mana   Author: adde88   File: test_skipping.py    (license) View Source Project 6 votes vote down vote up
def test_skip_doesnt_run_setup(self):
        class Foo(unittest.TestCase):
            wasSetUp = False
            wasTornDown = False
            def setUp(self):
                Foo.wasSetUp = True
            def tornDown(self):
                Foo.wasTornDown = True
            @unittest.skip('testing')
            def test_1(self):
                pass

        result = unittest.TestResult()
        test = Foo("test_1")
        suite = unittest.TestSuite([test])
        suite.run(result)
        self.assertEqual(result.skipped, [(test, "testing")])
        self.assertFalse(Foo.wasSetUp)
        self.assertFalse(Foo.wasTornDown) 
Example 28
Project: hostapd-mana   Author: adde88   File: test_skipping.py    (license) View Source Project 6 votes vote down vote up
def test_decorated_skip(self):
        def decorator(func):
            def inner(*a):
                return func(*a)
            return inner

        class Foo(unittest.TestCase):
            @decorator
            @unittest.skip('testing')
            def test_1(self):
                pass

        result = unittest.TestResult()
        test = Foo("test_1")
        suite = unittest.TestSuite([test])
        suite.run(result)
        self.assertEqual(result.skipped, [(test, "testing")]) 
Example 29
Project: hostapd-mana   Author: adde88   File: test_runner.py    (license) View Source Project 6 votes vote down vote up
def testTestCaseDebugExecutesCleanups(self):
        ordering = []

        class TestableTest(unittest.TestCase):
            def setUp(self):
                ordering.append('setUp')
                self.addCleanup(cleanup1)

            def testNothing(self):
                ordering.append('test')

            def tearDown(self):
                ordering.append('tearDown')

        test = TestableTest('testNothing')

        def cleanup1():
            ordering.append('cleanup1')
            test.addCleanup(cleanup2)
        def cleanup2():
            ordering.append('cleanup2')

        test.debug()
        self.assertEqual(ordering, ['setUp', 'test', 'tearDown', 'cleanup1', 'cleanup2']) 
Example 30
Project: hostapd-mana   Author: adde88   File: test_runner.py    (license) View Source Project 6 votes vote down vote up
def testRunnerRegistersResult(self):
        class Test(unittest.TestCase):
            def testFoo(self):
                pass
        originalRegisterResult = unittest.runner.registerResult
        def cleanup():
            unittest.runner.registerResult = originalRegisterResult
        self.addCleanup(cleanup)

        result = unittest.TestResult()
        runner = unittest.TextTestRunner(stream=StringIO())
        # Use our result object
        runner._makeResult = lambda: result

        self.wasRegistered = 0
        def fakeRegisterResult(thisResult):
            self.wasRegistered += 1
            self.assertEqual(thisResult, result)
        unittest.runner.registerResult = fakeRegisterResult

        runner.run(unittest.TestSuite())
        self.assertEqual(self.wasRegistered, 1) 
Example 31
Project: hostapd-mana   Author: adde88   File: test_setups.py    (license) View Source Project 6 votes vote down vote up
def test_setup_class(self):
        class Test(unittest.TestCase):
            setUpCalled = 0
            @classmethod
            def setUpClass(cls):
                Test.setUpCalled += 1
                unittest.TestCase.setUpClass()
            def test_one(self):
                pass
            def test_two(self):
                pass

        result = self.runTests(Test)

        self.assertEqual(Test.setUpCalled, 1)
        self.assertEqual(result.testsRun, 2)
        self.assertEqual(len(result.errors), 0) 
Example 32
Project: hostapd-mana   Author: adde88   File: test_setups.py    (license) View Source Project 6 votes vote down vote up
def test_teardown_class(self):
        class Test(unittest.TestCase):
            tearDownCalled = 0
            @classmethod
            def tearDownClass(cls):
                Test.tearDownCalled += 1
                unittest.TestCase.tearDownClass()
            def test_one(self):
                pass
            def test_two(self):
                pass

        result = self.runTests(Test)

        self.assertEqual(Test.tearDownCalled, 1)
        self.assertEqual(result.testsRun, 2)
        self.assertEqual(len(result.errors), 0) 
Example 33
Project: hostapd-mana   Author: adde88   File: test_setups.py    (license) View Source Project 6 votes vote down vote up
def test_error_in_setupclass(self):
        class BrokenTest(unittest.TestCase):
            @classmethod
            def setUpClass(cls):
                raise TypeError('foo')
            def test_one(self):
                pass
            def test_two(self):
                pass

        result = self.runTests(BrokenTest)

        self.assertEqual(result.testsRun, 0)
        self.assertEqual(len(result.errors), 1)
        error, _ = result.errors[0]
        self.assertEqual(str(error),
                    'setUpClass (%s.BrokenTest)' % __name__) 
Example 34
Project: hostapd-mana   Author: adde88   File: test_setups.py    (license) View Source Project 6 votes vote down vote up
def test_class_not_setup_or_torndown_when_skipped(self):
        class Test(unittest.TestCase):
            classSetUp = False
            tornDown = False
            @classmethod
            def setUpClass(cls):
                Test.classSetUp = True
            @classmethod
            def tearDownClass(cls):
                Test.tornDown = True
            def test_one(self):
                pass

        Test = unittest.skip("hop")(Test)
        self.runTests(Test)
        self.assertFalse(Test.classSetUp)
        self.assertFalse(Test.tornDown) 
Example 35
Project: hostapd-mana   Author: adde88   File: test_setups.py    (license) View Source Project 6 votes vote down vote up
def test_setup_module(self):
        class Module(object):
            moduleSetup = 0
            @staticmethod
            def setUpModule():
                Module.moduleSetup += 1

        class Test(unittest.TestCase):
            def test_one(self):
                pass
            def test_two(self):
                pass
        Test.__module__ = 'Module'
        sys.modules['Module'] = Module

        result = self.runTests(Test)
        self.assertEqual(Module.moduleSetup, 1)
        self.assertEqual(result.testsRun, 2)
        self.assertEqual(len(result.errors), 0) 
Example 36
Project: hostapd-mana   Author: adde88   File: test_setups.py    (license) View Source Project 6 votes vote down vote up
def test_skiptest_in_setupclass(self):
        class Test(unittest.TestCase):
            @classmethod
            def setUpClass(cls):
                raise unittest.SkipTest('foo')
            def test_one(self):
                pass
            def test_two(self):
                pass

        result = self.runTests(Test)
        self.assertEqual(result.testsRun, 0)
        self.assertEqual(len(result.errors), 0)
        self.assertEqual(len(result.skipped), 1)
        skipped = result.skipped[0][0]
        self.assertEqual(str(skipped), 'setUpClass (%s.Test)' % __name__) 
Example 37
Project: hostapd-mana   Author: adde88   File: test_setups.py    (license) View Source Project 6 votes vote down vote up
def test_skiptest_in_setupmodule(self):
        class Test(unittest.TestCase):
            def test_one(self):
                pass
            def test_two(self):
                pass

        class Module(object):
            @staticmethod
            def setUpModule():
                raise unittest.SkipTest('foo')

        Test.__module__ = 'Module'
        sys.modules['Module'] = Module

        result = self.runTests(Test)
        self.assertEqual(result.testsRun, 0)
        self.assertEqual(len(result.errors), 0)
        self.assertEqual(len(result.skipped), 1)
        skipped = result.skipped[0][0]
        self.assertEqual(str(skipped), 'setUpModule (Module)') 
Example 38
Project: hostapd-mana   Author: adde88   File: test_case.py    (license) View Source Project 6 votes vote down vote up
def test_run_call_order__error_in_tearDown_default_result(self):

        class Foo(Test.LoggingTestCase):
            def defaultTestResult(self):
                return LoggingResult(self.events)
            def tearDown(self):
                super(Foo, self).tearDown()
                raise RuntimeError('raised by Foo.tearDown')

        events = []
        Foo(events).run()
        expected = ['startTestRun', 'startTest', 'setUp', 'test', 'tearDown',
                    'addError', 'stopTest', 'stopTestRun']
        self.assertEqual(events, expected)

    # "TestCase.run() still works when the defaultTestResult is a TestResult
    # that does not support startTestRun and stopTestRun. 
Example 39
Project: hostapd-mana   Author: adde88   File: test_case.py    (license) View Source Project 6 votes vote down vote up
def test_failureException__subclassing__explicit_raise(self):
        events = []
        result = LoggingResult(events)

        class Foo(unittest.TestCase):
            def test(self):
                raise RuntimeError()

            failureException = RuntimeError

        self.assertIs(Foo('test').failureException, RuntimeError)


        Foo('test').run(result)
        expected = ['startTest', 'addFailure', 'stopTest']
        self.assertEqual(events, expected)

    # "This class attribute gives the exception raised by the test() method.
    # If a test framework needs to use a specialized exception, possibly to
    # carry additional information, it must subclass this exception in
    # order to ``play fair'' with the framework."
    #
    # Make sure TestCase.run() respects the designated failureException 
Example 40
Project: hostapd-mana   Author: adde88   File: test_case.py    (license) View Source Project 6 votes vote down vote up
def test_failureException__subclassing__implicit_raise(self):
        events = []
        result = LoggingResult(events)

        class Foo(unittest.TestCase):
            def test(self):
                self.fail("foo")

            failureException = RuntimeError

        self.assertIs(Foo('test').failureException, RuntimeError)


        Foo('test').run(result)
        expected = ['startTest', 'addFailure', 'stopTest']
        self.assertEqual(events, expected)

    # "The default implementation does nothing." 
Example 41
Project: hostapd-mana   Author: adde88   File: test_case.py    (license) View Source Project 6 votes vote down vote up
def test_run__uses_defaultTestResult(self):
        events = []

        class Foo(unittest.TestCase):
            def test(self):
                events.append('test')

            def defaultTestResult(self):
                return LoggingResult(events)

        # Make run() find a result object on its own
        Foo('test').run()

        expected = ['startTestRun', 'startTest', 'test', 'addSuccess',
            'stopTest', 'stopTestRun']
        self.assertEqual(events, expected) 
Example 42
Project: hostapd-mana   Author: adde88   File: test_case.py    (license) View Source Project 6 votes vote down vote up
def testKeyboardInterrupt(self):
        def _raise(self=None):
            raise KeyboardInterrupt
        def nothing(self):
            pass

        class Test1(unittest.TestCase):
            test_something = _raise

        class Test2(unittest.TestCase):
            setUp = _raise
            test_something = nothing

        class Test3(unittest.TestCase):
            test_something = nothing
            tearDown = _raise

        class Test4(unittest.TestCase):
            def test_something(self):
                self.addCleanup(_raise)

        for klass in (Test1, Test2, Test3, Test4):
            with self.assertRaises(KeyboardInterrupt):
                klass('test_something').run() 
Example 43
Project: django-performance-testing   Author: PaesslerAG   File: test_integrates_with_django_testrunner.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def test_runner_sets_executing_test_method_as_context():

    class SomeTestCase(unittest.TestCase):
        def test_foo(self):
            assert 'test name' in ctx.data, ctx.data.keys()
            tests = ctx.data['test name']
            assert len(tests) == 1
            assert [str(self)] == tests

    with override_current_context() as ctx:
        run_testcases_with_django_runner(SomeTestCase, nr_of_tests=1) 
Example 44
Project: django-performance-testing   Author: PaesslerAG   File: test_integrates_with_django_testrunner.py    (BSD 3-Clause "New" or "Revised" License) View Source Project 5 votes vote down vote up
def test_collected_results_serialized_to_settings_based_filename(
        settings, tmpfilepath):

    class SomeTestCase(unittest.TestCase):
        def test_foo(self):
            assert 'test name' in ctx.data, ctx.data.keys()
            tests = ctx.data['test name']
            assert len(tests) == 1
            assert [str(self)] == tests

    settings.DJPT_DATAFILE_PATH = tmpfilepath
    with override_current_context() as ctx:
        run_testcases_with_django_runner(SomeTestCase, nr_of_tests=1)
    reader = Reader(settings.DJPT_DATAFILE_PATH)
    assert [] != reader.read_all() 
Example 45
Project: core-framework   Author: RedhawkSDR   File: runtests.py    (license) View Source Project 5 votes vote down vote up
def loadTests(self):
        for file in self.__files:
            mod = runtestHelpers.loadModule(file)
            candidates = dir(mod)
            for candidate in candidates:
                candidate = getattr(mod, candidate)
                try:
                    if issubclass(candidate, unittest.TestCase):
                        print "LOADING"
                        loader = PromptTestLoader()
                        loader.PROMPT = self.__prompt
                        loader.testMethodPrefix = self.__testMethodPrefix
                        self.addTest(loader.loadTestsFromTestCase(candidate))
                except TypeError, e:
                    pass 
Example 46
Project: core-framework   Author: RedhawkSDR   File: rhunittest.py    (license) View Source Project 5 votes vote down vote up
def loadTestsFromName(self, name, module=None):
        """Return a suite of all tests cases given a string specifier.

        The name may resolve either to a module, a test case class, a
        test method within a test case class, or a callable object which
        returns a TestCase or TestSuite instance.

        The method optionally resolves the names relative to a given module.
        """
        parent, obj = self._resolveName(name, module)

        if type(obj) == types.ModuleType:
            return self.loadTestsFromModule(obj)
        elif (isinstance(obj, (type, types.ClassType)) and
              issubclass(obj, unittest.TestCase)):
            return self.loadTestsFromTestCase(obj)
        elif (type(obj) == types.UnboundMethodType and
              isinstance(parent, (type, types.ClassType)) and
              issubclass(parent, unittest.TestCase)):
            return self.loadSpecificTestFromTestCase(parent, obj.__name__)
        elif isinstance(obj, unittest.TestSuite):
            return obj
        elif hasattr(obj, '__call__'):
            test = obj()
            if isinstance(test, unittest.TestSuite):
                return test
            elif isinstance(test, unittest.TestCase):
                return self.suiteClass([test])
            else:
                raise TypeError("calling %s returned %s, not a test" %
                                (obj, test))
        else:
            raise TypeError("don't know how to make test from: %s" % obj) 
Example 47
Project: core-framework   Author: RedhawkSDR   File: test_helpers.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, methodName='runTest'):
        unittest.TestCase.__init__(self, methodName) 
Example 48
Project: core-framework   Author: RedhawkSDR   File: test_helpers.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, methodName='runTest'):
        unittest.TestCase.__init__(self, methodName) 
Example 49
Project: core-framework   Author: RedhawkSDR   File: test_python_attachable.py    (license) View Source Project 5 votes vote down vote up
def __init__( self, methodName='runTest' ):
        unittest.TestCase.__init__(self, methodName) 
Example 50
Project: spoon   Author: SpamExperts   File: test_server.py    (GNU General Public License v2.0) View Source Project 5 votes vote down vote up
def tearDown(self):
        unittest.TestCase.tearDown(self)
        patch.stopall()