How to use accept method in taiko

Best JavaScript code snippet using taiko

negotiator.py

Source:negotiator.py Github

copy

Full Screen

...396 log.info("Accept-Language: " + str(accept_language))397 log.info("Accept-Packaging: " + str(accept_packaging))398 # get us back a dictionary keyed by q value which tells us the order of preference that the client has399 # requested400 accept_analysed = self._analyse_accept(accept)401 lang_analysed = self._analyse_language(accept_language)402 encoding_analysed = self._analyse_encoding(accept_encoding)403 charset_analysed = self._analyse_charset(accept_charset)404 packaging_analysed = self._analyse_packaging(accept_packaging)405 406 log.info("Accept Analysed: " + str(accept_analysed))407 log.info("Language Analysed: " + str(lang_analysed))408 log.info("Packaging Analysed: " + str(packaging_analysed))409 410 # now combine these results into one list of preferred accepts411 preferences = self._list_acceptable(self.weights, accept_analysed, lang_analysed, encoding_analysed, charset_analysed, packaging_analysed)412 413 log.info("Preference List: " + str(preferences))414 415 # go through the analysed formats and cross reference them with the acceptable formats416 accept_parameters = self._get_acceptable(preferences, self.acceptable)417 418 log.info("Acceptable: " + str(accept_parameters))419 # return the acceptable type. If this is None (which get_acceptable can return), then the caller420 # will know that we failed to negotiate a type and should 415 the client421 return accept_parameters422 def _list_acceptable(self, weights, content_types=None, languages=None, encodings=None, charsets=None, packaging=None):423 424 log.debug("Relative weights: " + str(weights))425 426 if content_types is None:427 content_types = {0.0 : [None]}428 if languages is None:429 languages = {0.0 : [None]}430 if encodings is None:431 encodings = {0.0 : [None]}432 if charsets is None:433 charsets = {0.0 : [None]}434 if packaging is None:435 packaging = {0.0 : [None]}436 437 log.debug("Matrix of options:")438 log.debug("Content Types: " + str(content_types))439 log.debug("Languages: " + str(languages))440 log.debug("Encodings: " + str(encodings))441 log.debug("Charsets: " + str(charsets))442 log.debug("Packaging: " + str(packaging))443 444 unsorted = []445 446 # create an accept_parameter for each first precedence field447 # FIXME: this is hideous, but recursive programming is making my head448 # hurt so screw it.449 for q1, vals1 in content_types.items():450 for v1 in vals1:451 for q2, vals2 in languages.items():452 for v2 in vals2:453 for q3, vals3 in encodings.items():454 for v3 in vals3:455 for q4, vals4 in charsets.items():456 for v4 in vals4:457 for q5, vals5 in packaging.items():458 wq = ((weights['content_type'] * q1) + (weights['language'] * q2) +459 (weights['encoding'] * q3) + (weights['charset'] * q4) + 460 (weights['packaging'] * q5))461 for v5 in vals5:462 ap = AcceptParameters(v1, v2, v3, v4, v5)463 unsorted.append((ap, wq))464 465 sorted = self._sort_by_q(unsorted, 0.0)466 return sorted467 def _analyse_packaging(self, accept):468 if accept is None:469 return None470 471 # if the header is not none, then it should be a straightforward uri,472 # with no q value, so our return is simple:473 return {1.0 : [accept]}474 def _analyse_encoding(self, accept):475 return None476 477 def _analyse_charset(self, accept):478 return None479 def _analyse_language(self, accept):480 if accept is None:481 return None482 parts = self._split_accept_header(accept)483 highest_q = 0.0484 counter = 0485 unsorted = []486 for part in parts:487 counter += 1488 lang, sublang, q = self._interpret_accept_language_field(part, -1 * counter)489 if q > highest_q:490 highest_q = q491 unsorted.append((Language(language=lang, variant=sublang), q))492 sorted = self._sort_by_q(unsorted, highest_q)493 # now we have a dictionary keyed by q value which we can return494 return sorted495 def _analyse_accept(self, accept):496 """497 Analyse the Accept header string from the HTTP headers and return a structured dictionary with each498 content types grouped by their common q values, thus:499 dict = {500 1.0 : [<ContentType>, <ContentType>],501 0.8 : [<ContentType],502 0.5 : [<ContentType>, <ContentType>]503 }504 This method will guarantee that every content type has some q value associated with it, even if this was not505 supplied in the original Accept header; it will be inferred based on the rules of content negotiation506 """507 if accept is None:508 return None509 ...

Full Screen

Full Screen

as_string.py

Source:as_string.py Github

copy

Full Screen

