Python/Jython Unittest

Here my take at it, with tests discovery.

It is using PrettyUnit https://github.com/beatsbears/prettyunit, in which I removed the function "generate_json_and_send_http" and the "import requests", at the top, that are not used in this case

def __getMembers(baseTypeName, baseType, callback):
	import inspect
	
	result = {
		"test-cases": { },
		"project": baseTypeName,
		"start-timestamp": system.date.now(),
		"end-timestamp": system.date.now()
	}
	
	for name, obj in inspect.getmembers(baseType):
		if "Package" in str(type(obj)):
			__mergeResults(result, __getMembers(baseTypeName + '.' + name, obj, callback))
		elif "Module" in str(type(obj)):
			__mergeResults(result, callback(baseTypeName + '.' + name, obj), baseTypeName + '.')
	
	return result

def __mergeResults(mergedResults, results, baseTypeName = ''):
	for prop in results:
		if prop not in mergedResults:
			mergedResults[prop] = results[prop]
		elif isinstance(results[prop], (int, long)):
			mergedResults[prop] = mergedResults[prop] + results[prop]
	
	for prop in results["test-cases"]:
		propDestination = (baseTypeName + prop).replace('.', '-')
		if propDestination in mergedResults["test-cases"]:
			mergedResults["test-cases"][propDestination] = mergedResults["test-cases"][propDestination] + results["test-cases"][prop]
		else:
			mergedResults["test-cases"][propDestination] = results["test-cases"][prop]
	
	mergedResults["end-timestamp"] = system.date.now()
	return mergedResults


def runAll():
	"""Discover and run all test from specified package
	https://docs.python.org/2.7/library/unittest.html
	Args:
		None
	Returns:
		Test Results formatted using PrettyUnit
	"""
	# Lets say I want to discover all tests defined in MyPackage.test
	return __getMembers('MyPackage', MyPackage.test, runModule)

def runModule(moduleName, module):
	import unittest
	from prettyunit import PrettyUnit
	
	PU = PrettyUnit(moduleName)
	
	suite = unittest.TestLoader().loadTestsFromModule(module)
	results = unittest.TextTestRunner(verbosity=0).run(suite)
	
	# Populate UC dictionary and generate json
	PU.populate_json(moduleName, suite._tests)
	PU.add_results_json(results)
	return PU.data

and I created a view in Perspective

4 Likes