rem
stringlengths
0
322k
add
stringlengths
0
2.05M
context
stringlengths
8
228k
lambda self, selectors: self.assertEqual( selectors.test_run.attachments, {}), lambda self, selectors: self.assertEqual( selectors.test_run.sw_context, None), lambda self, selectors: self.assertEqual( selectors.test_run.hw_context, None), ] }), ('analyzer_assigned_uuid_is_parsed_as_uuid', { 'json_text': """ { "test_run...
def test_deserialize_clears_old_error_on_success(self): BundleDeserializationError.objects.create( bundle = self.bundle, error_message="not important").save() mock = self.mocker.patch(self.bundle) expect(mock._do_deserialize()) self.mocker.replay() self.bundle.deserialize() # note we cannot check for self.bundle.deseri...
] }), ('analyzer_assigned_date_is_parsed_as_datetime', { 'json_text': """ { "test_runs": [{ "analyzer_assigned_date": "2010-12-31T23:59:59Z" }] } """, 'selectors': { 'test_run': lambda bundle: bundle.test_runs[0] }, 'validators': [ lambda self, selectors: self.assertEqual(
lambda self, selectors: self.assertEqual(
def test_deserialize_clears_old_error_on_success(self): BundleDeserializationError.objects.create( bundle = self.bundle, error_message="not important").save() mock = self.mocker.patch(self.bundle) expect(mock._do_deserialize()) self.mocker.replay() self.bundle.deserialize() # note we cannot check for self.bundle.deseri...
]
lambda self, selectors: self.assertEqual( selectors.test_run.time_check_performed, False), lambda self, selectors: self.assertEqual( selectors.test_run.attributes, {}), lambda self, selectors: self.assertEqual( selectors.test_run.attachments, {}), lambda self, selectors: self.assertEqual( selectors.test_run.sw_context,...
def test_deserialize_clears_old_error_on_success(self): BundleDeserializationError.objects.create( bundle = self.bundle, error_message="not important").save() mock = self.mocker.patch(self.bundle) expect(mock._do_deserialize()) self.mocker.replay() self.bundle.deserialize() # note we cannot check for self.bundle.deseri...
('software_context_defaults', {
('software_context_parsing', {
def test_deserialize_clears_old_error_on_success(self): BundleDeserializationError.objects.create( bundle = self.bundle, error_message="not important").save() mock = self.mocker.patch(self.bundle) expect(mock._do_deserialize()) self.mocker.replay() self.bundle.deserialize() # note we cannot check for self.bundle.deseri...
"test_id": "some_test",
def test_deserialize_clears_old_error_on_success(self): BundleDeserializationError.objects.create( bundle = self.bundle, error_message="not important").save() mock = self.mocker.patch(self.bundle) expect(mock._do_deserialize()) self.mocker.replay() self.bundle.deserialize() # note we cannot check for self.bundle.deseri...
to_hide = set(self._hook.prohibited)
to_hide = set()
def mock_imports(self, reload_list=None): """ Make prohibit_importing() work by hiding and importing again all the modules that depended on an imported prohibited module.
self.format = format or self.FORMAT self.test_runs = test_runs or []
if format is None: format = self.FORMAT if test_runs is None: test_runs = [] self.format = format self.test_runs = test_runs
def __init__(self, format=None, test_runs=None): self.format = format or self.FORMAT self.test_runs = test_runs or []
print "DEBUG ", dir(test_results) print "DEBUG ", test_results.start_index
def test_run_detail(request, analyzer_assigned_uuid): test_run = get_object_or_404(TestRun, analyzer_assigned_uuid=analyzer_assigned_uuid) if test_run.bundle.bundle_stream.can_access(request.user): from django.core.paginator import Paginator, InvalidPage, EmptyPage paginator = Paginator(test_run.test_results.all(), 25)...
def test_construction_1(self): name = object() sw_image = SoftwareImage(name) self.assertTrue(sw_image.name is name) def test_construction_2(self): name = object() sw_image = SoftwareImage(name=name) self.assertTrue(sw_image.name is name)
def test_construction_argument_one_sets_desc(self): desc = object() sw_image = SoftwareImage(desc) self.assertTrue(sw_image.desc is desc) def test_construction_argument_is_called_desc(self): desc = object() sw_image = SoftwareImage(desc=desc) self.assertTrue(sw_image.desc is desc)
def test_construction_1(self): name = object() sw_image = SoftwareImage(name) self.assertTrue(sw_image.name is name)
class BundleStreamDetailViewAuthenticatedTest(TestCase):
class BundleStreamDetailViewAuthorizedTest(BundleStreamDetailViewAnonymousTest):
def test_template_used(self): response = self.client.get("/streams" + self.bundle_stream.pathname) if self.bundle_stream.can_access(self.user): self.assertTemplateUsed(response, "dashboard_app/bundle_stream_detail.html") else: self.assertTemplateUsed(response, "403.html")
raise ValueError("Test id must be None or a string with reverse domain name")
raise ValueError("Test id must be None or a string with reverse " "domain name")
def _set_test_id(self, test_id): if test_id is not None and not self._TEST_ID_PATTERN.match(test_id): raise ValueError("Test id must be None or a string with reverse domain name") self._test_id = test_id
slots = [slot[1:] if slot.startswith('_') else slot for slot in self.__slots__]
slots = [s[1:] if s.startswith('_') else s for s in self.__slots__]
def __repr__(self): """ Produce more-less human readable encoding of all fields.
if timestamp is not None and not isinstance(timestamp, datetime.datetime): raise TypeError("Timestamp must be None or datetime.datetime() instance")
if timestamp is not None and not isinstance(timestamp, datetime.datetime): raise TypeError("Timestamp must be None or datetime.datetime() " "instance")
def _set_timestamp(self, timestamp): if timestamp is not None and not isinstance(timestamp, datetime.datetime): raise TypeError("Timestamp must be None or datetime.datetime() instance") self._timestamp = timestamp
if duration is not None and not isinstance(duration, datetime.timedelta): raise TypeError("duration must be None or datetime.timedelta() instance")
if duration is not None and not isinstance(duration, datetime.timedelta): raise TypeError("duration must be None or datetime.timedelta() " "instance")
def _set_duration(self, duration): if duration is not None and not isinstance(duration, datetime.timedelta): raise TypeError("duration must be None or datetime.timedelta() instance") if duration is not None and duration.days < 0: raise ValueError("duration cannot be negative") self._duration = duration
"cause": linaro_json.json.decoder.JSONDecodeError
"cause": ValueError,
def test_TestResult__attributes(self): self.assertEqual( self._attrs2set(self.s_test_result.attributes.all()), frozenset([ ("attr1", "value1"), ("attr2", "value2")]))
self.assertEqual(self.cause, type(ex.cause))
self.assertIsInstance(ex.cause, self.cause)
def test_json_to_memory_model_failure(self): deserializer = BundleDeserializer() try: deserializer.json_to_memory_model(self.json_text) except DocumentError as ex: self.assertEqual(self.cause, type(ex.cause)) else: self.fail("Should have raised an exception")
} for bundle in bundle_stream.bundles.all()]
} for bundle in bundle_stream.bundles.all().order_by("uploaded_on")]
def bundles(self, pathname): """ Name ---- `bundles` (`pathname`)
if self.deserialization_error.exists():
if self.deserialization_error.count():
def deserialize(self): """ Deserialize the contents of this bundle.
users = set() groups = set()
def created_bundle_streams(spec): """ Helper context manager that creates bundle streams according to specification spec is a list of dictionaries with the following keys: user: string indicating user name to create [optional] group: string indicating group name to create [optional] slug: slug-like name [optional] nam...
users.add(user)
def created_bundle_streams(spec): """ Helper context manager that creates bundle streams according to specification spec is a list of dictionaries with the following keys: user: string indicating user name to create [optional] group: string indicating group name to create [optional] slug: slug-like name [optional] nam...
groups.add(group)
def created_bundle_streams(spec): """ Helper context manager that creates bundle streams according to specification spec is a list of dictionaries with the following keys: user: string indicating user name to create [optional] group: string indicating group name to create [optional] slug: slug-like name [optional] nam...
for bundle_stream in bundle_streams: bundle_stream.delete() for user in users: user.delete() for group in groups: group.delete()
def created_bundle_streams(spec): """ Helper context manager that creates bundle streams according to specification spec is a list of dictionaries with the following keys: user: string indicating user name to create [optional] group: string indicating group name to create [optional] slug: slug-like name [optional] nam...
class CSRFExemptForXMLRPCAPITestCase(CSRFTestCase, DashboardAPITestCase):
def test_cross_site_login_fails(self): response = self.client.post(self.login_path, { 'user': 'user', 'pass': 'pass'}) self.assertEquals(response.status_code, 403)
response = self.client.post( self.endpoint_path, request_body, "text/xml")
response = self.client.post(endpoint_path, request_body, "text/xml")
def test_csrf_not_protecting_xml_rpc_views(self): """call version and check that we didn't get 403""" request_body = xmlrpclib.dumps((), methodname="version") response = self.client.post( self.endpoint_path, request_body, "text/xml") self.assertContains(response, "<methodResponse>", status_code=200)
urls = 'dashboard_app.test_urls'
def test_test_result__unknown(self): obj = TestResult(result=TestResult.RESULT_UNKNOWN, id=1) self.assertEqual(unicode(obj), "#1 unknown")
endpoint_path = reverse("dashboard_app.dashboard_xml_rpc_handler")
endpoint_path = reverse("xml-rpc")
def test_csrf_not_protecting_xml_rpc_views(self): """call version and check that we didn't get 403""" endpoint_path = reverse("dashboard_app.dashboard_xml_rpc_handler") request_body = xmlrpclib.dumps((), methodname="version") response = self.client.post(endpoint_path, request_body, "text/xml") self.assertContains(respo...
self.prohibit_importing('debian.debian_support') self.mock_imports('launch_control.sw_profile') mocker = Mocker() obj = mocker.replace('debian_bundle.debian_support.version_compare') mocker.replay() import launch_control.sw_profile self.assertTrue(launch_control.sw_profile.debian_version_compare is obj) mocker.verify()...
try: import debian except ImportError: pass else: self.prohibit_importing('debian.debian_support') self.mock_imports('launch_control.sw_profile') mocker = Mocker() obj = mocker.replace('debian_bundle.debian_support.version_compare') mocker.replay() import launch_control.sw_profile self.assertTrue(launch_control.sw_prof...
def test_debian_import_failure(self): """ Make sure we import debian_bundle if debian is not available """ self.prohibit_importing('debian.debian_support') self.mock_imports('launch_control.sw_profile') mocker = Mocker() obj = mocker.replace('debian_bundle.debian_support.version_compare') mocker.replay() import launch_...
this sample. The quantity describes a value of certain type. See the units property to know more. Measurement can be None on failed tests only. >>> sample = QuantitativeSample('test-id', None, ... test_result='fail') >>> sample.measurement is None True We expect to have some value if the test was carried out corr...
a test result. The quantity describes a value of certain type. See the units property to know more. Measurement must be a number. Either int, long, float or Decimal: >>> result = TestResult('some-test', 'unknown') >>> result.measurement = 10 >>> result.measurement = 10L >>> result.measurement = 10.0 >>> result.measure...
def _set_measurement(self, value): valid_types = (int, long, float, Decimal, NoneType) if not isinstance(value, valid_types): raise TypeError("Measurement must be an int, long, float, Decimal or None") self._measurement = value
>>> sample.measurement = "great" Traceback (most recent call last): ... TypeError: Measurement must be an int, long or float
>>> result.measurement = "great" Traceback (most recent call last): ... TypeError: Measurement must be an int, long, float, Decimal or None
def _set_measurement(self, value): valid_types = (int, long, float, Decimal, NoneType) if not isinstance(value, valid_types): raise TypeError("Measurement must be an int, long, float, Decimal or None") self._measurement = value
>>> sample = QualitativeSample('fail')
>>> sample = TestResult('some-test-case', 'fail')
def _set_duration(self, duration): if duration is not None and not isinstance(duration, timedelta): raise TypeError("Duration must be None or timedelta " "instance") if duration is not None and duration.days < 0: raise ValueError("Duration cannot be negative") self._duration = duration
netloc = "%s:%s@%s:%d" % (
netloc = "%s:%s@%s" % (
def __init__(self, parser, args): super(XMLRPCCommand, self).__init__(parser, args) parts = urlparse.urlsplit(args.dashboard_url) if args.username and args.password: netloc = "%s:%s@%s:%d" % ( args.username, args.password, parts.host, parts.port or 80) else: netloc = parts.netloc urltext = urlparse.urlunsplit((parts.sc...
parts.host, parts.port or 80)
parts.netloc)
def __init__(self, parser, args): super(XMLRPCCommand, self).__init__(parser, args) parts = urlparse.urlsplit(args.dashboard_url) if args.username and args.password: netloc = "%s:%s@%s:%d" % ( args.username, args.password, parts.host, parts.port or 80) else: netloc = parts.netloc urltext = urlparse.urlunsplit((parts.sc...
def __eq__(self, other): return self.name == other.name and \ debian_version_compare(self.version, other.version) == 0 def __lt__(self, other): return self.name < other.name or ( self.name == other.name and debian_version_compare(self.version, other.version) < 0)
def __cmp__(self, other): result = cmp(self.name, other.name) if result != 0: return result return debian_version_compare(self.version, other.version)
def __eq__(self, other): return self.name == other.name and \ debian_version_compare(self.version, other.version) == 0
analyzer_assigned_uuid = c_test_run.analyzer_assigned_uuid,
analyzer_assigned_uuid = str(c_test_run.analyzer_assigned_uuid),
def memory_model_to_db_model(self, c_bundle, s_bundle): """ Translate a memory model to database model """ from dashboard_app.models import ( Attachment, HardwareDevice, NamedAttribute, SoftwarePackage, Test, TestCase, TestResult, TestRun, ) # All variables prefixed with c_ refer to CLIENT SIDE models # All variables p...
QuantitativeSample Qualitative Sample class. Used to represent results for benchmarks.
Quantitative Sample class. Used to represent results for benchmarks.
def __init__(self, test_result, test_id=None, message=None, timestamp=None, duration=None): """ Initialize qualitative sample instance.
{'test_runs': [TestRuns]})
{'test_runs': [TestRun]})
def test_get_json_attr_types(self): self.assertEqual(DashboardBundle.get_json_attr_types(), {'test_runs': [TestRuns]})
class BundleStreamManagerAllowedForAnyoneTestCase(TestCase):
class BundleStreamManagerAllowedForUserTestCase(TestCase):
def test_allowed_for_anyone(self): with fixtures.created_bundle_streams(self.bundle_streams): pathnames = [bundle_stream.pathname for bundle_stream in BundleStream.objects.allowed_for_anyone().order_by('pathname')] self.assertEqual(pathnames, self.expected_pathnames)
bundle.deserialization_error.error_message)
bundle.deserialization_error.get().error_message)
def deserialize(self, content_sha1): """ Name ---- `deserialize` (`content_sha1`)
parse_config_file(options, config_name, pdf_name)
parse_config_file(options, config_name, os.path.basename(pdf_name))
def main(): options = Options() parser = optparse.OptionParser(usage='%prog input.pdf [output.html]') parser.add_option('--version', action='store_true', help='print version and exit') options.add_to_option_parser(parser) opts, args = parser.parse_args() if opts.version: print "pdf2html.py v%s by %s" % (__version__, _...
def convert_pdf_to_html(pdf_file, html_file):
def convert_pdf_to_html(pdf_file, html_file, debug=False):
def convert_pdf_to_html(pdf_file, html_file): tmpdir = tempfile.mkdtemp('pdf2html') try: xml_file = os.path.join(tmpdir, 'data') # pdf2html always adds .xml subprocess.check_call(['pdftohtml', '-xml', pdf_file, xml_file]) xml_file += '.xml' convert_pdfxml_to_html(xml_file, html_file) finally: shutil.rmtree(tmpdir)
convert_pdfxml_to_html(xml_file, html_file)
convert_pdfxml_to_html(xml_file, html_file, debug)
def convert_pdf_to_html(pdf_file, html_file): tmpdir = tempfile.mkdtemp('pdf2html') try: xml_file = os.path.join(tmpdir, 'data') # pdf2html always adds .xml subprocess.check_call(['pdftohtml', '-xml', pdf_file, xml_file]) xml_file += '.xml' convert_pdfxml_to_html(xml_file, html_file) finally: shutil.rmtree(tmpdir)
def convert_pdfxml_to_html(xml_file, html_file):
def convert_pdfxml_to_html(xml_file, html_file, debug=False):
def convert_pdfxml_to_html(xml_file, html_file): # The structure of the pdf2xml documents is this: # <pdf2xml> # <page number="1" position="absolute" top="0" left="0" # height="800" width="600" > # <fontspec id="0" size="12" family="Times" color="#000000" /> # ... # <text top="100" lef...
convert_pdfxml_to_html(pdf_name, output_name)
convert_pdfxml_to_html(pdf_name, output_name, opts.debug)
def main(): parser = optparse.OptionParser(usage='%prog input.pdf [output.html]') opts, args = parser.parse_args() if len(args) < 1: parser.error('please specify an input file name') if len(args) > 2: parser.error('too many arguments') pdf_name = args[0] if len(args) > 1: output_name = args[1] else: output_name = os.p...
convert_pdf_to_html(pdf_name, output_name)
convert_pdf_to_html(pdf_name, output_name, opts.debug)
def main(): parser = optparse.OptionParser(usage='%prog input.pdf [output.html]') opts, args = parser.parse_args() if len(args) < 1: parser.error('please specify an input file name') if len(args) > 2: parser.error('too many arguments') pdf_name = args[0] if len(args) > 1: output_name = args[1] else: output_name = os.p...
if False: print attr + ':'
if debug: print "Top 5 most frequent values of %r:" % attr
def n_most_frequent(attr, n): frequencies = count_frequencies(attr) frequencies = [(freq, value) for value, freq in frequencies.items()] frequencies.sort() if False: # debug print attr + ':' for f, v in frequencies[-5:]: print f, v return [value for (freq, value) in frequencies[-n:]]
print f, v
bar = '*' * (30 * f / frequencies[-1][0]) print ' %6d chunks have value %-6s %s' % (f, v, bar)
def n_most_frequent(attr, n): frequencies = count_frequencies(attr) frequencies = [(freq, value) for value, freq in frequencies.items()] frequencies.sort() if False: # debug print attr + ':' for f, v in frequencies[-5:]: print f, v return [value for (freq, value) in frequencies[-n:]]
print "DEBUG assertion failed" print ET.tostring(prev_chunk) print ET.tostring(chunk)
print "*** DEBUG assertion failed" print ' ', ET.tostring(prev_chunk).rstrip() print ' ', ET.tostring(chunk).rstrip()
def looks_like_a_heading(chunk): if len(chunk) != 1: return False bold = chunk while bold.tag != 'b': if len(bold) != 1: return False bold = bold[0] return (fonts[chunk.get('font')] != most_frequent_font and int(chunk.get('height')) >= int(most_frequent_height) and bold.text and any(c.isalpha() for c in bold.text))
odd_left, odd_indent = sorted(map(int, n_most_frequent('left', 2, odd_pages))) even_left, even_indent = sorted(map(int, n_most_frequent('left', 2, even_pages)))
odd_left, odd_indent = margin_and_indent(odd_pages) even_left, even_indent = margin_and_indent(even_pages)
def even_pages(page): "even pages" return int(page.get('number')) % 2 == 0
middleware.process_request(request)
Middleware.process_request(request)
def detected(request, *args, **kwargs): middleware.process_request(request) return view(request, *args, **kwargs)
aheadUTC = self.minutes > 0 if aheadUTC: sign = '+' mins = self.minutes * -1 else:
sign = '+' mins = self.minutes if mins < 0:
def tzname(self): aheadUTC = self.minutes > 0 if aheadUTC: sign = '+' mins = self.minutes * -1 else: sign = '-' mins = self.minutes wholehours = int(self.minutes / 60.) minutesleft = self.minutes % 60 return """%s%0.2d%0.2d""" % (sign, wholehours, minutesleft)
mins = self.minutes wholehours = int(self.minutes / 60.) minutesleft = self.minutes % 60
mins = mins * -1 wholehours = mins / 60 minutesleft = mins % 60
def tzname(self): aheadUTC = self.minutes > 0 if aheadUTC: sign = '+' mins = self.minutes * -1 else: sign = '-' mins = self.minutes wholehours = int(self.minutes / 60.) minutesleft = self.minutes % 60 return """%s%0.2d%0.2d""" % (sign, wholehours, minutesleft)
paths = ['/'.join(o.getPhysicalPath()) for o in self.Value()]
paths = ['/'.join(o.getPhysicalPath()) for o in self.Value() if o is not None]
def getCriteriaItems(self): result = [] depth = (not self.Recurse() and 1) or -1 paths = ['/'.join(o.getPhysicalPath()) for o in self.Value()]
if (value is None or value == ""): if not field.getRaw(self): if 'mimetype' in kwargs and kwargs['mimetype']: field.setContentType(self, kwargs['mimetype']) if 'filename' in kwargs and kwargs['filename']: field.setFilename(self, kwargs['filename']) else: return
if not value and not field.getRaw(self): if 'mimetype' in kwargs and kwargs['mimetype']: field.setContentType(self, kwargs['mimetype']) if 'filename' in kwargs and kwargs['filename']: field.setFilename(self, kwargs['filename'])
def setText(self, value, **kwargs): """Body text mutator * hook into mxTidy an replace the value with the tidied value """ field = self.getField('text') # XXX this is ugly # When an object is initialized the first time we have to # set the filename and mimetype. # In the case the value is empty/None we must not set th...
print "ANIMATIONS_%s = {" % name.upper()
print("ANIMATIONS_%s = {" % name.upper())
print "def get_%s_icon_name_from_enum(enum):" % name
print " %s_%s:'%s'," % match print " }\n" print "def get_%s_animation_name_from_enum(enum):" % name print " if ANIMATIONS_%s.has_key(enum):" % name.upper() print " return ANIMATIONS_%s[enum]" % name.upper() print " else:" print " return None\n"
print(" %s_%s:'%s'," % match) print(" }\n") print("def get_%s_animation_name_from_enum(enum):" % name) print(" if ANIMATIONS_%s.has_key(enum):" % name.upper()) print(" return ANIMATIONS_%s[enum]" % name.upper()) print(" else:") print(" return None\n")
print "def get_%s_icon_name_from_enum(enum):" % name
print "PAST_%s = {" % name.upper()
print("PAST_%s = {" % name.upper())
print "def get_%s_animation_name_from_enum(enum):" % name
print " %s_%s:%s %% %s," % match
print(" %s_%s:%s %% %s," % match)
print "def get_%s_animation_name_from_enum(enum):" % name
print " %s_%s:%s," % match print " }\n" print "def get_%s_localised_past_from_enum(enum):" % name print " if PAST_%s.has_key(enum):" % name.upper() print " return PAST_%s[enum]" % name.upper() print " else:" print " return None\n"
print(" %s_%s:%s," % match) print(" }\n") print("def get_%s_localised_past_from_enum(enum):" % name) print(" if PAST_%s.has_key(enum):" % name.upper()) print(" return PAST_%s[enum]" % name.upper()) print(" else:") print(" return None\n")
print "def get_%s_animation_name_from_enum(enum):" % name
print "PRESENT_%s = {" % name.upper()
print("PRESENT_%s = {" % name.upper())
print "def get_%s_localised_past_from_enum(enum):" % name
print " %s_%s:%s %% %s," % match
print(" %s_%s:%s %% %s," % match)
print "def get_%s_localised_past_from_enum(enum):" % name
print " %s_%s:%s," % match print " }\n" print "def get_%s_localised_present_from_enum(enum):" % name print " if PRESENT_%s.has_key(enum):" % name.upper() print " return PRESENT_%s[enum]" % name.upper() print " else:" print " return None\n"
print(" %s_%s:%s," % match) print(" }\n") print("def get_%s_localised_present_from_enum(enum):" % name) print(" if PRESENT_%s.has_key(enum):" % name.upper()) print(" return PRESENT_%s[enum]" % name.upper()) print(" else:") print(" return None\n")
print "def get_%s_localised_past_from_enum(enum):" % name
print "DESCS_%s = {" % name.upper()
print("DESCS_%s = {" % name.upper())
print "def get_%s_localised_present_from_enum(enum):" % name
print " %s_%s:%s %% %s," % match
print(" %s_%s:%s %% %s," % match)
print "def get_%s_localised_present_from_enum(enum):" % name
print " %s_%s:%s," % match print " }\n" print "def get_%s_description_from_enum(enum):" % name print " if DESCS_%s.has_key(enum):" % name.upper() print " return DESCS_%s[enum]" % name.upper() print " else:" print " return None\n"
print(" %s_%s:%s," % match) print(" }\n") print("def get_%s_description_from_enum(enum):" % name) print(" if DESCS_%s.has_key(enum):" % name.upper()) print(" return DESCS_%s[enum]" % name.upper()) print(" else:") print(" return None\n")
print "def get_%s_localised_present_from_enum(enum):" % name
print "STRINGS_%s = {" % name.upper()
print("STRINGS_%s = {" % name.upper())
print "def get_%s_description_from_enum(enum):" % name
print " %s_%s:%s," % match print " }\n" print "def get_%s_string_from_enum(enum):" % name print " if STRINGS_%s.has_key(enum):" % name.upper() print " return STRINGS_%s[enum]" % name.upper() print " else:" print " return None\n"
print(" %s_%s:%s," % match) print(" }\n") print("def get_%s_string_from_enum(enum):" % name) print(" if STRINGS_%s.has_key(enum):" % name.upper()) print(" return STRINGS_%s[enum]" % name.upper()) print(" else:") print(" return None\n")
print "def get_%s_description_from_enum(enum):" % name
self.assertAlmostEqual(float('inf'), float('inf')) self.assertRaises(self.failureException, self.assertNotAlmostEqual, float('inf'), float('inf'))
try: self.assertAlmostEqual(float('inf'), float('inf')) self.assertRaises(self.failureException, self.assertNotAlmostEqual, float('inf'), float('inf')) except ValueError: x = object() self.assertAlmostEqual(x, x) self.assertRaises(self.failureException, self.assertNotAlmostEqual, x, x)
def test_AlmostEqual(self): self.assertAlmostEqual(1.00000001, 1.0) self.assertNotAlmostEqual(1.0000001, 1.0) self.assertRaises(self.failureException, self.assertAlmostEqual, 1.0000001, 1.0) self.assertRaises(self.failureException, self.assertNotAlmostEqual, 1.00000001, 1.0)
self.assertFalse(unittest2.TestCase.longMessage)
self.assertTrue(unittest2.TestCase.longMessage)
def testDefault(self): self.assertFalse(unittest2.TestCase.longMessage)
self.assertEqual(out_stream.getvalue(), 'foo\n') self.assertEqual(err_stream.getvalue(), 'bar\n')
self.assertEqual(out_stream.getvalue(), 'foo%s' % os.linesep) self.assertEqual(err_stream.getvalue(), 'bar%s' % os.linesep)
def testBufferOutputStartTestAddSuccess(self): real_out = self._real_out real_err = self._real_err result = unittest2.TestResult() self.assertFalse(result.buffer) result.buffer = True self.assertIs(real_out, sys.stdout) self.assertIs(real_err, sys.stderr) result.startTest(self) self.assertIsNot(real_out, sys.stdou...
""")
""").replace('\n', os.linesep)
def testBufferOutputAddErrorOrFailure(self): for message_attr, add_attr, include_error in [ ('errors', 'addError', True), ('failures', 'addFailure', False), ('errors', 'addError', True), ('failures', 'addFailure', False) ]: result = self.getStartedResult() buffered_out = sys.stdout buffered_err = sys.stderr result._ori...
""") expectedFullMessage = 'None\n%s%s' % (expectedOutMessage, expectedErrMessage)
""").replace('\n', os.linesep) expectedFullMessage = 'None%s%s%s' % (os.linesep, expectedOutMessage, expectedErrMessage)
def testBufferOutputAddErrorOrFailure(self): for message_attr, add_attr, include_error in [ ('errors', 'addError', True), ('failures', 'addFailure', False), ('errors', 'addError', True), ('failures', 'addFailure', False) ]: result = self.getStartedResult() buffered_out = sys.stdout buffered_err = sys.stderr result._ori...
if self.catchbreak != False:
if self.catchbreak != False and installHandler is not None:
def usageExit(self, msg=None): if msg: print msg usage = {'progName': self.progName, 'catchbreak': '', 'failfast': ''} if self.failfast != False: usage['failfast'] = FAILFAST if self.catchbreak != False: usage['catchbreak'] = CATCHBREAK print self.USAGE % usage sys.exit(2)
if self.catchbreak is None:
if self.catchbreak is None and installHandler is not None:
def parseArgs(self, argv): if len(argv) > 1 and argv[1].lower() == 'discover': self._do_discovery(argv[2:]) return
loader._top_level_dir = '/foo' suite = list(loader._find_tests('/foo', 'test*.py'))
top_level = '/foo' loader._top_level_dir = top_level suite = list(loader._find_tests(top_level, 'test*.py'))
def isfile(path): # another_dir is not a package and so shouldn't be recursed into return not path.endswith('dir') and not 'another_dir' in path
msg = (r"^'foo' module incorrectly imported from %r\. Expected %r\. " "Is this module globally installed\?$") % (mod_dir, expected_dir)
msg = re.escape(r"'foo' module incorrectly imported from %r. Expected %r. " "Is this module globally installed?" % (mod_dir, expected_dir))
def isdir(_): return True
ImportError, msg, loader.discover,
ImportError, '^%s$' % msg, loader.discover,
def isdir(_): return True
top_level = '/foo'
top_level = os.path.abspath('/foo')
def isfile(path): # another_dir is not a package and so shouldn't be recursed into return not path.endswith('dir') and not 'another_dir' in path
def print_tb(tb, limit=None, file=None): """Print up to 'limit' stack trace entries from the traceback 'tb'.
def print_tb(tb, limit=None, file=None): """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() method. """ if fi...
If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() method. """ if file is None: file = sys.stderr if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit ...
class TracebackCases(unittest2.TestCase):
def print_tb(tb, limit=None, file=None): """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() method. """ if fi...
def format_tb(tb, limit = None): """A shorthand for 'format_list(extract_stack(f, limit)).""" return format_list(extract_tb(tb, limit))
def get_exception_format(self, func, exc): try: func() except exc, value: return traceback.format_exception_only(exc, value) else: raise ValueError, "call did not raise exception"
def format_tb(tb, limit = None): """A shorthand for 'format_list(extract_stack(f, limit)).""" return format_list(extract_tb(tb, limit))
def extract_tb(tb, limit = None): """Return list of up to limit pre-processed entries from traceback.
def syntax_error_with_caret(self): compile("def fact(x):\n\treturn x!\n", "?", "exec")
def extract_tb(tb, limit = None): """Return list of up to limit pre-processed entries from traceback. This is useful for alternate formatting of stack traces. If 'limit' is omitted or None, all entries are extracted. A pre-processed stack trace entry is a quadruple (filename, line number, function name, text) repres...
This is useful for alternate formatting of stack traces. If 'limit' is omitted or None, all entries are extracted. A pre-processed stack trace entry is a quadruple (filename, line number, function name, text) representing the information that is usually printed for a stack trace. The text is a string with leading an...
def syntax_error_with_caret_2(self): compile("1 +\n", "?", "exec") def syntax_error_without_caret(self): import test.badsyntax_nocaret def syntax_error_bad_indentation(self): compile("def spam():\n print 1\n print 2", "?", "exec") def test_caret(self): err = self.get_exception_format(self.syntax_error_with_caret, ...
def extract_tb(tb, limit = None): """Return list of up to limit pre-processed entries from traceback. This is useful for alternate formatting of stack traces. If 'limit' is omitted or None, all entries are extracted. A pre-processed stack trace entry is a quadruple (filename, line number, function name, text) repres...
def print_exception(etype, value, tb, limit=None, file=None): """Print exception up to 'limit' stack trace entries from 'tb' to 'file'.
def print_exception(etype, value, tb, limit=None, file=None): """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception type and value a...
This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception type and value after the stack trace; (3) if type is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred...
if __name__ == "__main__": unittest2.main()
def print_exception(etype, value, tb, limit=None, file=None): """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if traceback is not None, it prints a header "Traceback (most recent call last):"; (2) it prints the exception type and value a...
return getUtility(IRegistry).forInterface(self.schema)
return getUtility(IRegistry).forInterface(self.schema, prefix=self.prefix)
def getContent(self): return getUtility(IRegistry).forInterface(self.schema)
print "Could not open socket: " + message
def open_socket(self): while 1 : try: self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind((self.host,self.port)) self.server.listen(5) break except socket.error, (value,message): if self.server: self.server.close() print "Could not open socket: " + message time.sleep(1)
generate_html()
c = HtmlGenerator() c.start() self.threads.append(c)
def run(self): generate_html()
g_client_table[self.address[0]] = message
g_client_message_board[self.address[0]] = message
def run(self): running = 1 while running: message = self.client.recv(self.size)
del g_client_table[self.address[0]]
del g_client_message_board[self.address[0]]
def run(self): running = 1 while running: message = self.client.recv(self.size)
generate_html()
def run(self): running = 1 while running: message = self.client.recv(self.size)
message = '<p><strong>' + self.address[0] + '</strong>: \"' + message + '\"</p>\n'
message = '<p><strong>' + self.address[0] + '</strong>: ' + message + '</p>\n'
def run(self): running = 1 while running: message = self.client.recv(self.size) if message: f = open(self.address[0], 'w') message = '<p><strong>' + self.address[0] + '</strong>: \"' + message + '\"</p>\n' f.write(message) f.close() else: self.client.close() running = 0
def get_output(cmd):
team_name_map = { re.compile('WE20\d\d'): 'WrightEagle', re.compile('helios'): 'Helios', re.compile('nq{player,coach}'): 'LsuAmoyNQ', re.compile('oxsy'): 'Oxsy', re.compile('BS2k'): 'BrainStormer' } def get_output(cmd) :
def get_output(cmd): pipe = os.popen(cmd) output = pipe.read() pipe.close() return output
def testing() : return get_output("ps -o comm= -e | sort | uniq -c | sort -nr | head -2 | awk '{print $2}'").strip().split('\n')
def find_testing_teams() : teams = [] process_list = get_output("ps -o comm= -e | sort | uniq").strip().split('\n') for process in process_list : for pattern in team_name_map.keys() : if pattern.match(process) : teams.append(team_name_map[pattern]) break if len(teams) >= 2 : break return teams
def testing() : return get_output("ps -o comm= -e | sort | uniq -c | sort -nr | head -2 | awk '{print $2}'").strip().split('\n')
team = testing() return ' return '
message += '%d,%s' % (count, output[0]) teams = find_testing_teams() if len(teams) > 0 : message += ' (' for team in teams : message += team + ',' message = message.strip(',') + ')' else : message += '0' return message
def rcssserver() : output = get_output('ps -o user= -C rcssserver').split('\n'); count = len(output) - 1; if count > 0: team = testing() return ' #rcssserver: %d,%s (%s,%s)' % (count, output[0], team[0], team[1]) return ' #rcssserver: 0'
for client in sorted(g_message_board.keys()) : html_content += '<p><strong>' + client + '</strong>: ' + g_message_board[client] + '</p>\n'
for ip in sorted(g_message_board.keys()) : html_content += '<p><strong>' + ip + '</strong>: ' + g_message_board[ip] + '</p>\n'
def generate_html(self) : html_content = g_html_head for client in sorted(g_message_board.keys()) : html_content += '<p><strong>' + client + '</strong>: ' + g_message_board[client] + '</p>\n' html_content += g_html_tail
self.size = 1024
def __init__(self): self.host = '' self.port = 50000 self.size = 1024 self.server = None self.threads = []
self.threads = []
def __init__(self): self.host = '' self.port = 50000 self.size = 1024 self.server = None self.threads = []
c = HtmlGenerator() c.start() self.threads.append(c)
HtmlGenerator().start()
def run(self): c = HtmlGenerator() c.start() self.threads.append(c)
running = 1 while running: c = Client(self.server.accept()) c.start() self.threads.append(c) self.server.close() for c in self.threads: c.join()
while 1: Client(self.server.accept()).start()
def run(self): c = HtmlGenerator() c.start() self.threads.append(c)
self.address = address
self.ip = address[0]
def __init__(self,(client,address)): threading.Thread.__init__(self) self.client = client self.address = address self.size = 1024