...63class AsStringVisitor(object):64 """Visitor to render an Astroid node as a valid python code string"""65 def __call__(self, node):66 """Makes this visitor behave as a simple function"""67 return node.accept(self)68 def _stmt_list(self, stmts):69 """return a list of nodes to string"""70 stmts = '\n'.join([nstr for nstr in [n.accept(self) for n in stmts] if nstr])71 return INDENT + stmts.replace('\n', '\n'+INDENT)72 ## visit_<node> methods ###########################################73 def visit_arguments(self, node):74 """return an astroid.Function node as string"""75 return node.format_args()76 def visit_assattr(self, node):77 """return an astroid.AssAttr node as string"""78 return self.visit_getattr(node)79 def visit_assert(self, node):80 """return an astroid.Assert node as string"""81 if node.fail:82 return 'assert %s, %s' % (node.test.accept(self),83 node.fail.accept(self))84 return 'assert %s' % node.test.accept(self)85 def visit_assname(self, node):86 """return an astroid.AssName node as string"""87 return node.name88 def visit_assign(self, node):89 """return an astroid.Assign node as string"""90 lhs = ' = '.join([n.accept(self) for n in node.targets])91 return '%s = %s' % (lhs, node.value.accept(self))92 def visit_augassign(self, node):93 """return an astroid.AugAssign node as string"""94 return '%s %s %s' % (node.target.accept(self), node.op, node.value.accept(self))95 def visit_backquote(self, node):96 """return an astroid.Backquote node as string"""97 return '`%s`' % node.value.accept(self)98 def visit_binop(self, node):99 """return an astroid.BinOp node as string"""100 return '(%s) %s (%s)' % (node.left.accept(self), node.op, node.right.accept(self))101 def visit_boolop(self, node):102 """return an astroid.BoolOp node as string"""103 return (' %s ' % node.op).join(['(%s)' % n.accept(self)104 for n in node.values])105 def visit_break(self, node):106 """return an astroid.Break node as string"""107 return 'break'108 def visit_callfunc(self, node):109 """return an astroid.CallFunc node as string"""110 expr_str = node.func.accept(self)111 args = [arg.accept(self) for arg in node.args]112 if node.starargs:113 args.append('*' + node.starargs.accept(self))114 if node.kwargs:115 args.append('**' + node.kwargs.accept(self))116 return '%s(%s)' % (expr_str, ', '.join(args))117 def visit_class(self, node):118 """return an astroid.Class node as string"""119 decorate = node.decorators and node.decorators.accept(self) or ''120 bases = ', '.join([n.accept(self) for n in node.bases])121 if sys.version_info[0] == 2:122 bases = bases and '(%s)' % bases or ''123 else:124 metaclass = node.metaclass()125 if metaclass and not node.has_metaclass_hack():126 if bases:127 bases = '(%s, metaclass=%s)' % (bases, metaclass.name)128 else:129 bases = '(metaclass=%s)' % metaclass.name130 else:131 bases = bases and '(%s)' % bases or ''132 docs = node.doc and '\n%s"""%s"""' % (INDENT, node.doc) or ''133 return '\n\n%sclass %s%s:%s\n%s\n' % (decorate, node.name, bases, docs,134 self._stmt_list(node.body))135 def visit_compare(self, node):136 """return an astroid.Compare node as string"""137 rhs_str = ' '.join(['%s %s' % (op, expr.accept(self))138 for op, expr in node.ops])139 return '%s %s' % (node.left.accept(self), rhs_str)140 def visit_comprehension(self, node):141 """return an astroid.Comprehension node as string"""142 ifs = ''.join([' if %s' % n.accept(self) for n in node.ifs])143 return 'for %s in %s%s' % (node.target.accept(self),144 node.iter.accept(self), ifs)145 def visit_const(self, node):146 """return an astroid.Const node as string"""147 return repr(node.value)148 def visit_continue(self, node):149 """return an astroid.Continue node as string"""150 return 'continue'151 def visit_delete(self, node): # XXX check if correct152 """return an astroid.Delete node as string"""153 return 'del %s' % ', '.join([child.accept(self)154 for child in node.targets])155 def visit_delattr(self, node):156 """return an astroid.DelAttr node as string"""157 return self.visit_getattr(node)158 def visit_delname(self, node):159 """return an astroid.DelName node as string"""160 return node.name161 def visit_decorators(self, node):162 """return an astroid.Decorators node as string"""163 return '@%s\n' % '\n@'.join([item.accept(self) for item in node.nodes])164 def visit_dict(self, node):165 """return an astroid.Dict node as string"""166 return '{%s}' % ', '.join(['%s: %s' % (key.accept(self),167 value.accept(self))168 for key, value in node.items])169 def visit_dictcomp(self, node):170 """return an astroid.DictComp node as string"""171 return '{%s: %s %s}' % (node.key.accept(self), node.value.accept(self),172 ' '.join([n.accept(self) for n in node.generators]))173 def visit_discard(self, node):174 """return an astroid.Discard node as string"""175 return node.value.accept(self)176 def visit_emptynode(self, node):177 """dummy method for visiting an Empty node"""178 return ''179 def visit_excepthandler(self, node):180 if node.type:181 if node.name:182 excs = 'except %s, %s' % (node.type.accept(self),183 node.name.accept(self))184 else:185 excs = 'except %s' % node.type.accept(self)186 else:187 excs = 'except'188 return '%s:\n%s' % (excs, self._stmt_list(node.body))189 def visit_ellipsis(self, node):190 """return an astroid.Ellipsis node as string"""191 return '...'192 def visit_empty(self, node):193 """return an Empty node as string"""194 return ''195 def visit_exec(self, node):196 """return an astroid.Exec node as string"""197 if node.locals:198 return 'exec %s in %s, %s' % (node.expr.accept(self),199 node.locals.accept(self),200 node.globals.accept(self))201 if node.globals:202 return 'exec %s in %s' % (node.expr.accept(self),203 node.globals.accept(self))204 return 'exec %s' % node.expr.accept(self)205 def visit_extslice(self, node):206 """return an astroid.ExtSlice node as string"""207 return ','.join([dim.accept(self) for dim in node.dims])208 def visit_for(self, node):209 """return an astroid.For node as string"""210 fors = 'for %s in %s:\n%s' % (node.target.accept(self),211 node.iter.accept(self),212 self._stmt_list(node.body))213 if node.orelse:214 fors = '%s\nelse:\n%s' % (fors, self._stmt_list(node.orelse))215 return fors216 def visit_from(self, node):217 """return an astroid.From node as string"""218 return 'from %s import %s' % ('.' * (node.level or 0) + node.modname,219 _import_string(node.names))220 def visit_function(self, node):221 """return an astroid.Function node as string"""222 decorate = node.decorators and node.decorators.accept(self) or ''223 docs = node.doc and '\n%s"""%s"""' % (INDENT, node.doc) or ''224 return '\n%sdef %s(%s):%s\n%s' % (decorate, node.name, node.args.accept(self),225 docs, self._stmt_list(node.body))226 def visit_genexpr(self, node):227 """return an astroid.GenExpr node as string"""228 return '(%s %s)' % (node.elt.accept(self),229 ' '.join([n.accept(self) for n in node.generators]))230 def visit_getattr(self, node):231 """return an astroid.Getattr node as string"""232 return '%s.%s' % (node.expr.accept(self), node.attrname)233 def visit_global(self, node):234 """return an astroid.Global node as string"""235 return 'global %s' % ', '.join(node.names)236 def visit_if(self, node):237 """return an astroid.If node as string"""238 ifs = ['if %s:\n%s' % (node.test.accept(self), self._stmt_list(node.body))]239 if node.orelse:# XXX use elif ???240 ifs.append('else:\n%s' % self._stmt_list(node.orelse))241 return '\n'.join(ifs)242 def visit_ifexp(self, node):243 """return an astroid.IfExp node as string"""244 return '%s if %s else %s' % (node.body.accept(self),245 node.test.accept(self),246 node.orelse.accept(self))247 def visit_import(self, node):248 """return an astroid.Import node as string"""249 return 'import %s' % _import_string(node.names)250 def visit_keyword(self, node):251 """return an astroid.Keyword node as string"""252 return '%s=%s' % (node.arg, node.value.accept(self))253 def visit_lambda(self, node):254 """return an astroid.Lambda node as string"""255 return 'lambda %s: %s' % (node.args.accept(self),256 node.body.accept(self))257 def visit_list(self, node):258 """return an astroid.List node as string"""259 return '[%s]' % ', '.join([child.accept(self) for child in node.elts])260 def visit_listcomp(self, node):261 """return an astroid.ListComp node as string"""262 return '[%s %s]' % (node.elt.accept(self),263 ' '.join([n.accept(self) for n in node.generators]))264 def visit_module(self, node):265 """return an astroid.Module node as string"""266 docs = node.doc and '"""%s"""\n\n' % node.doc or ''267 return docs + '\n'.join([n.accept(self) for n in node.body]) + '\n\n'268 def visit_name(self, node):269 """return an astroid.Name node as string"""270 return node.name271 def visit_pass(self, node):272 """return an astroid.Pass node as string"""273 return 'pass'274 def visit_print(self, node):275 """return an astroid.Print node as string"""276 nodes = ', '.join([n.accept(self) for n in node.values])277 if not node.nl:278 nodes = '%s,' % nodes279 if node.dest:280 return 'print >> %s, %s' % (node.dest.accept(self), nodes)281 return 'print %s' % nodes282 def visit_raise(self, node):283 """return an astroid.Raise node as string"""284 if node.exc:285 if node.inst:286 if node.tback:287 return 'raise %s, %s, %s' % (node.exc.accept(self),288 node.inst.accept(self),289 node.tback.accept(self))290 return 'raise %s, %s' % (node.exc.accept(self),291 node.inst.accept(self))292 return 'raise %s' % node.exc.accept(self)293 return 'raise'294 def visit_return(self, node):295 """return an astroid.Return node as string"""296 if node.value:297 return 'return %s' % node.value.accept(self)298 else:299 return 'return'300 def visit_index(self, node):301 """return a astroid.Index node as string"""302 return node.value.accept(self)303 def visit_set(self, node):304 """return an astroid.Set node as string"""305 return '{%s}' % ', '.join([child.accept(self) for child in node.elts])306 def visit_setcomp(self, node):307 """return an astroid.SetComp node as string"""308 return '{%s %s}' % (node.elt.accept(self),309 ' '.join([n.accept(self) for n in node.generators]))310 def visit_slice(self, node):311 """return a astroid.Slice node as string"""312 lower = node.lower and node.lower.accept(self) or ''313 upper = node.upper and node.upper.accept(self) or ''314 step = node.step and node.step.accept(self) or ''315 if step:316 return '%s:%s:%s' % (lower, upper, step)317 return '%s:%s' % (lower, upper)318 def visit_subscript(self, node):319 """return an astroid.Subscript node as string"""320 return '%s[%s]' % (node.value.accept(self), node.slice.accept(self))321 def visit_tryexcept(self, node):322 """return an astroid.TryExcept node as string"""323 trys = ['try:\n%s' % self._stmt_list(node.body)]324 for handler in node.handlers:325 trys.append(handler.accept(self))326 if node.orelse:327 trys.append('else:\n%s' % self._stmt_list(node.orelse))328 return '\n'.join(trys)329 def visit_tryfinally(self, node):330 """return an astroid.TryFinally node as string"""331 return 'try:\n%s\nfinally:\n%s' % (self._stmt_list(node.body),332 self._stmt_list(node.finalbody))333 def visit_tuple(self, node):334 """return an astroid.Tuple node as string"""335 if len(node.elts) == 1:336 return '(%s, )' % node.elts[0].accept(self)337 return '(%s)' % ', '.join([child.accept(self) for child in node.elts])338 def visit_unaryop(self, node):339 """return an astroid.UnaryOp node as string"""340 if node.op == 'not':341 operator = 'not '342 else:343 operator = node.op344 return '%s%s' % (operator, node.operand.accept(self))345 def visit_while(self, node):346 """return an astroid.While node as string"""347 whiles = 'while %s:\n%s' % (node.test.accept(self),348 self._stmt_list(node.body))349 if node.orelse:350 whiles = '%s\nelse:\n%s' % (whiles, self._stmt_list(node.orelse))351 return whiles352 def visit_with(self, node): # 'with' without 'as' is possible353 """return an astroid.With node as string"""354 items = ', '.join(('(%s)' % expr.accept(self)) +355 (vars and ' as (%s)' % (vars.accept(self)) or '')356 for expr, vars in node.items)357 return 'with %s:\n%s' % (items, self._stmt_list(node.body))358 def visit_yield(self, node):359 """yield an ast.Yield node as string"""360 yi_val = node.value and (" " + node.value.accept(self)) or ""361 expr = 'yield' + yi_val362 if node.parent.is_statement:363 return expr364 else:365 return "(%s)" % (expr,)366class AsStringVisitor3k(AsStringVisitor):367 """AsStringVisitor3k overwrites some AsStringVisitor methods"""368 def visit_excepthandler(self, node):369 if node.type:370 if node.name:371 excs = 'except %s as %s' % (node.type.accept(self),372 node.name.accept(self))373 else:374 excs = 'except %s' % node.type.accept(self)375 else:376 excs = 'except'377 return '%s:\n%s' % (excs, self._stmt_list(node.body))378 def visit_nonlocal(self, node):379 """return an astroid.Nonlocal node as string"""380 return 'nonlocal %s' % ', '.join(node.names)381 def visit_raise(self, node):382 """return an astroid.Raise node as string"""383 if node.exc:384 if node.cause:385 return 'raise %s from %s' % (node.exc.accept(self),386 node.cause.accept(self))387 return 'raise %s' % node.exc.accept(self)388 return 'raise'389 def visit_starred(self, node):390 """return Starred node as string"""391 return "*" + node.value.accept(self)392 def visit_yieldfrom(self, node):393 """ Return an astroid.YieldFrom node as string. """394 yi_val = node.value and (" " + node.value.accept(self)) or ""395 expr = 'yield from' + yi_val396 if node.parent.is_statement:397 return expr398 else:399 return "(%s)" % (expr,)400def _import_string(names):401 """return a list of (name, asname) formatted as a string"""402 _names = []403 for name, asname in names:404 if asname is not None:405 _names.append('%s as %s' % (name, asname))406 else:407 _names.append(name)408 return ', '.join(_names)...

