--- a/layout/tools/reftest/runreftest.py
+++ b/layout/tools/reftest/runreftest.py
@@ -52,16 +52,18 @@ try:
from mozbuild.base import MozbuildObject
build_obj = MozbuildObject.from_environment(cwd=here)
except ImportError:
build_obj = None
def categoriesToRegex(categoryList):
return "\\(" + ', '.join(["(?P<%s>\\d+) %s" % c for c in categoryList]) + "\\)"
+
+
summaryLines = [('Successful', [('pass', 'pass'), ('loadOnly', 'load only')]),
('Unexpected', [('fail', 'unexpected fail'),
('pass', 'unexpected pass'),
('asserts', 'unexpected asserts'),
('fixedAsserts', 'unexpected fixed asserts'),
('failedLoad', 'failed load'),
('exception', 'exception')]),
('Known problems', [('knownFail', 'known fail'),
--- a/security/manager/ssl/tests/unit/pycert.py
+++ b/security/manager/ssl/tests/unit/pycert.py
@@ -741,12 +741,13 @@ class Certificate(object):
# system throws an error.
# The one concrete failure mode is if one run happens before
# midnight on New Year's Eve and the next run happens after
# midnight.
def main(output, inputPath):
with open(inputPath) as configStream:
output.write(Certificate(configStream).toPEM())
+
# When run as a standalone program, this will read a specification from
# stdin and output the certificate as PEM to stdout.
if __name__ == '__main__':
print Certificate(sys.stdin).toPEM()
--- a/security/manager/ssl/tests/unit/pykey.py
+++ b/security/manager/ssl/tests/unit/pykey.py
@@ -730,12 +730,13 @@ def keyFromSpecification(specification):
# The build harness will call this function with an output file-like
# object and a path to a file containing a specification. This will
# read the specification and output the key as ASCII-encoded PKCS #8.
def main(output, inputPath):
with open(inputPath) as configStream:
output.write(keyFromSpecification(configStream.read().strip()).toPEM())
+
# When run as a standalone program, this will read a specification from
# stdin and output the certificate as PEM to stdout.
if __name__ == '__main__':
print keyFromSpecification(sys.stdin.read()).toPEM()
--- a/security/manager/ssl/tests/unit/test_cert_version/generate.py
+++ b/security/manager/ssl/tests/unit/test_cert_version/generate.py
@@ -49,16 +49,17 @@ def writeCertspec(issuer, subject, field
filename = '%s.pem.certspec' % subject
with open(filename, 'w') as f:
f.write('issuer:%s\n' % issuer)
f.write('subject:%s\n' % subject)
for field in fields:
if len(field) > 0:
f.write('%s\n' % field)
+
keyUsage = 'extension:keyUsage:keyCertSign,cRLSign'
basicConstraintsCA = 'extension:basicConstraints:cA,'
writeCertspec('ca', 'ca', [keyUsage, basicConstraintsCA])
for versionStr, versionVal in versions.iteritems():
# intermediates
versionText = 'version:%s' % versionVal
--- a/taskcluster/docker/funsize-balrog-submitter/scripts/funsize-balrog-submitter.py
+++ b/taskcluster/docker/funsize-balrog-submitter/scripts/funsize-balrog-submitter.py
@@ -200,10 +200,11 @@ def main():
appVersion=e["version"], locale=e["locale"],
hashFunction='sha512', extVersion=e["version"],
partialInfo=partial_info, completeInfo=complete_info),
attempts=30, sleeptime=10, max_sleeptime=60,
)
else:
raise RuntimeError("Cannot determine Balrog submission style")
+
if __name__ == '__main__':
main()
--- a/taskcluster/docker/rust-build/splat_rust.py
+++ b/taskcluster/docker/rust-build/splat_rust.py
@@ -50,16 +50,17 @@ def update_manifest(source_manifest, tar
if version:
print(' %s' % version)
print('Updating %s' % target_filename)
old = load_manifest(target_filename)
replace(old, stanza)
save_manifest(old, target_filename)
break
+
'''Mapping from targets to target filenames.'''
TARGETS = {
'x86_64-unknown-linux-gnu-repack': [
'browser/config/tooltool-manifests/linux32/releng.manifest',
'browser/config/tooltool-manifests/linux64/asan.manifest',
'browser/config/tooltool-manifests/linux64/clang.manifest',
'browser/config/tooltool-manifests/linux64/clang.manifest.centos6',
'browser/config/tooltool-manifests/linux64/hazard.manifest',
--- a/taskcluster/taskgraph/cron/schema.py
+++ b/taskcluster/taskgraph/cron/schema.py
@@ -14,16 +14,17 @@ from taskgraph.util.schema import (
Schema,
)
def even_15_minutes(minutes):
if minutes % 15 != 0:
raise ValueError("minutes must be evenly divisible by 15")
+
cron_yml_schema = Schema({
'jobs': [{
# Name of the crontask (must be unique)
Required('name'): basestring,
# what to run
# Description of the job to run, keyed by 'type'
--- a/taskcluster/taskgraph/test/test_cron_util.py
+++ b/taskcluster/taskgraph/test/test_cron_util.py
@@ -56,10 +56,11 @@ class TestMatchUtc(unittest.TestCase):
self.assertFalse(match_utc(params, minute=30))
self.assertFalse(match_utc(params, minute=45))
def test_invalid_minute(self):
params = {'time': datetime.datetime(2017, 01, 26, 13, 0, 0)}
self.assertRaises(Exception, lambda:
match_utc(params, minute=1))
+
if __name__ == '__main__':
main()
--- a/taskcluster/taskgraph/test/test_graph.py
+++ b/taskcluster/taskgraph/test/test_graph.py
@@ -148,10 +148,11 @@ class TestGraph(unittest.TestCase):
def test_reverse_links_dict(self):
"reverse link dict for a graph with multiple edges is correct"
self.assertEqual(self.multi_edges.reverse_links_dict(), {
'1': set(['2', '3']),
'2': set(['3']),
'3': set(['4']),
})
+
if __name__ == '__main__':
main()
--- a/taskcluster/taskgraph/test/test_morph.py
+++ b/taskcluster/taskgraph/test/test_morph.py
@@ -77,10 +77,11 @@ class TestIndexTask(unittest.TestCase):
def make_taskgraph(self, tasks):
label_to_taskid = {k: k + '-tid' for k in tasks}
for label, task_id in label_to_taskid.iteritems():
tasks[label].task_id = task_id
graph = Graph(nodes=set(tasks), edges=set())
taskgraph = TaskGraph(tasks, graph)
return taskgraph, label_to_taskid
+
if __name__ == '__main__':
main()
--- a/taskcluster/taskgraph/test/test_parameters.py
+++ b/taskcluster/taskgraph/test/test_parameters.py
@@ -53,10 +53,11 @@ class TestParameters(unittest.TestCase):
{'some': 'data'})
def test_load_parameters_file_json(self):
with MockedOpen({"params.json": '{"some": "data"}'}):
self.assertEqual(
load_parameters_file({'parameters': 'params.json'}),
{'some': 'data'})
+
if __name__ == '__main__':
main()
--- a/taskcluster/taskgraph/test/test_target_tasks.py
+++ b/taskcluster/taskgraph/test/test_target_tasks.py
@@ -78,10 +78,11 @@ class TestTargetTasks(unittest.TestCase)
orig_TryOptionSyntax = try_option_syntax.TryOptionSyntax
try:
try_option_syntax.TryOptionSyntax = FakeTryOptionSyntax
method = target_tasks.get_method('try_option_syntax')
self.assertEqual(method(tg, params), ['b'])
finally:
try_option_syntax.TryOptionSyntax = orig_TryOptionSyntax
+
if __name__ == '__main__':
main()
--- a/taskcluster/taskgraph/test/test_taskgraph.py
+++ b/taskcluster/taskgraph/test/test_taskgraph.py
@@ -69,10 +69,11 @@ class TestTaskGraph(unittest.TestCase):
dependencies={},
optimizations=[['seta']],
task={'task': 'def2'}),
}, graph=Graph(nodes={'a', 'b'}, edges={('a', 'b', 'prereq')}))
tasks, new_graph = TaskGraph.from_json(graph.to_json())
self.assertEqual(graph, new_graph)
+
if __name__ == '__main__':
main()
--- a/taskcluster/taskgraph/test/test_try_option_syntax.py
+++ b/taskcluster/taskgraph/test/test_try_option_syntax.py
@@ -319,10 +319,11 @@ class TestTryOptionSyntax(unittest.TestC
tos = TryOptionSyntax('try: --tag tagName', graph_with_jobs)
self.assertEqual(tos.tag, 'tagName')
def test_no_retry(self):
"--no-retry sets no_retry to true"
tos = TryOptionSyntax('try: --no-retry', graph_with_jobs)
self.assertTrue(tos.no_retry)
+
if __name__ == '__main__':
main()
--- a/taskcluster/taskgraph/test/test_util_templates.py
+++ b/taskcluster/taskgraph/test/test_util_templates.py
@@ -223,10 +223,11 @@ class MergeTest(unittest.TestCase):
}
self.assertEqual(merge(first, second, third), expected)
# inputs haven't changed..
self.assertEqual(first, {'a': 1, 'b': 2, 'd': 11})
self.assertEqual(second, {'b': 20, 'c': 30})
self.assertEqual(third, {'c': 300, 'd': 400})
+
if __name__ == '__main__':
mozunit.main()
--- a/taskcluster/taskgraph/test/test_util_time.py
+++ b/taskcluster/taskgraph/test/test_util_time.py
@@ -48,10 +48,11 @@ class FromNowTest(unittest.TestCase):
def test_json_from_now(self):
now = datetime(2014, 1, 1)
self.assertEqual(json_time_from_now('1 years', now),
'2015-01-01T00:00:00Z')
self.assertEqual(json_time_from_now('6 days', now),
'2014-01-07T00:00:00Z')
+
if __name__ == '__main__':
mozunit.main()
--- a/taskcluster/taskgraph/transforms/job/__init__.py
+++ b/taskcluster/taskgraph/transforms/job/__init__.py
@@ -155,16 +155,17 @@ def make_task_description(config, jobs):
# give the function for job.run.using on this worker implementation a
# chance to set up the task description.
configure_taskdesc_for_run(config, job, taskdesc, impl)
del taskdesc['run']
# yield only the task description, discarding the job description
yield taskdesc
+
# A registry of all functions decorated with run_job_using
registry = {}
def run_job_using(worker_implementation, run_using, schema=None):
"""Register the decorated function as able to set up a task description for
jobs with the given worker implementation and `run.using` property. If
`schema` is given, the job's run field will be verified to match it.
--- a/taskcluster/taskgraph/transforms/l10n.py
+++ b/taskcluster/taskgraph/transforms/l10n.py
@@ -27,16 +27,17 @@ from voluptuous import (
Optional,
Required,
)
def _by_platform(arg):
return optionally_keyed_by('build-platform', arg)
+
# shortcut for a string where task references are allowed
taskref_or_string = Any(
basestring,
{Required('task-reference'): basestring})
# Voluptuous uses marker objects as dictionary *keys*, but they are not
# comparable, so we cast all of the keys back to regular strings
job_description_schema = {str(k): v for k, v in job_description_schema.schema.iteritems()}
--- a/taskcluster/taskgraph/transforms/task.py
+++ b/taskcluster/taskgraph/transforms/task.py
@@ -534,16 +534,17 @@ payload_builders = {}
def payload_builder(name):
def wrap(func):
payload_builders[name] = func
return func
return wrap
+
# define a collection of index builders, depending on the type implementation
index_builders = {}
def index_builder(name):
def wrap(func):
index_builders[name] = func
return func
--- a/taskcluster/taskgraph/util/schema.py
+++ b/taskcluster/taskgraph/util/schema.py
@@ -124,16 +124,17 @@ def resolve_keyed_by(item, field, item_n
elif matches:
value = container[subfield] = matches[0]
continue
raise Exception(
"No {} matching {!r} nor 'default' found while determining item {} in {}".format(
keyed_by, key, field, item_name))
+
# Schemas for YAML files should use dashed identifiers by default. If there are
# components of the schema for which there is a good reason to use another format,
# they can be whitelisted here.
WHITELISTED_SCHEMA_IDENTIFIERS = [
# upstream-artifacts are handed directly to scriptWorker, which expects interCaps
lambda path: "[u'upstream-artifacts']" in path,
]
--- a/taskcluster/taskgraph/util/seta.py
+++ b/taskcluster/taskgraph/util/seta.py
@@ -194,11 +194,12 @@ class SETA(object):
return label in self.low_value_tasks[project]
# gecko decision task requesting if a bbb task is a low value task, so use bb jobs
# in this case, the label param sent in will be the buildbot buildername already
if project not in self.low_value_bb_tasks:
self.low_value_bb_tasks[project] = self.query_low_value_tasks(project, bbb=True)
return label in self.low_value_bb_tasks[project]
+
# create a single instance of this class, and expose its `is_low_value_task`
# bound method as a module-level function
is_low_value_task = SETA().is_low_value_task
--- a/taskcluster/taskgraph/util/time.py
+++ b/taskcluster/taskgraph/util/time.py
@@ -35,16 +35,17 @@ def months(value):
def years(value):
# Warning here "years" are vague don't use this for really sensitive date
# computation the idea is to give you a absolute amount of time in the
# future which is not the same thing as "precisely on this date next year"
return datetime.timedelta(days=int(value) * 365)
+
ALIASES = {}
ALIASES['seconds'] = ALIASES['second'] = ALIASES['s'] = seconds
ALIASES['minutes'] = ALIASES['minute'] = ALIASES['min'] = minutes
ALIASES['hours'] = ALIASES['hour'] = ALIASES['h'] = hours
ALIASES['days'] = ALIASES['day'] = ALIASES['d'] = days
ALIASES['months'] = ALIASES['month'] = ALIASES['mo'] = months
ALIASES['years'] = ALIASES['year'] = ALIASES['y'] = years
--- a/testing/firefox-ui/harness/setup.py
+++ b/testing/firefox-ui/harness/setup.py
@@ -13,16 +13,17 @@ def read(*parts):
with open(os.path.join(THIS_DIR, *parts)) as f:
return f.read()
def get_version():
return re.findall("__version__ = '([\d\.]+)'",
read('firefox_ui_harness', '__init__.py'), re.M)[0]
+
long_description = """Custom Marionette runner classes and entry scripts for Firefox Desktop
specific Marionette tests.
"""
setup(name='firefox-ui-harness',
version=get_version(),
description="Firefox UI Harness",
long_description=long_description,
--- a/testing/marionette/harness/marionette_harness/runtests.py
+++ b/testing/marionette/harness/marionette_harness/runtests.py
@@ -92,10 +92,11 @@ def cli(runner_class=MarionetteTestRunne
failed = harness_instance.run()
if failed > 0:
sys.exit(10)
except Exception:
logger.error('Failure during harness execution', exc_info=True)
sys.exit(1)
sys.exit(0)
+
if __name__ == "__main__":
cli()
--- a/testing/mochitest/runrobocop.py
+++ b/testing/mochitest/runrobocop.py
@@ -583,10 +583,11 @@ def run_test_harness(parser, options):
return runResult
def main(args=sys.argv[1:]):
parser = MochitestArgumentParser(app='android')
options = parser.parse_args(args)
return run_test_harness(parser, options)
+
if __name__ == "__main__":
sys.exit(main())
--- a/testing/mozbase/docs/_static/structured_example.py
+++ b/testing/mozbase/docs/_static/structured_example.py
@@ -93,10 +93,11 @@ def main():
logger = commandline.setup_logging("structured-example", args, {"raw": sys.stdout})
runner = TestRunner()
try:
runner.run()
except:
logger.critical("Error during test run:\n%s" % traceback.format_exc())
+
if __name__ == "__main__":
main()
--- a/testing/mozbase/manifestparser/manifestparser/cli.py
+++ b/testing/mozbase/manifestparser/manifestparser/cli.py
@@ -237,10 +237,11 @@ def main(args=sys.argv[1:]):
command = args[0]
if command not in commands:
parser.error("Command must be one of %s (you gave '%s')" %
(', '.join(sorted(commands.keys())), command))
handler = commands[command](parser)
handler(options, args[1:])
+
if __name__ == '__main__':
main()
--- a/testing/mozbase/manifestparser/manifestparser/expression.py
+++ b/testing/mozbase/manifestparser/manifestparser/expression.py
@@ -163,16 +163,17 @@ class int_token(literal_token):
literal_token.__init__(self, scanner, int(value))
class string_token(literal_token):
def __init__(self, scanner, value):
literal_token.__init__(self, scanner, value[1:-1])
+
precedence = [(end_token, rparen_token),
(or_op_token,),
(and_op_token,),
(lt_op_token, gt_op_token, le_op_token, ge_op_token,
eq_op_token, neq_op_token),
(lparen_token,),
]
for index, rank in enumerate(precedence):
--- a/testing/mozbase/manifestparser/manifestparser/manifestparser.py
+++ b/testing/mozbase/manifestparser/manifestparser/manifestparser.py
@@ -738,16 +738,17 @@ class ManifestParser(object):
# rewind buffer
write.flush()
write.seek(0)
manifests = [write]
# make a ManifestParser instance
return cls(manifests=manifests)
+
convert = ManifestParser.from_directories
class TestManifest(ManifestParser):
"""
apply logic to manifests; this is your integration layer :)
specific harnesses may subclass from this if they need more logic
"""
--- a/testing/mozbase/manifestparser/tests/test_default_overrides.py
+++ b/testing/mozbase/manifestparser/tests/test_default_overrides.py
@@ -109,10 +109,11 @@ class TestSubsuiteDefaults(unittest.Test
'test2': 'foo',
}
defaults = parser.manifest_defaults[manifest]
for test in parser.tests:
value = combine_fields(defaults, test)
self.assertEqual(expected_subsuites[value['name']],
value['subsuite'])
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/manifestparser/tests/test_manifestparser.py
+++ b/testing/mozbase/manifestparser/tests/test_manifestparser.py
@@ -319,10 +319,11 @@ yellow = submarine""" # noqa
"""
parser = ManifestParser()
manifest = os.path.join(here, 'no-tests.ini')
parser.read(manifest)
self.assertEqual(len(parser.tests), 0)
self.assertTrue(len(parser.manifests()) == 1)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/manifestparser/tests/test_testmanifest.py
+++ b/testing/mozbase/manifestparser/tests/test_testmanifest.py
@@ -115,10 +115,11 @@ class TestTestManifest(unittest.TestCase
none_manifest = TestManifest(manifests=None, strict=False)
self.assertEqual(len(none_manifest.test_paths()), 0)
self.assertEqual(len(none_manifest.active_tests()), 0)
empty_manifest = TestManifest(manifests=[], strict=False)
self.assertEqual(len(empty_manifest.test_paths()), 0)
self.assertEqual(len(empty_manifest.active_tests()), 0)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/moz.build
+++ b/testing/mozbase/moz.build
@@ -43,9 +43,9 @@ python_modules = [
TEST_HARNESS_FILES.mozbase += [m + '/**' for m in python_modules]
TEST_HARNESS_FILES.mozbase += [
'setup_development.py',
]
with Files('**'):
- BUG_COMPONENT = ('Testing', 'Mozbase')
\ No newline at end of file
+ BUG_COMPONENT = ('Testing', 'Mozbase')
--- a/testing/mozbase/mozcrash/mozcrash/mozcrash.py
+++ b/testing/mozbase/mozcrash/mozcrash/mozcrash.py
@@ -376,16 +376,17 @@ def check_for_java_exception(logcat, tes
exception_location)
else:
print "Automation Error: java exception in logcat at line " \
"%d of %d: %s" % (i, len(logcat), line)
break
return found_exception
+
if mozinfo.isWin:
import ctypes
import uuid
kernel32 = ctypes.windll.kernel32
OpenProcess = kernel32.OpenProcess
CloseHandle = kernel32.CloseHandle
--- a/testing/mozbase/mozcrash/tests/test.py
+++ b/testing/mozbase/mozcrash/tests/test.py
@@ -235,10 +235,11 @@ class TestJavaException(unittest.TestCas
"""
Test for an exception which should not be caught
"""
passable_log = list(self.test_log)
passable_log[0] = "01-30 20:15:41.937 E/GeckoAppShell( 1703):" \
" >>> NOT-SO-BAD EXCEPTION FROM THREAD 9 (\"GeckoBackgroundThread\")"
self.assert_(not mozcrash.check_for_java_exception(passable_log, quiet=True))
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozdevice/adb_tests/test_device_running_adb_as_root.py
+++ b/testing/mozbase/mozdevice/adb_tests/test_device_running_adb_as_root.py
@@ -28,16 +28,17 @@ class TestFileOperations(unittest.TestCa
self.assertTrue(dm.processInfo("adbd")[2] == "root")
dm.reboot(wait=True)
self.assertTrue(dm.processInfo("adbd")[2] == "root")
def tearDown(self):
dm = DeviceManagerADB()
dm.reboot()
+
if __name__ == "__main__":
dm = DeviceManagerADB()
if not dm.devices():
print "There are no connected adb devices"
sys.exit(1)
else:
if not (int(dm._runCmd(["shell", "getprop", "ro.secure"]).output[0]) and
int(dm._runCmd(["shell", "getprop", "ro.debuggable"]).output[0])):
--- a/testing/mozbase/mozdevice/mozdevice/dmcli.py
+++ b/testing/mozbase/mozdevice/mozdevice/dmcli.py
@@ -341,10 +341,11 @@ class DMCli(object):
print(self.dm.getIP())
def cli(args=sys.argv[1:]):
# process the command line
cli = DMCli()
cli.run(args)
+
if __name__ == '__main__':
cli()
--- a/testing/mozbase/mozfile/tests/test_load.py
+++ b/testing/mozbase/mozfile/tests/test_load.py
@@ -56,10 +56,11 @@ class TestLoad(unittest.TestCase):
# read the file with load and a file URL
self.assertEqual(load('file://%s' % tmp.name).read(), contents)
finally:
# remove the tempfile
if os.path.exists(tmp.name):
os.remove(tmp.name)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozfile/tests/test_tempdir.py
+++ b/testing/mozbase/mozfile/tests/test_tempdir.py
@@ -35,10 +35,11 @@ class TestTemporaryDirectory(unittest.Te
with self.assertRaises(Exception):
with TemporaryDirectory() as tmp:
path = tmp
self.assertTrue(os.path.isdir(tmp))
raise Exception("oops")
self.assertFalse(os.path.isdir(path))
self.assertFalse(os.path.exists(path))
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozfile/tests/test_tempfile.py
+++ b/testing/mozbase/mozfile/tests/test_tempfile.py
@@ -95,10 +95,11 @@ class TestNamedTemporaryFile(unittest.Te
path = tf.name
self.assertTrue(os.path.exists(path))
del tf
self.assertTrue(os.path.exists(path))
finally:
if path and os.path.exists(path):
os.remove(path)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozfile/tests/test_url.py
+++ b/testing/mozbase/mozfile/tests/test_url.py
@@ -14,10 +14,11 @@ class TestIsUrl(unittest.TestCase):
"""test the is_url function"""
def test_is_url(self):
self.assertTrue(is_url('http://mozilla.org'))
self.assertFalse(is_url('/usr/bin/mozilla.org'))
self.assertTrue(is_url('file:///usr/bin/mozilla.org'))
self.assertFalse(is_url('c:\foo\bar'))
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozhttpd/mozhttpd/mozhttpd.py
+++ b/testing/mozbase/mozhttpd/mozhttpd/mozhttpd.py
@@ -321,10 +321,11 @@ def main(args=sys.argv[1:]):
host = options.host
# create the server
server = MozHttpd(host=host, port=options.port, docroot=options.docroot)
print "Serving '%s' at %s:%s" % (server.docroot, server.host, server.port)
server.start(block=True)
+
if __name__ == '__main__':
main()
--- a/testing/mozbase/mozhttpd/tests/baseurl.py
+++ b/testing/mozbase/mozhttpd/tests/baseurl.py
@@ -12,10 +12,11 @@ class BaseUrlTest(unittest.TestCase):
httpd.start(block=False)
self.assertEqual("http://127.0.0.1:%s/" % httpd.httpd.server_port,
httpd.get_url())
self.assertEqual("http://127.0.0.1:%s/cheezburgers.html" %
httpd.httpd.server_port,
httpd.get_url(path="/cheezburgers.html"))
httpd.stop()
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozhttpd/tests/basic.py
+++ b/testing/mozbase/mozhttpd/tests/basic.py
@@ -39,10 +39,11 @@ class TestBasic(unittest.TestCase):
# Retrieve file and check contents matchup
for k in sizes.keys():
retrieved_content = mozfile.load(server_url + k).read()
self.assertEqual(retrieved_content, sizes[k][1])
# Cleanup tempdir and related files
mozfile.rmtree(tempdir)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozhttpd/tests/paths.py
+++ b/testing/mozbase/mozhttpd/tests/paths.py
@@ -70,10 +70,11 @@ class PathTest(unittest.TestCase):
"""Test that path mappings with no docroot work."""
with TemporaryDirectory() as d1:
httpd = mozhttpd.MozHttpd(port=0,
path_mappings={'/foo': d1})
httpd.start(block=False)
self.try_get_expect_404(httpd.get_url())
httpd.stop()
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozhttpd/tests/requestlog.py
+++ b/testing/mozbase/mozhttpd/tests/requestlog.py
@@ -34,10 +34,11 @@ class RequestLogTest(unittest.TestCase):
self.assertEqual(log_entry['path'], '/')
self.assertEqual(type(log_entry['time']), float)
def test_logging_disabled(self):
request_log = self.check_logging(log_requests=False)
self.assertEqual(len(request_log), 0)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozinfo/mozinfo/mozinfo.py
+++ b/testing/mozbase/mozinfo/mozinfo/mozinfo.py
@@ -24,16 +24,18 @@ from ctypes.util import find_library
class unknown(object):
"""marker class for unknown information"""
def __nonzero__(self):
return False
def __str__(self):
return 'UNKNOWN'
+
+
unknown = unknown() # singleton
def get_windows_version():
import ctypes
class OSVERSIONINFOEXW(ctypes.Structure):
_fields_ = [('dwOSVersionInfoSize', ctypes.c_ulong),
@@ -51,16 +53,17 @@ def get_windows_version():
os_version = OSVERSIONINFOEXW()
os_version.dwOSVersionInfoSize = ctypes.sizeof(os_version)
retcode = ctypes.windll.Ntdll.RtlGetVersion(ctypes.byref(os_version))
if retcode != 0:
raise OSError
return os_version.dwMajorVersion, os_version.dwMinorVersion, os_version.dwBuildNumber
+
# get system information
info = {'os': unknown,
'processor': unknown,
'version': unknown,
'os_version': unknown,
'bits': unknown,
'has_sandbox': unknown}
(system, node, release, version, machine, processor) = platform.uname()
@@ -239,16 +242,17 @@ def find_and_update_from_json(*dirs):
return None
def output_to_file(path):
import json
with open(path, 'w') as f:
f.write(json.dumps(info))
+
update({})
# exports
__all__ = info.keys()
__all__ += ['is' + os_name.title() for os_name in choices['os']]
__all__ += [
'info',
'unknown',
@@ -292,10 +296,11 @@ def main(args=None):
flag = True
if flag:
return
# otherwise, print out all info
for key, value in info.items():
print '%s: %s' % (key, value)
+
if __name__ == '__main__':
main()
--- a/testing/mozbase/mozlog/mozlog/commandline.py
+++ b/testing/mozbase/mozlog/mozlog/commandline.py
@@ -62,16 +62,17 @@ def default_formatter_options(log_type,
"level": "info"}
rv.update(formatter_option_defaults.get(log_type, {}))
if overrides is not None:
rv.update(overrides)
return rv
+
fmt_options = {
# <option name>: (<wrapper function>, description, <applicable formatters>, action)
# "action" is used by the commandline parser in use.
'verbose': (verbose_wrapper,
"Enables verbose mode for the given formatter.",
["mach"], "store_true"),
'compact': (compact_wrapper,
"Enables compact mode for the given formatter.",
--- a/testing/mozbase/mozlog/mozlog/formatters/__init__.py
+++ b/testing/mozbase/mozlog/mozlog/formatters/__init__.py
@@ -13,11 +13,12 @@ try:
import ujson as json
except ImportError:
import json
def JSONFormatter():
return lambda x: json.dumps(x) + "\n"
+
__all__ = ['UnittestFormatter', 'XUnitFormatter', 'HTMLFormatter',
'MachFormatter', 'TbplFormatter', 'ErrorSummaryFormatter',
'JSONFormatter']
--- a/testing/mozbase/mozlog/mozlog/formatters/html/xmlgen.py
+++ b/testing/mozbase/mozlog/mozlog/formatters/html/xmlgen.py
@@ -75,16 +75,17 @@ class Tag(list):
l = []
SimpleUnicodeVisitor(l.append, indent).visit(self)
return u("").join(l)
def __repr__(self):
name = self.__class__.__name__
return "<%r tag object %d>" % (name, id(self))
+
Namespace = NamespaceMetaclass('Namespace', (object, ), {
'__tagspec__': None,
'__tagclass__': Tag,
'__stickyname__': False,
})
class HtmlTag(Tag):
@@ -275,9 +276,10 @@ class _escape:
def _replacer(self, match):
return self.escape[match.group(0)]
def __call__(self, ustring):
""" xml-escape the given unicode string. """
ustring = unicode(ustring)
return self.charef_rex.sub(self._replacer, ustring)
+
escape = _escape()
--- a/testing/mozbase/mozlog/mozlog/scripts/format.py
+++ b/testing/mozbase/mozlog/mozlog/scripts/format.py
@@ -30,13 +30,14 @@ def main(**kwargs):
formatter = commandline.log_formatters[kwargs["format"]][0]()
handler = handlers.StreamHandler(stream=output_file,
formatter=formatter)
for data in reader.read(input_file):
handler(data)
+
if __name__ == "__main__":
parser = get_parser()
args = parser.parse_args()
kwargs = vars(args)
main(**kwargs)
--- a/testing/mozbase/mozlog/mozlog/scripts/unstable.py
+++ b/testing/mozbase/mozlog/mozlog/scripts/unstable.py
@@ -50,16 +50,17 @@ def _filter(results_cmp):
for test, subtests in tests.iteritems():
for name, results in subtests.iteritems():
if results_cmp(results):
rv[run_info][test][name] = results
return rv
return inner
+
filter_unstable = _filter(lambda x: len(x) > 1)
filter_stable = _filter(lambda x: len(x) == 1)
def group_results(data):
rv = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
for run_info, tests in data.iteritems():
@@ -108,13 +109,14 @@ def main(**kwargs):
if kwargs["json"]:
print json.dumps(unstable)
else:
if not kwargs["group"]:
print_results(unstable)
else:
print_run(unstable)
+
if __name__ == "__main__":
parser = get_parser()
args = parser.parse_args()
kwargs = vars(args)
main(**kwargs)
--- a/testing/mozbase/mozlog/mozlog/structuredlog.py
+++ b/testing/mozbase/mozlog/mozlog/structuredlog.py
@@ -92,16 +92,17 @@ def set_default_logger(default_logger):
function if you're using setting up logging that way (recommended).
:param default_logger: The logger to set to default.
"""
global _default_logger_name
_default_logger_name = default_logger.name
+
log_levels = dict((k.upper(), v) for v, k in
enumerate(["critical", "error", "warning", "info", "debug"]))
lint_levels = ["ERROR", "WARNING"]
def log_actions():
"""Returns the set of actions implemented by mozlog."""
--- a/testing/mozbase/mozlog/tests/test_logger.py
+++ b/testing/mozbase/mozlog/tests/test_logger.py
@@ -256,10 +256,11 @@ class TestLoggingMixin(unittest.TestCase
expected_messages = ['message for "log" method',
'message for "info" method',
'message for "error" method',
'message for "log_structured" method']
actual_messages = loggable._logger.handlers[0].messages
self.assertEqual(expected_messages, actual_messages)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozlog/tests/test_structured.py
+++ b/testing/mozbase/mozlog/tests/test_structured.py
@@ -1090,10 +1090,11 @@ class TestReader(unittest.TestCase):
self.action_1_count += 1
handler = ReaderTestHandler()
reader.handle_log(reader.read(f), handler)
self.assertEquals(handler.action_0_count, 1)
self.assertEquals(handler.action_1_count, 1)
+
if __name__ == "__main__":
mozunit.main()
--- a/testing/mozbase/mozprocess/mozprocess/qijo.py
+++ b/testing/mozbase/mozprocess/mozprocess/qijo.py
@@ -75,16 +75,17 @@ class JOBOBJECT_ASSOCIATE_COMPLETION_POR
class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(Structure):
_fields_ = [('BasicLimitInformation', JOBOBJECT_BASIC_LIMIT_INFORMATION),
('IoInfo', IO_COUNTERS),
('ProcessMemoryLimit', SIZE_T),
('JobMemoryLimit', SIZE_T),
('PeakProcessMemoryUsed', SIZE_T),
('PeakJobMemoryUsed', SIZE_T)]
+
# These numbers below come from:
# http://msdn.microsoft.com/en-us/library/ms686216%28v=vs.85%29.aspx
JobObjectAssociateCompletionPortInformation = 7
JobObjectBasicAndIoAccountingInformation = 8
JobObjectExtendedLimitInformation = 9
class JobObjectInfo(object):
--- a/testing/mozbase/mozprocess/mozprocess/winprocess.py
+++ b/testing/mozbase/mozprocess/mozprocess/winprocess.py
@@ -94,16 +94,17 @@ class PROCESS_INFORMATION(Structure):
("dwProcessID", DWORD),
("dwThreadID", DWORD)]
def __init__(self):
Structure.__init__(self)
self.cb = sizeof(self)
+
LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
# STARTUPINFO structure
class STARTUPINFO(Structure):
_fields_ = [("cb", DWORD),
("lpReserved", LPWSTR),
@@ -119,16 +120,18 @@ class STARTUPINFO(Structure):
("dwFlags", DWORD),
("wShowWindow", WORD),
("cbReserved2", WORD),
("lpReserved2", LPBYTE),
("hStdInput", HANDLE),
("hStdOutput", HANDLE),
("hStdError", HANDLE)
]
+
+
LPSTARTUPINFO = POINTER(STARTUPINFO)
SW_HIDE = 0
STARTF_USESHOWWINDOW = 0x01
STARTF_USESIZE = 0x02
STARTF_USEPOSITION = 0x04
STARTF_USECOUNTCHARS = 0x08
@@ -155,16 +158,17 @@ class EnvironmentBlock:
if isinstance(k, bytes):
k = k.decode(fs_encoding, 'replace')
if isinstance(v, bytes):
v = v.decode(fs_encoding, 'replace')
values.append("{}={}".format(k, v))
values.append("")
self._as_parameter_ = LPCWSTR("\0".join(values))
+
# Error Messages we need to watch for go here
# See: http://msdn.microsoft.com/en-us/library/ms681388%28v=vs.85%29.aspx
ERROR_ABANDONED_WAIT_0 = 735
# GetLastError()
GetLastErrorProto = WINFUNCTYPE(DWORD) # Return Type
GetLastErrorFlags = ()
GetLastError = GetLastErrorProto(("GetLastError", windll.kernel32), GetLastErrorFlags)
@@ -197,16 +201,17 @@ CreateProcessFlags = ((1, "lpApplication
def ErrCheckCreateProcess(result, func, args):
ErrCheckBool(result, func, args)
# return a tuple (hProcess, hThread, dwProcessID, dwThreadID)
pi = args[9]
return AutoHANDLE(pi.hProcess), AutoHANDLE(pi.hThread), pi.dwProcessID, pi.dwThreadID
+
CreateProcess = CreateProcessProto(("CreateProcessW", windll.kernel32),
CreateProcessFlags)
CreateProcess.errcheck = ErrCheckCreateProcess
# flags for CreateProcess
CREATE_BREAKAWAY_FROM_JOB = 0x01000000
CREATE_DEFAULT_ERROR_MODE = 0x04000000
CREATE_NEW_CONSOLE = 0x00000010
@@ -356,16 +361,17 @@ except AttributeError:
# ResumeThread()
def ErrCheckResumeThread(result, func, args):
if result == -1:
raise WinError()
return args
+
ResumeThreadProto = WINFUNCTYPE(DWORD, # Return type
HANDLE # hThread
)
ResumeThreadFlags = ((1, "hThread"),)
ResumeThread = ResumeThreadProto(("ResumeThread", windll.kernel32),
ResumeThreadFlags)
ResumeThread.errcheck = ErrCheckResumeThread
--- a/testing/mozbase/mozprocess/tests/proclaunch.py
+++ b/testing/mozbase/mozprocess/tests/proclaunch.py
@@ -184,16 +184,17 @@ class ProcessLauncher(object):
:param running_time: Running time of the process in seconds.
"""
elapsed_time = 0
while elapsed_time < running_time:
time.sleep(self.UNIT_TIME)
elapsed_time += self.UNIT_TIME
+
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("manifest", help="Specify the configuration .ini file")
args = parser.parse_args()
proclaunch = ProcessLauncher(args.manifest)
proclaunch.run()
--- a/testing/mozbase/mozprocess/tests/test_mozprocess_kill.py
+++ b/testing/mozbase/mozprocess/tests/test_mozprocess_kill.py
@@ -85,10 +85,11 @@ class ProcTestKill(proctest.ProcTest):
p = processhandler.ProcessHandler([self.python, script, 'deadlock'])
p.run()
time.sleep(1)
p.kill()
self.assertEquals(p.proc.returncode, -signal.SIGKILL)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozprocess/tests/test_mozprocess_kill_broad_wait.py
+++ b/testing/mozbase/mozprocess/tests/test_mozprocess_kill_broad_wait.py
@@ -26,10 +26,11 @@ class ProcTestKill(proctest.ProcTest):
cwd=here)
p.run()
# Let the tree spawn a bit, before attempting to kill
time.sleep(3)
p.kill()
self.determine_status(p, expectedfail=('returncode',))
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozprocess/tests/test_mozprocess_misc.py
+++ b/testing/mozbase/mozprocess/tests/test_mozprocess_misc.py
@@ -34,10 +34,11 @@ class ProcTestMisc(proctest.ProcTest):
}
p = processhandler.ProcessHandler([self.python, self.proclaunch,
"process_normal_finish_python.ini"],
cwd=here, env=env)
# passes if no exceptions are raised
p.run()
p.wait()
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozprocess/tests/test_mozprocess_output.py
+++ b/testing/mozbase/mozprocess/tests/test_mozprocess_output.py
@@ -50,10 +50,11 @@ class ProcTestOutput(proctest.ProcTest):
# make sure mozprocess doesn't close the stream
# since mozprocess didn't create it
self.assertFalse(buf.closed)
buf.close()
self.determine_status(p, False, ())
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozprocess/tests/test_mozprocess_wait.py
+++ b/testing/mozbase/mozprocess/tests/test_mozprocess_wait.py
@@ -89,10 +89,11 @@ class ProcTestWait(proctest.ProcTest):
self.determine_status(p)
self.assertLess(returncode2, 0,
'Negative returncode expected, got "%s"' % returncode2)
self.assertEqual(returncode1, returncode2,
'Expected both returncodes of wait() to be equal')
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozprofile/mozprofile/cli.py
+++ b/testing/mozbase/mozprofile/mozprofile/cli.py
@@ -122,10 +122,11 @@ def cli(args=sys.argv[1:]):
# view the profile, if specified
print profile.summary()
return
# if no profile was passed in print the newly created profile
if not cli.options.profile:
print profile.profile
+
if __name__ == '__main__':
cli()
--- a/testing/mozbase/mozprofile/mozprofile/diff.py
+++ b/testing/mozbase/mozprofile/mozprofile/diff.py
@@ -72,10 +72,11 @@ def diff_profiles(args=sys.argv[1:]):
# display them
while diffs:
key, value = diffs.pop(0)
print '[%s]:\n' % key
print value
if diffs:
print '-' * 4
+
if __name__ == '__main__':
diff_profiles()
--- a/testing/mozbase/mozprofile/mozprofile/view.py
+++ b/testing/mozbase/mozprofile/mozprofile/view.py
@@ -34,10 +34,11 @@ def view_profile(args=sys.argv[1:]):
# print summary for each profile
while args:
path = args.pop(0)
profile = mozprofile.Profile(path)
print profile.summary()
if args:
print '-' * 4
+
if __name__ == '__main__':
view_profile()
--- a/testing/mozbase/mozprofile/tests/addonid.py
+++ b/testing/mozbase/mozprofile/tests/addonid.py
@@ -178,10 +178,11 @@ class AddonIDTest(unittest.TestCase):
<em:maxVersion>42.0a2</em:maxVersion>
</Description>
</em:targetApplication>
</Description>
</RDF>
"""]
return tests
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozprofile/tests/bug785146.py
+++ b/testing/mozbase/mozprofile/tests/bug785146.py
@@ -45,10 +45,11 @@ http://127.0.0.1:8888 privileg
con = sqlite3.connect(perms_db_filename)
cur = con.cursor()
cur.execute(stmt)
entries = cur.fetchall()
schema_version = entries[0][0]
self.assertEqual(schema_version, 5)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozprofile/tests/permissions.py
+++ b/testing/mozbase/mozprofile/tests/permissions.py
@@ -193,10 +193,11 @@ http://127.0.0.1:8888 privileg
self.verify_user_version(3)
def test_existing_permissions_db_v4(self):
self.verify_user_version(4)
def test_existing_permissions_db_v5(self):
self.verify_user_version(5)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozprofile/tests/test_nonce.py
+++ b/testing/mozbase/mozprofile/tests/test_nonce.py
@@ -43,10 +43,11 @@ class PreferencesNonceTest(unittest.Test
self.assertEqual(dict(prefs), {'foo': 'bar', 'fleem': 'baz'})
# cleanup the profile;
# this should remove the new preferences but not the old
profile.cleanup()
prefs = Preferences.read_prefs(user_js)
self.assertEqual(dict(prefs), {'foo': 'bar'})
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozprofile/tests/test_preferences.py
+++ b/testing/mozbase/mozprofile/tests/test_preferences.py
@@ -372,10 +372,11 @@ user_pref("webgl.force-enabled", true);
httpd.start(block=False)
# read preferences through the web
read = prefs.read_prefs('http://%s:%d/prefs_with_comments.js' % (host, port))
self.assertEqual(dict(read), self._prefs_with_comments)
finally:
httpd.stop()
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozprofile/tests/test_profile_view.py
+++ b/testing/mozbase/mozprofile/tests/test_profile_view.py
@@ -68,10 +68,11 @@ class TestProfilePrint(unittest.TestCase
diff = dict(mozprofile.diff(profile2, ff_profile))
self.assertEqual(diff.keys(), ['user.js'])
lines = [line.strip() for line in diff['user.js'].splitlines()]
self.assertTrue('-foo: bar' in lines)
ff_pref_lines = ['+%s: %s' % (key, value)
for key, value in mozprofile.FirefoxProfile.preferences.items()]
self.assertTrue(set(ff_pref_lines).issubset(lines))
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozrunner/mozrunner/utils.py
+++ b/testing/mozbase/mozrunner/mozrunner/utils.py
@@ -56,16 +56,17 @@ def findInPath(fileName, path=os.environ
dirs = path.split(os.pathsep)
for dir in dirs:
if os.path.isfile(os.path.join(dir, fileName)):
return os.path.join(dir, fileName)
if mozinfo.isWin:
if os.path.isfile(os.path.join(dir, fileName + ".exe")):
return os.path.join(dir, fileName + ".exe")
+
if __name__ == '__main__':
for i in sys.argv[1:]:
print findInPath(i)
def _find_marionette_in_args(*args, **kwargs):
try:
m = [a for a in args + tuple(kwargs.values()) if hasattr(a, 'session')][0]
--- a/testing/mozbase/moztest/tests/test.py
+++ b/testing/mozbase/moztest/tests/test.py
@@ -48,10 +48,11 @@ class Collection(unittest.TestCase):
t4 = TestResult('t4', context=c4)
self.collection = TestResultCollection('tests')
self.collection.extend([t1, t2, t3, t4])
def test_unique_contexts(self):
self.assertEqual(len(self.collection.contexts), 3)
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozversion/mozversion/mozversion.py
+++ b/testing/mozbase/mozversion/mozversion/mozversion.py
@@ -318,10 +318,11 @@ def cli(args=sys.argv[1:]):
get_version(binary=args.binary,
sources=args.sources,
host=host,
device_serial=args.device,
adb_host=args.adb_host,
adb_port=args.adb_port)
+
if __name__ == '__main__':
cli()
--- a/testing/mozbase/mozversion/tests/test_apk.py
+++ b/testing/mozbase/mozversion/tests/test_apk.py
@@ -37,10 +37,11 @@ class ApkTest(unittest.TestCase):
def test_with_package_name(self):
with mozfile.NamedTemporaryFile() as f:
with zipfile.ZipFile(f.name, 'w') as z:
self.create_apk_zipfiles(z)
z.writestr('package-name.txt', "org.mozilla.fennec")
v = get_version(f.name)
self.assertEqual(v.get('package_name'), "org.mozilla.fennec")
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/mozversion/tests/test_b2g.py
+++ b/testing/mozbase/mozversion/tests/test_b2g.py
@@ -65,10 +65,11 @@ class SourcesTest(unittest.TestCase):
self.assertIsNone(v.get('gaia_date'))
def test_missing_gaia_commit(self):
self._create_zip()
v = get_version(self.binary)
self.assertIsNone(v.get('gaia_changeset'))
self.assertIsNone(v.get('gaia_date'))
+
if __name__ == '__main__':
mozunit.main()
--- a/testing/mozbase/setup_development.py
+++ b/testing/mozbase/setup_development.py
@@ -264,10 +264,11 @@ def main(args=sys.argv[1:]):
for package in test_packages:
call(['easy_install', package])
# install extra non-mozbase packages if desired
if options.extra:
for package in extra_packages:
call(['easy_install', package])
+
if __name__ == '__main__':
main()
--- a/testing/mozharness/mozprocess/qijo.py
+++ b/testing/mozharness/mozprocess/qijo.py
@@ -75,16 +75,17 @@ class JOBOBJECT_ASSOCIATE_COMPLETION_POR
class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(Structure):
_fields_ = [('BasicLimitInformation', JOBOBJECT_BASIC_LIMIT_INFORMATION),
('IoInfo', IO_COUNTERS),
('ProcessMemoryLimit', SIZE_T),
('JobMemoryLimit', SIZE_T),
('PeakProcessMemoryUsed', SIZE_T),
('PeakJobMemoryUsed', SIZE_T)]
+
# These numbers below come from:
# http://msdn.microsoft.com/en-us/library/ms686216%28v=vs.85%29.aspx
JobObjectAssociateCompletionPortInformation = 7
JobObjectBasicAndIoAccountingInformation = 8
JobObjectExtendedLimitInformation = 9
class JobObjectInfo(object):
--- a/testing/mozharness/mozprocess/winprocess.py
+++ b/testing/mozharness/mozprocess/winprocess.py
@@ -94,16 +94,17 @@ class PROCESS_INFORMATION(Structure):
("dwProcessID", DWORD),
("dwThreadID", DWORD)]
def __init__(self):
Structure.__init__(self)
self.cb = sizeof(self)
+
LPPROCESS_INFORMATION = POINTER(PROCESS_INFORMATION)
# STARTUPINFO structure
class STARTUPINFO(Structure):
_fields_ = [("cb", DWORD),
("lpReserved", LPWSTR),
@@ -119,16 +120,18 @@ class STARTUPINFO(Structure):
("dwFlags", DWORD),
("wShowWindow", WORD),
("cbReserved2", WORD),
("lpReserved2", LPBYTE),
("hStdInput", HANDLE),
("hStdOutput", HANDLE),
("hStdError", HANDLE)
]
+
+
LPSTARTUPINFO = POINTER(STARTUPINFO)
SW_HIDE = 0
STARTF_USESHOWWINDOW = 0x01
STARTF_USESIZE = 0x02
STARTF_USEPOSITION = 0x04
STARTF_USECOUNTCHARS = 0x08
@@ -155,16 +158,17 @@ class EnvironmentBlock:
if isinstance(k, bytes):
k = k.decode(fs_encoding, 'replace')
if isinstance(v, bytes):
v = v.decode(fs_encoding, 'replace')
values.append("{}={}".format(k, v))
values.append("")
self._as_parameter_ = LPCWSTR("\0".join(values))
+
# Error Messages we need to watch for go here
# See: http://msdn.microsoft.com/en-us/library/ms681388%28v=vs.85%29.aspx
ERROR_ABANDONED_WAIT_0 = 735
# GetLastError()
GetLastErrorProto = WINFUNCTYPE(DWORD) # Return Type
GetLastErrorFlags = ()
GetLastError = GetLastErrorProto(("GetLastError", windll.kernel32), GetLastErrorFlags)
@@ -197,16 +201,17 @@ CreateProcessFlags = ((1, "lpApplication
def ErrCheckCreateProcess(result, func, args):
ErrCheckBool(result, func, args)
# return a tuple (hProcess, hThread, dwProcessID, dwThreadID)
pi = args[9]
return AutoHANDLE(pi.hProcess), AutoHANDLE(pi.hThread), pi.dwProcessID, pi.dwThreadID
+
CreateProcess = CreateProcessProto(("CreateProcessW", windll.kernel32),
CreateProcessFlags)
CreateProcess.errcheck = ErrCheckCreateProcess
# flags for CreateProcess
CREATE_BREAKAWAY_FROM_JOB = 0x01000000
CREATE_DEFAULT_ERROR_MODE = 0x04000000
CREATE_NEW_CONSOLE = 0x00000010
@@ -356,16 +361,17 @@ except AttributeError:
# ResumeThread()
def ErrCheckResumeThread(result, func, args):
if result == -1:
raise WinError()
return args
+
ResumeThreadProto = WINFUNCTYPE(DWORD, # Return type
HANDLE # hThread
)
ResumeThreadFlags = ((1, "hThread"),)
ResumeThread = ResumeThreadProto(("ResumeThread", windll.kernel32),
ResumeThreadFlags)
ResumeThread.errcheck = ErrCheckResumeThread
--- a/testing/talos/INSTALL.py
+++ b/testing/talos/INSTALL.py
@@ -61,10 +61,11 @@ def main(args=sys.argv[1:]):
if os.path.exists(virtualenv_python):
break
else:
raise AssertionError('virtualenv python not found')
# install talos into the virtualenv
call([os.path.abspath(virtualenv_python), 'setup.py', 'develop'], cwd=here)
+
if __name__ == '__main__':
main()
--- a/testing/talos/talos/cmanager_win32.py
+++ b/testing/talos/talos/cmanager_win32.py
@@ -18,16 +18,17 @@ pdh = windll.pdh
class _PDH_COUNTER_PATH_ELEMENTS_A(Structure):
_fields_ = [("szMachineName", LPSTR),
("szObjectName", LPSTR),
("szInstanceName", LPSTR),
("szParentInstance", LPSTR),
("dwInstanceIndex", DWORD),
("szCounterName", LPSTR)]
+
_PDH_MORE_DATA = -2147481646 # the need more space error
def _getExpandedCounterPaths(processName, counterName):
'''
Get list of expanded counter paths given a counter name. Returns a
list of strings or None, if no counter paths can be created
'''
@@ -73,16 +74,17 @@ class _PDH_Counter_Union(Union):
('AnsiStringValue', LPCSTR),
('WideStringValue', LPCWSTR)]
class _PDH_FMT_COUNTERVALUE(Structure):
_fields_ = [('CStatus', DWORD),
('union', _PDH_Counter_Union)]
+
_PDH_FMT_LONG = 0x00000100
class WinCounterManager(CounterManager):
def __init__(self, process_name, process, counters,
childProcess="plugin-container"):
CounterManager.__init__(self)
--- a/testing/talos/talos/mainthreadio.py
+++ b/testing/talos/talos/mainthreadio.py
@@ -148,11 +148,12 @@ def main(argv):
# search for duration > 1.0
errors = wl.checkDuration(data, TUPLE_FILENAME_INDEX, 'Duration')
if errors:
strs = wl.get_error_strings(errors)
wl.print_errors(strs)
return 0
+
if __name__ == "__main__":
import sys
sys.exit(main(sys.argv))
--- a/testing/talos/talos/scripts/report.py
+++ b/testing/talos/talos/scripts/report.py
@@ -128,10 +128,11 @@ def main():
if args.test:
tuple_list = filter(lambda x: x[3] == args.test, tuple_list)
f += '-%s' % args.test
f += '-%s' % args.mode
generate_report(tuple_list, filepath=f + '.csv', mode=args.mode)
+
if __name__ == "__main__":
main()
--- a/testing/talos/talos/xtalos/etlparser.py
+++ b/testing/talos/talos/xtalos/etlparser.py
@@ -510,10 +510,11 @@ def main(args=sys.argv[1:]):
parser.error("No process ID argument given")
# call API
etlparser(args.xperf_path, args.etl_filename, args.processID, args.approot,
args.configFile, args.outputFile, args.whitelist_file,
args.error_filename, args.all_stages, args.all_threads,
debug=args.debug_level >= xtalos.DEBUG_INFO)
+
if __name__ == "__main__":
main()
--- a/testing/talos/talos/xtalos/parse_xperf.py
+++ b/testing/talos/talos/xtalos/parse_xperf.py
@@ -65,10 +65,11 @@ def main(args=sys.argv[1:]):
# start xperf
try:
stop_from_config(config_file=args.configFile,
debug=args.debug_level >= xtalos.DEBUG_INFO,
**args.__dict__)
except xtalos.XTalosError as e:
parser.error(str(e))
+
if __name__ == "__main__":
main()
--- a/testing/talos/talos_from_code.py
+++ b/testing/talos/talos_from_code.py
@@ -119,10 +119,11 @@ def download_file(url, path="", saveAs=N
def get_value(json_filename, key):
'''
It loads up a JSON file and returns the value for the given string
'''
f = open(json_filename, 'r')
return json.load(f)[key]
+
if __name__ == '__main__':
main()
--- a/testing/talos/tests/test_browser_output.py
+++ b/testing/talos/tests/test_browser_output.py
@@ -181,10 +181,11 @@ class TestTalosError(unittest.TestCase):
test TalosError class
"""
def test_browser_log_results(self):
# an example that should fail
# passing invalid value for argument result_raw
with self.assertRaises(TalosError):
BrowserLogResults(results_raw="__FAIL<bad test>__FAIL")
+
if __name__ == '__main__':
unittest.main()
--- a/testing/talos/tests/test_filter.py
+++ b/testing/talos/tests/test_filter.py
@@ -69,10 +69,11 @@ class TestFilter(unittest.TestCase):
# an example that should fail
self.assertRaises(ValueError, talos.filter.parse, 'foo:bar')
self.assertRaises(ValueError, talos.filter.parse, 'foo:1,')
# delete foo again
del talos.filter.scalar_filters['foo']
+
if __name__ == '__main__':
unittest.main()
--- a/testing/talos/tests/test_results.py
+++ b/testing/talos/tests/test_results.py
@@ -70,10 +70,11 @@ class TestPageloaderResults(unittest.Tes
self.assertEqual(filtered[-1][0], 1622.)
# apply some different filters
filters = [[talos.filter.ignore_max, []], [max, []]]
filtered = results.filter(*filters)
self.assertEqual(filtered[0][0], 68.)
self.assertEqual(filtered[-1][0], 1623.)
+
if __name__ == '__main__':
unittest.main()
--- a/testing/talos/tests/test_talosconfig.py
+++ b/testing/talos/tests/test_talosconfig.py
@@ -146,10 +146,11 @@ class TalosConfigUnitTest(unittest.TestC
# Checking keyerror when calling processID when xperf_providers is missing
with self.assertRaises(KeyError):
self.validate(content['processID'], "None")
# Checking keyerror when calling approot when xperf_providers is missing
with self.assertRaises(KeyError):
self.validate(content['approot'], "test/path/to")
+
if __name__ == '__main__':
unittest.main()
--- a/testing/talos/tests/test_urlsplit.py
+++ b/testing/talos/tests/test_urlsplit.py
@@ -44,10 +44,11 @@ class TestURLParsing(unittest.TestCase):
to be file:// URLs
"""
path = '/foo/bar'
parsed = talos.utils.urlsplit(path)
self.assertEqual(parsed,
['file', '', '/foo/bar', '', ''])
+
if __name__ == '__main__':
unittest.main()
--- a/testing/talos/tests/test_xrestop.py
+++ b/testing/talos/tests/test_xrestop.py
@@ -54,10 +54,11 @@ class TestXrestop(unittest.TestCase):
pid = 1668
self.assertTrue(pid in output)
terminal = output[pid]
self.assertEqual(terminal['pixmap bytes'], '1943716')
# cleanup: set subprocess.Popen back
subprocess.Popen = Popen
+
if __name__ == '__main__':
unittest.main()
--- a/toolkit/components/telemetry/gen-event-data.py
+++ b/toolkit/components/telemetry/gen-event-data.py
@@ -141,10 +141,11 @@ def main(output, *filenames):
string_table_name = "gEventsStringTable"
string_table.writeDefinition(output, string_table_name)
static_assert(output, "sizeof(%s) <= UINT32_MAX" % string_table_name,
"index overflow")
print("", file=output)
print(file_footer, file=output)
+
if __name__ == '__main__':
main(sys.stdout, *sys.argv[1:])
--- a/toolkit/components/telemetry/gen-event-enum.py
+++ b/toolkit/components/telemetry/gen-event-enum.py
@@ -71,10 +71,11 @@ def main(output, *filenames):
print("#endif", file=output)
print("};\n", file=output)
print("const uint32_t EventCount = %d;\n" % index, file=output)
print(file_footer, file=output)
+
if __name__ == '__main__':
main(sys.stdout, *sys.argv[1:])
--- a/toolkit/components/telemetry/gen-histogram-bucket-ranges.py
+++ b/toolkit/components/telemetry/gen-histogram-bucket-ranges.py
@@ -44,9 +44,10 @@ def main(argv):
parameters['bucket_count'] = len(buckets)
except histogram_tools.DefinitionException:
continue
all_histograms.update({name: parameters})
print json.dumps({'histograms': all_histograms})
+
main(sys.argv[1:])
--- a/toolkit/components/telemetry/gen-histogram-data.py
+++ b/toolkit/components/telemetry/gen-histogram-data.py
@@ -188,10 +188,11 @@ def main(output, *filenames):
print("\nError processing histograms:\n" + str(ex) + "\n")
sys.exit(1)
print(banner, file=output)
write_histogram_table(output, histograms)
write_histogram_static_asserts(output, histograms)
write_debug_histogram_ranges(output, histograms)
+
if __name__ == '__main__':
main(sys.stdout, *sys.argv[1:])
--- a/toolkit/components/telemetry/gen-histogram-enum.py
+++ b/toolkit/components/telemetry/gen-histogram-enum.py
@@ -108,10 +108,11 @@ def main(output, *filenames):
print("\ntemplate<class T> struct CategoricalLabelId {};", file=output)
for name, _, id in enums:
print("template<> struct CategoricalLabelId<%s> : "
"IntegralConstant<uint32_t, %s> {};" % (name, id), file=output)
# Footer.
print(footer, file=output)
+
if __name__ == '__main__':
main(sys.stdout, *sys.argv[1:])
--- a/toolkit/components/telemetry/gen-process-data.py
+++ b/toolkit/components/telemetry/gen-process-data.py
@@ -63,10 +63,11 @@ def main(output, *filenames):
print(banner, file=output)
print(file_header, file=output)
write_processes_data(processes, output)
print(file_footer, file=output)
except ParserError as ex:
print("\nError generating processes data:\n" + str(ex) + "\n")
sys.exit(1)
+
if __name__ == '__main__':
main(sys.stdout, *sys.argv[1:])
--- a/toolkit/components/telemetry/gen-process-enum.py
+++ b/toolkit/components/telemetry/gen-process-enum.py
@@ -57,10 +57,11 @@ def main(output, *filenames):
print(banner, file=output)
print(file_header, file=output)
write_processes_enum(processes, output)
print(file_footer, file=output)
except ParserError as ex:
print("\nError generating processes enums:\n" + str(ex) + "\n")
sys.exit(1)
+
if __name__ == '__main__':
main(sys.stdout, *sys.argv[1:])
--- a/toolkit/components/telemetry/gen-scalar-data.py
+++ b/toolkit/components/telemetry/gen-scalar-data.py
@@ -90,10 +90,11 @@ def main(output, *filenames):
sys.exit(1)
# Write the scalar data file.
print(banner, file=output)
print(file_header, file=output)
write_scalar_tables(scalars, output)
print(file_footer, file=output)
+
if __name__ == '__main__':
main(sys.stdout, *sys.argv[1:])
--- a/toolkit/components/telemetry/gen-scalar-enum.py
+++ b/toolkit/components/telemetry/gen-scalar-enum.py
@@ -54,10 +54,11 @@ def main(output, *filenames):
print(" %s," % s.enum_label, file=output)
if cpp_guard:
print("#endif", file=output)
print(" ScalarCount,", file=output)
print(file_footer, file=output)
+
if __name__ == '__main__':
main(sys.stdout, *sys.argv[1:])
--- a/toolkit/components/telemetry/histogram_tools.py
+++ b/toolkit/components/telemetry/histogram_tools.py
@@ -64,16 +64,17 @@ def exponential_buckets(dmin, dmax, n_bu
next_value = int(math.floor(math.exp(log_next) + 0.5))
if next_value > current:
current = next_value
else:
current = current + 1
ret_array[bucket_index] = current
return ret_array
+
always_allowed_keys = ['kind', 'description', 'cpp_guard', 'expires_in_version',
'alert_emails', 'keyed', 'releaseChannelCollection',
'bug_numbers', 'record_in_processes']
whitelists = None
def load_whitelist():
@@ -575,16 +576,17 @@ def from_nsDeprecatedOperationList(filen
'kind': 'boolean',
'description': 'Whether a %s used %s' % (context, op)
}
add_counter('document')
add_counter('page')
return histograms
+
FILENAME_PARSERS = {
'Histograms.json': from_Histograms_json,
'nsDeprecatedOperationList.h': from_nsDeprecatedOperationList,
}
# Similarly to the dance above with buildconfig, usecounters may not be
# available, so handle that gracefully.
try:
--- a/toolkit/components/telemetry/tests/marionette/harness/setup.py
+++ b/toolkit/components/telemetry/tests/marionette/harness/setup.py
@@ -10,16 +10,17 @@ PACKAGE_VERSION = '0.1'
THIS_DIR = os.path.dirname(os.path.realpath(__name__))
def read(*parts):
with open(os.path.join(THIS_DIR, *parts)) as f:
return f.read()
+
setup(name='telemetry-harness',
version=PACKAGE_VERSION,
description=("""Custom Marionette runner classes and entry scripts for Telemetry
specific Marionette tests."""),
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)',
--- a/toolkit/components/telemetry/tests/marionette/harness/telemetry_harness/runtests.py
+++ b/toolkit/components/telemetry/tests/marionette/harness/telemetry_harness/runtests.py
@@ -4,10 +4,11 @@
from marionette_harness.runtests import cli as mn_cli
from testcase import TelemetryTestCase
def cli():
mn_cli(testcase_class=TelemetryTestCase)
+
if __name__ == '__main__':
cli()