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())
python类TestCase()的实例源码
test_worst_report_integrates_with_django_testrunner.py 文件源码
项目:django-performance-testing
作者: PaesslerAG
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
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
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')
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))
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 = ""
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
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)
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
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()
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
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
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()
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
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()
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)
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])
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())
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
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
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."
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."
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))
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)
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)
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)
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())
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)
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")])
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'])
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)