Best Python code snippet using robotframework-ioslibrary_python
__init__.py
Source:__init__.py
...26except ImportError:27 import https.cookies as cookie28HOST = 'api.duoshuo.com'29URI_SCHEMA = 'http'30INTERFACES = _parse_json(open(os.path.join(os.path.dirname(__file__), 'interfaces.json'), 'r').read())31try:32 import settings33except ImportError:34 DUOSHUO_SHORT_NAME = None35 DUOSHUO_SECRET = None36else:37 DUOSHUO_SHORT_NAME = getattr(settings, "DUOSHUO_SHORT_NAME", None)38 DUOSHUO_SECRET = getattr(settings, "DUOSHUO_SECRET", None)39class APIError(Exception):40 def __init__(self, code, message):41 self.code = code42 self.message = message43 def __str__(self):44 return '%s: %s' % (self.code, self.message)45class Resource(object):46 def __init__(self, api, interface=INTERFACES, node=None, tree=()):47 self.api = api48 self.node = node49 self.interface = interface50 if node:51 tree = tree + (node,)52 self.tree = tree53 def __getattr__(self, attr):54 if attr in getattr(self, '__dict__'):55 return getattr(self, attr)56 interface = self.interface57 if attr not in interface:58 interface[attr] = {}59 #raise APIError('03', 'Interface is not defined')60 return Resource(self.api, interface[attr], attr, self.tree)61 def __call__(self, **kwargs):62 return self._request(**kwargs)63 def _request(self, **kwargs):64 resource = self.interface65 for k in resource.get('required', []):66 if k not in [x.split(':')[0] for x in kwargs.keys()]:67 raise ValueError('Missing required argument: %s' % k)68 method = kwargs.pop('method', resource.get('method'))69 api = self.api70 format = kwargs.pop('format', api.format)71 path = '%s://%s/%s.%s' % (URI_SCHEMA, HOST, '/'.join(self.tree), format)72 if 'secret' not in kwargs and api.secret:73 kwargs['secret'] = api.secret74 if 'short_name' not in kwargs and api.short_name:75 kwargs['short_name'] = api.short_name76 # We need to ensure this is a list so that77 # multiple values for a key work78 params = []79 for k, v in kwargs.iteritems():80 if isinstance(v, (list, tuple)):81 for val in v:82 params.append((k, val))83 else:84 params.append((k, v))85 if method == 'GET':86 path = '%s?%s' % (path, urllib.urlencode(params))87 response = urllib2.urlopen(path).read()88 else:89 data = urllib.urlencode(params)90 response = urllib2.urlopen(path, data).read()91 try:92 return _parse_json(response)93 except:94 return _parse_json('{"code": "500"}')95class DuoshuoAPI(Resource):96 def __init__(self, short_name=DUOSHUO_SHORT_NAME, secret=DUOSHUO_SECRET, format='json', **kwargs):97 self.short_name = short_name98 self.secret = secret99 self.format = format100 self.uri_schema = URI_SCHEMA101 self.host = HOST102 if not secret or not short_name:103 warnings.warn('You should pass short_name and secret.')104 #self.version = version105 super(DuoshuoAPI, self).__init__(self)106 def _request(self, **kwargs):107 raise SyntaxError('You cannot call the API without a resource.')108 def _get_key(self):109 return self.secret110 key = property(_get_key)111 def get_token(self, code=None):112 if not code:113 raise APIError('01', 'Invalid request: code')114 #elif not redirect_uri:115 # raise APIError('01', 'Invalid request: redirect_uri')116 else:117 #params = {'client_id': self.client_id, 'secret': self.secret, 'redirect_uri': redirect_uri, 'code': code}118 params = {'code': code}119 data = urllib.urlencode(params)120 url = '%s://%s/oauth2/access_token' % (URI_SCHEMA, HOST)121 print url122 request = urllib2.Request(url)123 response = urllib2.build_opener(urllib2.HTTPCookieProcessor()).open(request, data)124 return _parse_json(response.read())125 def setSecret(self, key):126 self.secret = key127 def setFormat(self, key):...
test_asset_loader.py
Source:test_asset_loader.py
...16def test_valid_json_path() -> None:17 actual = _validate_asset_path("./test/assets/valid-asset.json")18 assert isinstance(actual, str)19def test_invalid_json_file() -> None:20 actual = _parse_json("./test/assets/invalid-json.json")21 assert isinstance(actual, Exception)22def test_nonexisting_json_file() -> None:23 actual = _parse_json("/does/not/exist")24 assert isinstance(actual, Exception)25def test_valid_json_file() -> None:26 actual = _parse_json("./test/assets/valid-asset.json")27 assert not isinstance(actual, Exception)28def test_invalid_asset_1() -> None:29 parsed_json = _parse_json("./test/assets/invalid-asset-1.json")30 assert not isinstance(parsed_json, Exception)31 actual = _validate_asset(parsed_json)32 assert isinstance(actual, Exception)33def test_invalid_asset_2() -> None:34 parsed_json = _parse_json("./test/assets/invalid-asset-2.json")35 assert not isinstance(parsed_json, Exception)36 actual = _validate_asset(parsed_json)37 assert isinstance(actual, Exception)38def test_invalid_asset_3() -> None:39 parsed_json = _parse_json("./test/assets/invalid-asset-3.json")40 assert not isinstance(parsed_json, Exception)41 actual = _validate_asset(parsed_json)42 assert isinstance(actual, Exception)43def test_invalid_asset_4() -> None:44 parsed_json = _parse_json("./test/assets/invalid-asset-4.json")45 assert not isinstance(parsed_json, Exception)46 actual = _validate_asset(parsed_json)47 assert isinstance(actual, Exception)48def test_invalid_asset_5() -> None:49 parsed_json = _parse_json("./test/assets/invalid-asset-5.json")50 assert not isinstance(parsed_json, Exception)51 actual = _validate_asset(parsed_json)52 assert isinstance(actual, Exception)53def test_valid_asset() -> None:54 parsed_json = _parse_json("./test/assets/valid-asset.json")55 assert not isinstance(parsed_json, Exception)56 actual = _validate_asset(parsed_json)...
json.py
Source:json.py
...41 return result42def parse_from_json(raw):43 """ a utility for spark function from_json"""44 assert (isinstance(raw,dict) or isinstance(raw,list))45 return _parse_json(raw)46def _parse_json(o):47 if isinstance(o, dict):48 l = []49 for k in o:50 if isinstance(o[k],dict):51 l.append( k +":" + _parse_json(o[k]) )52 elif isinstance(o[k],list):53 l.append(k + ':'+ _parse_json(o[k]))54 else:55 l.append( k +":"+ "string")56 return "strcut<"+ ",".join(l) +">"57 if isinstance(o,list):58 try:59 first = o[0]60 return "array<" + _parse_json(_parse_json(first)) + ">"61 except IndexError:62 return "array<string>"63 else:...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!