Full Screen

Full Screen

cgen.py

Source:cgen.py Github

copy

Full Screen

...7class CxxCodeGen(CodePrinter, Visitor):8 def __init__(self, outf=sys.stdout, indentCols=4):9 CodePrinter.__init__(self, outf, indentCols)10 def cgen(self, cxxfile):11 cxxfile.accept(self)12 def visitWhitespace(self, ws):13 if ws.indent:14 self.printdent('')15 self.write(ws.ws)16 def visitCppDirective(self, cd):17 if cd.rest:18 self.println('#%s %s'% (cd.directive, cd.rest))19 else:20 self.println('#%s'% (cd.directive))21 def visitNamespace(self, ns):22 self.println('namespace '+ ns.name +' {')23 self.visitBlock(ns)24 self.println('} // namespace '+ ns.name)25 def visitType(self, t):26 if t.const:27 self.write('const ')28 self.write(t.name)29 if t.T is not None:30 self.write('<')31 if type(t.T) is list:32 t.T[0].accept(self)33 for tt in t.T[1:]:34 self.write(', ')35 tt.accept(self)36 else:37 t.T.accept(self)38 self.write('>')39 if t.inner is not None:40 self.write('::')41 t.inner.accept(self)42 ts = ''43 if t.ptr: ts += '*'44 elif t.ptrconst: ts += '* const'45 elif t.ptrptr: ts += '**'46 elif t.ptrconstptr: ts += '* const*'47 ts += '&' * t.ref48 self.write(ts)49 def visitTypeEnum(self, te):50 self.write('enum')51 if te.name:52 self.write(' '+ te.name)53 self.println(' {')54 self.indent()55 nids = len(te.idnums)56 for i, (id, num) in enumerate(te.idnums):57 self.printdent(id)58 if num:59 self.write(' = '+ str(num))60 if i != (nids-1):61 self.write(',')62 self.println()63 self.dedent()64 self.printdent('}')65 def visitTypeUnion(self, u):66 self.write('union')67 if u.name:68 self.write(' '+ u.name)69 self.println(' {')70 self.indent()71 for decl in u.components:72 self.printdent()73 decl.accept(self)74 self.println(';')75 self.dedent()76 self.printdent('}')77 def visitTypeFunction(self, fn):78 self.write('std::function<')79 fn.ret.accept(self)80 self.write('(')81 self.writeDeclList(fn.params)82 self.write(')>')83 def visitTypedef(self, td):84 if td.templateargs:85 formals = ', '.join([ 'class ' + T for T in td.templateargs ])86 args = ', '.join(td.templateargs)87 self.printdent('template<' + formals + '> using ' + td.totypename + ' = ')88 td.fromtype.accept(self)89 self.println('<' + args + '>;')90 else:91 self.printdent('typedef ')92 td.fromtype.accept(self)93 self.println(' '+ td.totypename +';')94 def visitUsing(self, us):95 self.printdent('using ')96 us.type.accept(self)97 self.println(';')98 def visitForwardDecl(self, fd):99 if fd.cls: self.printdent('class ')100 elif fd.struct: self.printdent('struct ')101 self.write(str(fd.pqname))102 self.println(';')103 def visitDecl(self, d):104 # C-syntax arrays make code generation much more annoying105 if isinstance(d.type, TypeArray):106 d.type.basetype.accept(self)107 else:108 d.type.accept(self)109 if d.name:110 self.write(' '+ d.name)111 if isinstance(d.type, TypeArray):112 self.write('[')113 d.type.nmemb.accept(self)114 self.write(']')115 def visitParam(self, p):116 self.visitDecl(p)117 if p.default is not None:118 self.write(' = ')119 p.default.accept(self)120 def visitClass(self, c):121 if c.specializes is not None:122 self.printdentln('template<>')123 if c.struct:124 self.printdent('struct')125 else:126 self.printdent('class')127 self.write(' '+ c.name)128 if c.final:129 self.write(' final')130 if c.specializes is not None:131 self.write(' <')132 c.specializes.accept(self)133 self.write('>')134 ninh = len(c.inherits)135 if 0 < ninh:136 self.println(' :')137 self.indent()138 for i, inherit in enumerate(c.inherits):139 self.printdent()140 inherit.accept(self)141 if i != (ninh - 1):142 self.println(',')143 self.dedent()144 self.println()145 self.printdentln('{')146 self.indent()147 self.visitBlock(c)148 self.dedent()149 self.printdentln('};')150 def visitInherit(self, inh):151 self.write(inh.viz +' ')152 inh.type.accept(self)153 def visitFriendClassDecl(self, fcd):154 self.printdentln('friend class '+ fcd.friend +';')155 def visitMethodDecl(self, md):156 assert not (md.static and md.virtual)157 if md.T:158 self.write('template<')159 self.write('typename ')160 md.T.accept(self)161 self.println('>')162 self.printdent()163 if md.warn_unused:164 self.write('MOZ_MUST_USE ')165 if md.inline:166 self.write('inline ')167 if md.never_inline:168 self.write('MOZ_NEVER_INLINE ')169 if md.static:170 self.write('static ')171 if md.virtual:172 self.write('virtual ')173 if md.ret:174 if md.only_for_definition:175 self.write('auto ')176 else:177 md.ret.accept(self)178 self.println()179 self.printdent()180 if md.typeop is not None:181 self.write('operator ')182 md.typeop.accept(self)183 else:184 self.write(md.name)185 self.write('(')186 self.writeDeclList(md.params)187 self.write(')')188 if md.const:189 self.write(' const')190 if md.ret and md.only_for_definition:191 self.write(' -> ')192 md.ret.accept(self)193 if md.pure:194 self.write(' = 0')195 def visitMethodDefn(self, md):196 if md.decl.pure:197 return198 self.printdent()199 md.decl.accept(self)200 self.println()201 self.printdentln('{')202 self.indent()203 self.visitBlock(md)204 self.dedent()205 self.printdentln('}')206 def visitConstructorDecl(self, cd):207 if cd.explicit:208 self.write('explicit ')209 else:210 self.write('MOZ_IMPLICIT ')211 self.visitMethodDecl(cd)212 def visitConstructorDefn(self, cd):213 self.printdent()214 cd.decl.accept(self)215 if len(cd.memberinits):216 self.println(' :')217 self.indent()218 ninits = len(cd.memberinits)219 for i, init in enumerate(cd.memberinits):220 self.printdent()221 init.accept(self)222 if i != (ninits-1):223 self.println(',')224 self.dedent()225 self.println()226 self.printdentln('{')227 self.indent()228 self.visitBlock(cd)229 self.dedent()230 self.printdentln('}')231 def visitDestructorDecl(self, dd):232 if dd.inline:233 self.write('inline ')234 if dd.virtual:235 self.write('virtual ')236 # hack alert237 parts = dd.name.split('::')238 parts[-1] = '~'+ parts[-1]239 self.write('::'.join(parts) +'()')240 def visitDestructorDefn(self, dd):241 self.printdent()242 dd.decl.accept(self)243 self.println()244 self.printdentln('{')245 self.indent()246 self.visitBlock(dd)247 self.dedent()248 self.printdentln('}')249 def visitExprLiteral(self, el):250 self.write(str(el))251 def visitExprVar(self, ev):252 self.write(ev.name)253 def visitExprPrefixUnop(self, e):254 self.write('(')255 self.write(e.op)256 self.write('(')257 e.expr.accept(self)258 self.write(')')259 self.write(')')260 def visitExprCast(self, c):261 pfx, sfx = '', ''262 if c.dynamic: pfx, sfx = 'dynamic_cast<', '>'263 elif c.static: pfx, sfx = 'static_cast<', '>'264 elif c.reinterpret: pfx, sfx = 'reinterpret_cast<', '>'265 elif c.const: pfx, sfx = 'const_cast<', '>'266 elif c.C: pfx, sfx = '(', ')'267 self.write(pfx)268 c.type.accept(self)269 self.write(sfx +'(')270 c.expr.accept(self)271 self.write(')')272 def visitExprBinary(self, e):273 self.write('(')274 e.left.accept(self)275 self.write(') '+ e.op +' (')276 e.right.accept(self)277 self.write(')')278 def visitExprConditional(self, c):279 self.write('(')280 c.cond.accept(self)281 self.write(' ? ')282 c.ife.accept(self)283 self.write(' : ')284 c.elsee.accept(self)285 self.write(')')286 def visitExprIndex(self, ei):287 ei.arr.accept(self)288 self.write('[')289 ei.idx.accept(self)290 self.write(']')291 def visitExprSelect(self, es):292 self.write('(')293 es.obj.accept(self)294 self.write(')')295 self.write(es.op)296 es.field.accept(self)297 def visitExprAssn(self, ea):298 ea.lhs.accept(self)299 self.write(' '+ ea.op +' ')300 ea.rhs.accept(self)301 def visitExprCall(self, ec):302 ec.func.accept(self)303 self.write('(')304 self.writeExprList(ec.args)305 self.write(')')306 def visitExprMove(self, em):307 self.visitExprCall(em)308 def visitExprNew(self, en):309 self.write('new ')310 if en.newargs is not None:311 self.write('(')312 self.writeExprList(en.newargs)313 self.write(') ')314 en.ctype.accept(self)315 if en.args is not None:316 self.write('(')317 self.writeExprList(en.args)318 self.write(')')319 def visitExprDelete(self, ed):320 self.write('delete ')321 ed.obj.accept(self)322 def visitExprLambda(self, l):323 self.write('[')324 ncaptures = len(l.captures)325 for i, c in enumerate(l.captures):326 c.accept(self)327 if i != (ncaptures-1):328 self.write(', ')329 self.write('](')330 self.writeDeclList(l.params)331 self.write(')')332 if l.ret:333 self.write(' -> ')334 l.ret.accept(self)335 self.println(' {')336 self.indent()337 self.visitBlock(l)338 self.dedent()339 self.printdent('}')340 def visitStmtBlock(self, b):341 self.printdentln('{')342 self.indent()343 self.visitBlock(b)344 self.dedent()345 self.printdentln('}')346 def visitLabel(self, label):347 self.dedent() # better not be at global scope ...348 self.printdentln(label.name +':')349 self.indent()350 def visitCaseLabel(self, cl):351 self.dedent()352 self.printdentln('case '+ cl.name +':')353 self.indent()354 def visitDefaultLabel(self, dl):355 self.dedent()356 self.printdentln('default:')357 self.indent()358 def visitStmtIf(self, si):359 self.printdent('if (')360 si.cond.accept(self)361 self.println(') {')362 self.indent()363 si.ifb.accept(self)364 self.dedent()365 self.printdentln('}')366 if si.elseb is not None:367 self.printdentln('else {')368 self.indent()369 si.elseb.accept(self)370 self.dedent()371 self.printdentln('}')372 def visitStmtFor(self, sf):373 self.printdent('for (')374 if sf.init is not None:375 sf.init.accept(self)376 self.write('; ')377 if sf.cond is not None:378 sf.cond.accept(self)379 self.write('; ')380 if sf.update is not None:381 sf.update.accept(self)382 self.println(') {')383 self.indent()384 self.visitBlock(sf)385 self.dedent()386 self.printdentln('}')387 def visitStmtRangedFor(self, rf):388 self.printdent('for (auto& ')389 rf.var.accept(self)390 self.write(' : ')391 rf.iteree.accept(self)392 self.println(') {')393 self.indent()394 self.visitBlock(rf)395 self.dedent()396 self.printdentln('}')397 def visitStmtSwitch(self, sw):398 self.printdent('switch (')399 sw.expr.accept(self)400 self.println(') {')401 self.indent()402 self.visitBlock(sw)403 self.dedent()404 self.printdentln('}')405 def visitStmtBreak(self, sb):406 self.printdentln('break;')407 def visitStmtDecl(self, sd):408 self.printdent()409 sd.decl.accept(self)410 if sd.initargs is not None:411 self.write('(')412 self.writeDeclList(sd.initargs)413 self.write(')')414 if sd.init is not None:415 self.write(' = ')416 sd.init.accept(self)417 self.println(';')418 def visitStmtExpr(self, se):419 self.printdent()420 se.expr.accept(self)421 self.println(';')422 def visitStmtReturn(self, sr):423 self.printdent('return')424 if sr.expr:425 self.write (' ')426 sr.expr.accept(self)427 self.println(';')428 def writeDeclList(self, decls):429 # FIXME/cjones: try to do nice formatting of these guys430 ndecls = len(decls)431 if 0 == ndecls:432 return433 elif 1 == ndecls:434 decls[0].accept(self)435 return436 self.indent()437 self.indent()438 for i, decl in enumerate(decls):439 self.println()440 self.printdent()441 decl.accept(self)442 if i != (ndecls-1):443 self.write(',')444 self.dedent()445 self.dedent()446 def writeExprList(self, exprs):447 # FIXME/cjones: try to do nice formatting and share code with448 # writeDeclList()449 nexprs = len(exprs)450 for i, expr in enumerate(exprs):451 expr.accept(self)452 if i != (nexprs-1):...

Full Screen

Full Screen

test_acceptparse.py

Source:test_acceptparse.py Github

copy

Full Screen

1from webob import Request2from webob.acceptparse import Accept, MIMEAccept, NilAccept, NoAccept, accept_property, parse_accept3from nose.tools import eq_, assert_raises4def test_parse_accept_badq():5 assert parse_accept("value1; q=0.1.2") == [('value1', 1)]6def test_init_accept_content_type():7 name, value = ('Content-Type', 'text/html')8 accept = Accept(name, value)9 assert accept.header_name == name10 assert accept.header_value == value11 assert accept._parsed == [('text/html', 1)]12def test_init_accept_accept_charset():13 name, value = ('Accept-Charset', 'iso-8859-5, unicode-1-1;q=0.8')14 accept = Accept(name, value)15 assert accept.header_name == name16 assert accept.header_value == value17 assert accept._parsed == [('iso-8859-5', 1),18 ('unicode-1-1', 0.80000000000000004),19 ('iso-8859-1', 1)]20def test_init_accept_accept_charset_with_iso_8859_1():21 name, value = ('Accept-Charset', 'iso-8859-1')22 accept = Accept(name, value)23 assert accept.header_name == name24 assert accept.header_value == value25 assert accept._parsed == [('iso-8859-1', 1)]26def test_init_accept_accept_charset_wildcard():27 name, value = ('Accept-Charset', '*')28 accept = Accept(name, value)29 assert accept.header_name == name30 assert accept.header_value == value31 assert accept._parsed == [('*', 1)]32def test_init_accept_accept_language():33 name, value = ('Accept-Language', 'da, en-gb;q=0.8, en;q=0.7')34 accept = Accept(name, value)35 assert accept.header_name == name36 assert accept.header_value == value37 assert accept._parsed == [('da', 1),38 ('en-gb', 0.80000000000000004),39 ('en', 0.69999999999999996)]40def test_init_accept_invalid_value():41 name, value = ('Accept-Language', 'da, q, en-gb;q=0.8')42 accept = Accept(name, value)43 # The "q" value should not be there.44 assert accept._parsed == [('da', 1),45 ('en-gb', 0.80000000000000004)]46def test_init_accept_invalid_q_value():47 name, value = ('Accept-Language', 'da, en-gb;q=foo')48 accept = Accept(name, value)49 # I can't get to cover line 40-41 (webob.acceptparse) as the regex50 # will prevent from hitting these lines (aconrad)51 assert accept._parsed == [('da', 1), ('en-gb', 1)]52def test_accept_repr():53 name, value = ('Content-Type', 'text/html')54 accept = Accept(name, value)55 assert repr(accept) == '<%s at 0x%x %s: %s>' % ('Accept',56 abs(id(accept)),57 name,58 str(accept))59def test_accept_str():60 name, value = ('Content-Type', 'text/html')61 accept = Accept(name, value)62 assert str(accept) == value63def test_zero_quality():64 assert Accept('Accept-Encoding', 'bar, *;q=0').best_match(['foo']) is None65 assert 'foo' not in Accept('Accept-Encoding', '*;q=0')66 assert Accept('Accept-Encoding', 'foo, *;q=0').first_match(['bar', 'foo']) == 'foo'67def test_accept_str_with_q_not_1():68 name, value = ('Content-Type', 'text/html;q=0.5')69 accept = Accept(name, value)70 assert str(accept) == value71def test_accept_str_with_q_not_1_multiple():72 name, value = ('Content-Type', 'text/html;q=0.5, foo/bar')73 accept = Accept(name, value)74 assert str(accept) == value75def test_accept_add_other_accept():76 accept = Accept('Content-Type', 'text/html') + \77 Accept('Content-Type', 'foo/bar')78 assert str(accept) == 'text/html, foo/bar'79 accept += Accept('Content-Type', 'bar/baz;q=0.5')80 assert str(accept) == 'text/html, foo/bar, bar/baz;q=0.5'81def test_accept_add_other_list_of_tuples():82 accept = Accept('Content-Type', 'text/html')83 accept += [('foo/bar', 1)]84 assert str(accept) == 'text/html, foo/bar'85 accept += [('bar/baz', 0.5)]86 assert str(accept) == 'text/html, foo/bar, bar/baz;q=0.5'87 accept += ['she/bangs', 'the/house']88 assert str(accept) == ('text/html, foo/bar, bar/baz;q=0.5, '89 'she/bangs, the/house')...

Full Screen

Full Screen

policy.py

Source:policy.py Github

copy

Full Screen

1"""2Unit tests for the stem.exit_policy.ExitPolicy class.3"""4import pickle5import unittest6from stem.exit_policy import (7 DEFAULT_POLICY_RULES,8 get_config_policy,9 ExitPolicy,10 MicroExitPolicy,11 ExitPolicyRule,12)13class TestExitPolicy(unittest.TestCase):14 def test_example(self):15 # tests the ExitPolicy and MicroExitPolicy pydoc examples16 policy = ExitPolicy('accept *:80', 'accept *:443', 'reject *:*')17 self.assertEqual('accept *:80, accept *:443, reject *:*', str(policy))18 self.assertEqual('accept 80, 443', policy.summary())19 self.assertTrue(policy.can_exit_to('75.119.206.243', 80))20 policy = MicroExitPolicy('accept 80,443')21 self.assertTrue(policy.can_exit_to('75.119.206.243', 80))22 def test_constructor(self):23 # The ExitPolicy constructor takes a series of string or ExitPolicyRule24 # entries. Extra whitespace is ignored to make csvs easier to handle.25 expected_policy = ExitPolicy(26 ExitPolicyRule('accept *:80'),27 ExitPolicyRule('accept *:443'),28 ExitPolicyRule('reject *:*'),29 )30 policy = ExitPolicy('accept *:80', 'accept *:443', 'reject *:*')31 self.assertEqual(expected_policy, policy)32 policy = ExitPolicy(*'accept *:80, accept *:443, reject *:*'.split(','))33 self.assertEqual(expected_policy, policy)34 # checks that we truncate after getting a catch-all policy35 policy = ExitPolicy(*'accept *:80, accept *:443, reject *:*, accept *:20-50'.split(','))36 self.assertEqual(expected_policy, policy)37 # checks that we compress redundant policies38 policy = ExitPolicy(*'reject *:80, reject *:443, reject *:*'.split(','))39 self.assertEqual(ExitPolicy('reject *:*'), policy)40 def test_can_exit_to(self):41 # Basic sanity test for our can_exit_to() method. Most of the interesting42 # use cases (ip masks, wildcards, etc) are covered by the ExitPolicyRule43 # tests.44 policy = ExitPolicy('accept *:80', 'accept *:443', 'reject *:*')45 for index in range(1, 500):46 ip_addr = '%i.%i.%i.%i' % (index / 2, index / 2, index / 2, index / 2)47 expected_result = index in (80, 443)48 self.assertEqual(expected_result, policy.can_exit_to(ip_addr, index))49 self.assertEqual(expected_result, policy.can_exit_to(port = index))50 def test_is_exiting_allowed(self):51 test_inputs = {52 (): True,53 ('accept *:*', ): True,54 ('reject *:*', ): False,55 ('accept *:80', 'reject *:*'): True,56 ('reject *:80', 'accept *:80', 'reject *:*'): False,57 ('reject *:50-90', 'accept *:80', 'reject *:*'): False,58 ('reject *:2-65535', 'accept *:80-65535', 'reject *:*'): False,59 ('reject *:2-65535', 'accept 127.0.0.0:1', 'reject *:*'): True,60 ('reject 127.0.0.1:*', 'accept *:80', 'reject *:*'): True,61 }62 for rules, expected_result in test_inputs.items():63 policy = ExitPolicy(*rules)64 self.assertEqual(expected_result, policy.is_exiting_allowed())65 def test_summary_examples(self):66 # checks the summary() method's pydoc examples67 policy = ExitPolicy('accept *:80', 'accept *:443', 'reject *:*')68 self.assertEqual('accept 80, 443', policy.summary())69 policy = ExitPolicy('accept *:443', 'reject *:1-1024', 'accept *:*')70 self.assertEqual('reject 1-442, 444-1024', policy.summary())71 def test_summary_large_ranges(self):72 # checks the summary() method when the policy includes very large port ranges73 policy = ExitPolicy('reject *:80-65535', 'accept *:1-65533', 'reject *:*')74 self.assertEqual('accept 1-79', policy.summary())75 def test_non_private_non_default_policy(self):76 policy = get_config_policy('reject *:80-65535, accept *:1-65533, reject *:*')77 for rule in policy:78 self.assertFalse(rule.is_private())79 self.assertFalse(rule.is_default())80 self.assertFalse(policy.has_private())81 self.assertFalse(policy.has_default())82 self.assertEqual(policy, policy.strip_private())83 self.assertEqual(policy, policy.strip_default())84 def test_all_private_policy(self):85 for port in ('*', '80', '1-1024'):86 private_policy = get_config_policy('reject private:%s' % port)87 for rule in private_policy:88 self.assertTrue(rule.is_private())89 self.assertEqual(ExitPolicy(), private_policy.strip_private())90 # though not commonly done, technically private policies can be accept rules too91 private_policy = get_config_policy('accept private:*')92 self.assertEqual(ExitPolicy(), private_policy.strip_private())93 def test_all_default_policy(self):94 policy = ExitPolicy(*DEFAULT_POLICY_RULES)95 for rule in policy:96 self.assertTrue(rule.is_default())97 self.assertTrue(policy.has_default())98 self.assertEqual(ExitPolicy(), policy.strip_default())99 def test_mixed_private_policy(self):100 policy = get_config_policy('accept *:80, reject private:1-65533, accept *:*')101 for rule in policy:102 self.assertTrue(rule.is_accept != rule.is_private()) # only reject rules are the private ones103 self.assertEqual(get_config_policy('accept *:80, accept *:*'), policy.strip_private())104 def test_mixed_default_policy(self):105 policy = ExitPolicy('accept *:80', 'accept 127.0.0.1:1-65533', *DEFAULT_POLICY_RULES)106 for rule in policy:107 # only accept-all and reject rules are the default ones108 self.assertTrue(rule.is_accept != rule.is_default() or (rule.is_accept and rule.is_address_wildcard() and rule.is_port_wildcard()))109 self.assertEqual(get_config_policy('accept *:80, accept 127.0.0.1:1-65533'), policy.strip_default())110 def test_str(self):111 # sanity test for our __str__ method112 policy = ExitPolicy(' accept *:80\n', '\taccept *:443')113 self.assertEqual('accept *:80, accept *:443', str(policy))114 policy = ExitPolicy('reject 0.0.0.0/255.255.255.0:*', 'accept *:*')115 self.assertEqual('reject 0.0.0.0/24:*, accept *:*', str(policy))116 def test_iter(self):117 # sanity test for our __iter__ method118 rules = [119 ExitPolicyRule('accept *:80'),120 ExitPolicyRule('accept *:443'),121 ExitPolicyRule('reject *:*'),122 ]123 self.assertEqual(rules, list(ExitPolicy(*rules)))124 self.assertEqual(rules, list(ExitPolicy('accept *:80', 'accept *:443', 'reject *:*')))125 def test_microdescriptor_parsing(self):126 # mapping between inputs and if they should succeed or not127 test_inputs = {128 'accept 80': True,129 'accept 80,443': True,130 '': False,131 'accept': False,132 'accept ': False,133 'accept\t80,443': False,134 'accept 80, 443': False,135 'accept 80,\t443': False,136 '80,443': False,137 'accept 80,-443': False,138 'accept 80,+443': False,139 'accept 80,66666': False,140 'reject 80,foo': False,141 'bar 80,443': False,142 }143 for policy_arg, expect_success in test_inputs.items():144 try:145 policy = MicroExitPolicy(policy_arg)146 if expect_success:147 self.assertEqual(policy_arg, str(policy))148 else:149 self.fail()150 except ValueError:151 if expect_success:152 self.fail()153 def test_microdescriptor_attributes(self):154 # checks that its is_accept attribute is properly set155 # single port156 policy = MicroExitPolicy('accept 443')157 self.assertTrue(policy.is_accept)158 # multiple ports159 policy = MicroExitPolicy('accept 80,443')160 self.assertTrue(policy.is_accept)161 # port range162 policy = MicroExitPolicy('reject 1-1024')163 self.assertFalse(policy.is_accept)164 def test_microdescriptor_can_exit_to(self):165 test_inputs = {166 'accept 443': {442: False, 443: True, 444: False},167 'reject 443': {442: True, 443: False, 444: True},168 'accept 80,443': {80: True, 443: True, 10: False},169 'reject 1-1024': {1: False, 1024: False, 1025: True},170 }171 for policy_arg, attr in test_inputs.items():172 policy = MicroExitPolicy(policy_arg)173 for port, expected_value in attr.items():174 self.assertEqual(expected_value, policy.can_exit_to(port = port))175 # address argument should be ignored176 policy = MicroExitPolicy('accept 80,443')177 self.assertFalse(policy.can_exit_to('127.0.0.1', 79))178 self.assertTrue(policy.can_exit_to('127.0.0.1', 80))179 def test_get_config_policy(self):180 test_inputs = {181 '': ExitPolicy(),182 'reject *': ExitPolicy('reject *:*'),183 'reject *:*': ExitPolicy('reject *:*'),184 'reject private': ExitPolicy(185 'reject 0.0.0.0/8:*',186 'reject 169.254.0.0/16:*',187 'reject 127.0.0.0/8:*',188 'reject 192.168.0.0/16:*',189 'reject 10.0.0.0/8:*',190 'reject 172.16.0.0/12:*',191 'reject 12.34.56.78:*',192 ),193 'accept *:80, reject *': ExitPolicy(194 'accept *:80',195 'reject *:*',196 ),197 ' accept *:80, reject * ': ExitPolicy(198 'accept *:80',199 'reject *:*',200 ),201 }202 for test_input, expected in test_inputs.items():203 self.assertEqual(expected, get_config_policy(test_input, '12.34.56.78'))204 test_inputs = (205 'blarg',206 'accept *:*:*',207 'acceptt *:80',208 'accept 257.0.0.1:80',209 'accept *:999999',210 )211 for test_input in test_inputs:212 self.assertRaises(ValueError, get_config_policy, test_input)213 def test_pickleability(self):214 """215 Checks that we can unpickle ExitPolicy instances.216 """217 policy = ExitPolicy('accept *:80', 'accept *:443', 'reject *:*')218 self.assertTrue(policy.can_exit_to('74.125.28.106', 80))219 encoded_policy = pickle.dumps(policy)220 restored_policy = pickle.loads(encoded_policy)221 self.assertEqual(policy, restored_policy)222 self.assertTrue(restored_policy.is_exiting_allowed())...

Full Screen

Full Screen

test_misc_tools.py

Source:test_misc_tools.py Github

copy

Full Screen

...27 @cherrypy.expose28 def index(self):29 return '<a href="feed">Atom feed</a>'30 @cherrypy.expose31 @tools.accept(media='application/atom+xml')32 def feed(self):33 return """<?xml version="1.0" encoding="utf-8"?>34<feed xmlns="http://www.w3.org/2005/Atom">35 <title>Unknown Blog</title>36</feed>"""37 @cherrypy.expose38 def select(self):39 # We could also write this: mtype = cherrypy.lib.accept.accept(...)40 mtype = tools.accept.callable(['text/html', 'text/plain'])41 if mtype == 'text/html':42 return '<h2>Page Title</h2>'43 else:44 return 'PAGE TITLE'45 class Referer:46 @cherrypy.expose47 def accept(self):48 return 'Accepted!'49 reject = accept50 class AutoVary:51 @cherrypy.expose52 def index(self):53 # Read a header directly with 'get'54 cherrypy.request.headers.get('Accept-Encoding')55 # Read a header directly with '__getitem__'56 cherrypy.request.headers['Host']57 # Read a header directly with '__contains__'58 'If-Modified-Since' in cherrypy.request.headers59 # Read a header directly60 'Range' in cherrypy.request.headers61 # Call a lib function...

Full Screen

Full Screen

http.py

Source:http.py Github

copy

Full Screen

1import json2import requests3from threading import Thread4class NetApp_OCUM_HTTP(object):5 """6 Class object for handling HTTP requests/responses for the OCUM.7 """8 def __init__(self, settings):9 self.settings = settings10 self.path = None11 def _GET_worker(self, url, params, accept, responses, embedded_key):12 """13 Worker for performing threaded HTTP GET requests.14 """15 response = requests.get(url,16 auth = (self.settings.api_user, self.settings.api_password),17 verify = self.settings.verify_ssl,18 headers = {19 'Accept': 'application/vnd.netapp.object.inventory.{}.hal+json'.format(accept)20 },21 params = params22 )23 # Request failed24 if not int(response.status_code) == 200:25 raise Exception('Failed to GET {0}: {1}'.format(url, response.json()))26 responses[accept] = response.json()['_embedded'][embedded_key]27 def _sort_response_by_id(self, response, name_from):28 """29 Sort the responses by object ID.30 """31 objects_by_id = {}32 for accept_type, accept_responses in response.items():33 for accept_response in accept_responses:34 current_id = None35 # Object has a top level ID36 if 'id' in accept_response:37 current_id = accept_response['id']38 # Object ID is nested39 else:40 # Extract ID for volume relationship41 if self.path == 'volumes' and accept_type == 'relationship':42 # Map to the source volume if found, otherwise destination volume43 if accept_response['source_volume']['id']:44 current_id = accept_response['source_volume']['id']45 else:46 current_id = accept_response['destination_volume']['id']47 # Extract ID for aggregate capacity48 if self.path == 'aggregates' and accept_type == 'capacity':49 current_id = accept_response['aggregate']['id']50 # Extract ID for node capacity51 if self.path == 'nodes' and accept_type == 'capacity':52 current_id = accept_response['node']['id']53 if not current_id in objects_by_id:54 objects_by_id[current_id] = {55 'type': self.path56 }57 if accept_type == name_from[0]:58 objects_by_id[current_id]['name'] = accept_response[name_from[1]][name_from[2]]59 objects_by_id[current_id][accept_type] = accept_response60 # Convert to an array of objects61 object_array = []62 for object_id, object_attrs in objects_by_id.items():63 object_item = object_attrs64 object_item['id'] = object_id65 object_array.append(object_item)66 return object_array67 def GET(self, url_path, accept, embedded_key, name_from, params={}):68 """69 Make a GET request to the OCUM API method with an optional filter. Start70 a thread for each accept type.71 """72 responses = {}73 threads = []74 self.path = url_path75 api_url = 'https://{0}:{1}/api/ontap/{2}'.format(76 self.settings.api_host,77 self.settings.api_port,78 url_path79 )80 # Get objects for each type of endpoint based on Accept header81 # for accept_type in accept:82 # self._GET_worker(api_url, params, accept_type, responses, embedded_key)83 for accept_type in accept:84 t = Thread(target=self._GET_worker, args=(api_url, params, accept_type, responses, embedded_key))85 t.start()86 threads.append(t)87 for t in threads:88 t.join()89 # Sort response objects by ID and return...

Full Screen

Full Screen

accept.py

Source:accept.py Github

copy

Full Screen

1from ..datastructures import CharsetAccept2from ..datastructures import LanguageAccept3from ..datastructures import MIMEAccept4from ..http import parse_accept_header5from ..utils import cached_property6class AcceptMixin(object):7 """A mixin for classes with an :attr:`~BaseResponse.environ` attribute8 to get all the HTTP accept headers as9 :class:`~werkzeug.datastructures.Accept` objects (or subclasses10 thereof).11 """12 @cached_property13 def accept_mimetypes(self):14 """List of mimetypes this client supports as15 :class:`~werkzeug.datastructures.MIMEAccept` object.16 """17 return parse_accept_header(self.environ.get("HTTP_ACCEPT"), MIMEAccept)18 @cached_property19 def accept_charsets(self):20 """List of charsets this client supports as21 :class:`~werkzeug.datastructures.CharsetAccept` object.22 """23 return parse_accept_header(24 self.environ.get("HTTP_ACCEPT_CHARSET"), CharsetAccept25 )26 @cached_property27 def accept_encodings(self):28 """List of encodings this client accepts. Encodings in a HTTP term29 are compression encodings such as gzip. For charsets have a look at30 :attr:`accept_charset`.31 """32 return parse_accept_header(self.environ.get("HTTP_ACCEPT_ENCODING"))33 @cached_property34 def accept_languages(self):35 """List of languages this client accepts as36 :class:`~werkzeug.datastructures.LanguageAccept` object.37 .. versionchanged 0.538 In previous versions this was a regular39 :class:`~werkzeug.datastructures.Accept` object.40 """41 return parse_accept_header(42 self.environ.get("HTTP_ACCEPT_LANGUAGE"), LanguageAccept...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, accept, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await accept();6 } catch (e) {7 console.error(e);8 } finally {9 await closeBrowser();10 }11})();12const { openBrowser, goto, dismiss, closeBrowser } = require('taiko');13(async () => {14 try {15 await openBrowser();16 await dismiss();17 } catch (e) {18 console.error(e);19 } finally {20 await closeBrowser();21 }22})();23const { openBrowser, goto, press, closeBrowser } = require('taiko');24(async () => {25 try {26 await openBrowser();27 await press("Enter");28 } catch (e) {29 console.error(e);30 } finally {31 await closeBrowser();32 }33})();34const { openBrowser, goto, screenshot, closeBrowser } = require('taiko');35(async () => {36 try {37 await openBrowser();38 await screenshot({ path: './screenshot.png' });39 } catch (e) {40 console.error(e);41 } finally {42 await closeBrowser();43 }44})();45const { openBrowser, goto, setConfig, closeBrowser } = require('taiko');46(async () => {47 try {48 await openBrowser();49 await setConfig({

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, accept } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await goto("google.com");6 await accept();7 } catch (e) {8 console.error(e);9 } finally {10 closeBrowser();11 }12})();13const { openBrowser, goto, accept, closeBrowser } = require('taiko');14(async () => {15 try {16 await openBrowser();17 await goto("google.com");18 await accept();19 } catch (e) {20 console.error(e);21 } finally {22 closeBrowser();23 }24})();25const { openBrowser, goto, accept, closeBrowser } = require('taiko');26(async () => {27 try {28 await openBrowser();29 await goto("google.com");30 await accept();31 } catch (e) {32 console.error(e);33 } finally {34 closeBrowser();35 }36})();37const { openBrowser, goto, accept, closeBrowser } = require('taiko');38(async () => {39 try {40 await openBrowser();41 await goto("google.com");42 await accept();43 } catch (e) {44 console.error(e);45 } finally {46 closeBrowser();47 }48})();49const { openBrowser, goto, accept, closeBrowser } = require('taiko');50(async () => {51 try {52 await openBrowser();53 await goto("google.com");54 await accept();55 } catch (e) {56 console.error(e);57 } finally {58 closeBrowser();59 }60})();61const { openBrowser, goto, accept, closeBrowser } = require('taiko');62(async () => {63 try {64 await openBrowser();65 await goto("google.com");66 await accept();67 } catch (e) {68 console.error(e);69 } finally {70 closeBrowser();71 }72})();73const { openBrowser, goto, accept, closeBrowser } = require('taiko');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, write, click, closeBrowser, accept, $, toRightOf } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await goto("google.com");6 await write("taiko", into($("#lst-ib")));7 await click("Google Search");8 await click("Taiko - A Node.js library to automate end-to-end testing of web applications", toRightOf("Videos"));9 await click("Getting Started");10 await click("Installation");11 await click("Install taiko");12 await click("Install taiko");13 await accept("Allow Taiko to control Google Chrome and

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, click, closeBrowser, accept, $ } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await click("I agree");6 await accept();7 await click("Sign in");8 await accept();9 await click("Sign in");10 await accept();11 await accept();12 await click("Sign in");13 await accept()

Full Screen

Using AI Code Generation

copy

Full Screen

1accept();2dismiss();3press('Enter');4hover('button');5focus('input');6scrollDown(5);7scrollUp(5);8scrollTo('button');9scrollTo(5,5);10scrollRight(5);11scrollLeft(5);12dragAndDrop('input','button');13dragAndDrop('input',5,5);14dragAndDrop(5,5,'button');15dragAndDrop(5,5,5,5);16write('test');17clear('input');18clear(5,5);19attach('test','input');20attach('test',5,5);21});22});23toRightOf('test');24toRightOf(5,5);25toLeftOf('test');26toLeftOf(5,5);27above('test');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, write, click, closeBrowser, accept, text, inputField } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await write("Taiko", into(inputField({"placeholder":"Search"})));6 await click("Taiko - Google Search");7 await click("Taiko - A Node.js library to automate web applications");8 await click("Get Started");9 await click("Install Taiko");10 await click("npm");11 await click("Install");12 await accept("Taiko is now installed");13 await click("Hello World");14 await click("Run");15 await click("Run");16 await accept("Hello World!");17 await click("Run

Full Screen

Using AI Code Generation

copy

Full Screen

1const { browser, openBrowser, goto, alert, button, accept, closeBrowser } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await button("Run").click();6 await accept();7 } catch (e) {8 console.error(e);9 } finally {10 await closeBrowser();11 }12})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, write, click, closeBrowser, toRightOf, below, toLeftOf, accept, link, dropDown } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await write("taiko", into("Search"));6 await click("Google Search");7 await link("taiko", toRightOf("Google Search")).exists();8 await dropDown({id:"dropdown"}).select("option 1");9 await accept("Are you sure?");10 } catch (error) {11 console.error(error);12 } finally {13 await closeBrowser();14 }15})();16### accept(options)17* `options` (Object):18### dismiss(options)19* `options` (Object):20### getAlertText()21### getAlertMessage()22### getAlertState()23### getAlertType()24### getAlertOptions()25### getAlertDefaultOption()26### getAlertSelectedOption()27### getAlertSelectedOptions()28### getAlertSelectedValue()29### getAlertSelectedValues()30### getAlertSelectedLabel()31### getAlertSelectedLabels()32### getAlertSelectedIndex()33### getAlertSelectedIndexes()34### getAlertSelectedId()35### getAlertSelectedIds()36### getAlertSelectedElement()37### getAlertSelectedElements()

Full Screen

Using AI Code Generation

copy

Full Screen

1const { openBrowser, goto, write, click, closeBrowser, accept, focus, textBox, toRightOf, $, below, image, toLeftOf, link, button, text } = require('taiko');2(async () => {3 try {4 await openBrowser();5 await write("Taiko");6 await click("Google Search");7 await click("Taiko - A Node.js library to automate ...");8 await click("API Reference");9 await click("accept");10 await focus(textBox(toRightOf("accept")));11 await write("accept");12 await click("accept");13 await click("accept");14 await click("

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 taiko 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