How to use safe_decode method in Nose2

Best Python code snippet using nose2

vimeo.py

Source:vimeo.py Github

copy

Full Screen

...65 for (key, value) in obj.items()]))66 if isinstance(obj, (list, tuple)):67 return [feedparser_dict(member) for member in obj]68 return obj69def safe_decode(str_or_unicode):70 if isinstance(str_or_unicode, unicode):71 return str_or_unicode72 else:73 return str_or_unicode.decode('utf8')74def _json_to_feedparser(json):75 upload_date = datetime.datetime.strptime(76 json['upload_date'],77 '%Y-%m-%d %H:%M:%S')78 tags = [{'label': u'Tags',79 'scheme': None,80 'term': safe_decode(json['tags'])}]81 tags.extend({'label': None,82 'scheme': u'http://vimeo/tag:%s' % tag,83 'term': tag}84 for tag in safe_decode(json['tags']).split(', '))85 return {86 'author': safe_decode(json['user_name']),87 'enclosures': [88 {'href': u'http://vimeo.com/moogaloop.swf?clip_id=%s' % json['id'],89 'type': u'application/x-shockwave-flash'},90 {'thumbnail': {'width': u'200', 'height': u'150',91 'url': safe_decode(json['thumbnail_medium']),92 }}],93 'guidislink': False,94 'id': safe_decode(upload_date.strftime(95 'tag:vimeo,%%Y-%%m-%%d:clip%s' % json['id'].encode('utf8'))),96 'link': safe_decode(json['url']),97 'links': [{'href': safe_decode(json['url']),98 'rel': 'alternate',99 'type': 'text/html'}],100 'media:thumbnail': u'',101 'media_credit': safe_decode(json['user_name']),102 'media_player': u'',103 'summary': (u'<p><a href="%(url)s" title="%(title)s">'104 u'<img src="%(thumbnail_medium)s" alt="%(title)s" /></a>'105 u'</p><p>%(description)s</p>' % json),106 'summary_detail': {107 'base': u'%s/videos/rss' % safe_decode(json['user_url']),108 'language': None,109 'type': 'text/html',110 'value': (u'<p><a href="%(url)s" title="%(title)s">'111 u'<img src="%(thumbnail_medium)s" alt="%(title)s" /></a>'112 u'</p><p>%(description)s</p>' % json),113 },114 'tags': tags,115 'title': safe_decode(json['title']),116 'title_detail': {117 'base': u'%s/videos/rss' % safe_decode(json['user_url']),118 'language': None,119 'type': 'text/plain',120 'value': safe_decode(json['title'])},121 'updated': safe_decode(122 upload_date.strftime('%a, %d %b %Y %H:%M:%S %z')),...

Full Screen

Full Screen

test_encodeutils.py

Source:test_encodeutils.py Github

copy

Full Screen

...16from tests.unit import test17def b(s):18 return s.encode("latin-1")19class EncodeUtilsTestCase(test.TestCase):20 def test_safe_decode(self):21 safe_decode = encodeutils.safe_decode22 self.assertRaises(TypeError, safe_decode, True)23 self.assertEqual("ni\xf1o",24 safe_decode(b("ni\xc3\xb1o"), incoming="utf-8"))25 self.assertEqual("strange",26 safe_decode(b("\x80strange"), errors="ignore"))27 self.assertEqual("\xc0",28 safe_decode(b("\xc0"), incoming="iso-8859-1"))29 # Forcing incoming to ascii so it falls back to utf-830 self.assertEqual("ni\xf1o",31 safe_decode(b("ni\xc3\xb1o"), incoming="ascii"))32 self.assertEqual("foo", safe_decode(b"foo"))33 def test_safe_encode_none_instead_of_text(self):34 self.assertRaises(TypeError, encodeutils.safe_encode, None)35 def test_safe_encode_bool_instead_of_text(self):36 self.assertRaises(TypeError, encodeutils.safe_encode, True)37 def test_safe_encode_int_instead_of_text(self):38 self.assertRaises(TypeError, encodeutils.safe_encode, 1)39 def test_safe_encode_list_instead_of_text(self):40 self.assertRaises(TypeError, encodeutils.safe_encode, [])41 def test_safe_encode_dict_instead_of_text(self):42 self.assertRaises(TypeError, encodeutils.safe_encode, {})43 def test_safe_encode_tuple_instead_of_text(self):44 self.assertRaises(TypeError, encodeutils.safe_encode, ("foo", "bar",))45 def test_safe_encode_force_incoming_utf8_to_ascii(self):46 # Forcing incoming to ascii so it falls back to utf-8...

Full Screen

Full Screen

os_brick_executor.py

Source:os_brick_executor.py Github

copy

Full Screen

...28 execute = priv_rootwrap.execute29 self.set_execute(execute)30 self.set_root_helper(root_helper)31 @staticmethod32 def safe_decode(string):33 return string and encodeutils.safe_decode(string, errors='ignore')34 @classmethod35 def make_putils_error_safe(cls, exc):36 """Converts ProcessExecutionError string attributes to unicode."""37 for field in ('stderr', 'stdout', 'cmd', 'description'):38 value = getattr(exc, field, None)39 if value:40 setattr(exc, field, cls.safe_decode(value))41 def _execute(self, *args, **kwargs):42 try:43 result = self.__execute(*args, **kwargs)44 if result:45 result = (self.safe_decode(result[0]),46 self.safe_decode(result[1]))47 return result48 except putils.ProcessExecutionError as e:49 self.make_putils_error_safe(e)50 raise51 def set_execute(self, execute):52 self.__execute = execute53 def set_root_helper(self, helper):54 self._root_helper = helper55class Thread(threading.Thread):56 """Thread class that inherits the parent's context.57 This is useful when you are spawning a thread and want LOG entries to58 display the right context information, such as the request.59 """60 def __init__(self, *args, **kwargs):...

Full Screen

Full Screen

make_register_diagnostics.py

Source:make_register_diagnostics.py Github

copy

Full Screen

2import re3import glob4import hashlib5from io import StringIO6def safe_decode(x): 7 return x.decode('utf8') if type(x) is bytes else x8# File header9header="""10subroutine register_diagnostics11"""12footer="""13end subroutine register_diagnostics14"""15outfile = 'preprocessor/register_diagnostics.F90'16# get sha1 digest of existing generated file. Can't use 'rw' here17# because it updates the modtime of the file, which we're trying to18# avoid doing.19orig=hashlib.sha1()20try:21 f=open(outfile, 'r')22 orig.update(f.read().encode("utf8"))23except IOError:24 pass25else:26 f.close()27# Now read module files to generate potential new data28output=StringIO()29output.write(safe_decode(header))30# List of fortran source files.31fortran_files=glob.glob("*/*.F")+glob.glob("*/*.F90")32module_re=re.compile(r"^\s*module\s+(\w+)\s*$",re.IGNORECASE|re.MULTILINE)33module_list=[]34for filename in fortran_files:35 fortran=open(filename,"rb").read().decode("utf-8")36 modules=module_re.findall(fortran)37 for module in modules:38 if re.search(r"^\s*subroutine\s+"+module+"_register_diagnostic\s*$",\39 fortran,\40 re.IGNORECASE|re.MULTILINE):41 module_list.append(module)42for module in module_list:43 output.write(safe_decode(" use "+module+", only: "+module+"_register_diagnostic\n"))44# Ensure that the subroutine is legal in the trivial case.45output.write(safe_decode("""46 continue47 """))48for module in module_list:49 output.write(safe_decode(" call "+module+"_register_diagnostic\n"))50output.write(safe_decode(footer))51new=hashlib.sha1()52new.update(output.getvalue().encode("utf8"))53# Only write file if sha1sums differ54if new.digest() != orig.digest():55 try:56 f=open(outfile, 'w')57 f.write(output.getvalue())58 except IOError:59 # Fixme, this should fail better60 pass61 else:62 f.close()...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Nose2 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful