Best Python code snippet using localstack_python
negotiator.py
Source:negotiator.py  
...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            ...as_string.py
Source:as_string.py  
...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)...cgen.py
Source:cgen.py  
...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):...test_acceptparse.py
Source:test_acceptparse.py  
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')...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!!
