Best Python code snippet using pytest
conditions.py
Source:conditions.py
...27 for part in self.parts]28 method = getattr(self, method_name, self._propagate)29 return method(part_results, *args)30 def _propagate(self, parts, *args):31 return self.change_parts(parts)32 def simplified(self):33 return self._postorder_visit("_simplified")34 def relaxed(self):35 return self._postorder_visit("_relaxed")36 def untyped(self):37 return self._postorder_visit("_untyped")38 def uniquify_variables(self, type_map, renamings={}):39 # Cannot used _postorder_visit because this requires preorder40 # for quantified effects.41 if not self.parts:42 return self43 else:44 return self.__class__([part.uniquify_variables(type_map, renamings)45 for part in self.parts])46 def to_untyped_strips(self):47 raise ValueError("Not a STRIPS condition: %s" % self.__class__.__name__)48 def instantiate(self, var_mapping, init_facts, fluent_facts, result):49 raise ValueError("Cannot instantiate condition: not normalized")50 def free_variables(self):51 result = set()52 for part in self.parts:53 result |= part.free_variables()54 return result55 def has_disjunction(self):56 for part in self.parts:57 if part.has_disjunction():58 return True59 return False60 def has_existential_part(self):61 for part in self.parts:62 if part.has_existential_part():63 return True64 return False65 def has_universal_part(self):66 for part in self.parts:67 if part.has_universal_part():68 return True69 return False70class ConstantCondition(Condition):71 # Defining __eq__ blocks inheritance of __hash__, so must set it explicitly.72 __hash__ = Condition.__hash__73 parts = ()74 def __init__(self):75 self.hash = hash(self.__class__)76 def change_parts(self, parts):77 return self78 def __eq__(self, other):79 return self.__class__ is other.__class__80class Impossible(Exception):81 pass82class Falsity(ConstantCondition):83 def instantiate(self, var_mapping, init_facts, fluent_facts, result):84 raise Impossible()85 def negate(self):86 return Truth()87class Truth(ConstantCondition):88 def to_untyped_strips(self):89 return []90 def instantiate(self, var_mapping, init_facts, fluent_facts, result):91 pass92 def negate(self):93 return Falsity()94class JunctorCondition(Condition):95 # Defining __eq__ blocks inheritance of __hash__, so must set it explicitly.96 __hash__ = Condition.__hash__97 def __eq__(self, other):98 # Compare hash first for speed reasons.99 return (self.hash == other.hash and100 self.__class__ is other.__class__ and101 self.parts == other.parts)102 def change_parts(self, parts):103 return self.__class__(parts)104class Conjunction(JunctorCondition):105 def _simplified(self, parts):106 result_parts = []107 for part in parts:108 if isinstance(part, Conjunction):109 result_parts += part.parts110 elif isinstance(part, Falsity):111 return Falsity()112 elif not isinstance(part, Truth):113 result_parts.append(part)114 if not result_parts:115 return Truth()116 if len(result_parts) == 1:117 return result_parts[0]118 return Conjunction(result_parts)119 def to_untyped_strips(self):120 result = []121 for part in self.parts:122 result += part.to_untyped_strips()123 return result124 def instantiate(self, var_mapping, init_facts, fluent_facts, result):125 assert not result, "Condition not simplified"126 for part in self.parts:127 part.instantiate(var_mapping, init_facts, fluent_facts, result)128 def negate(self):129 return Disjunction([p.negate() for p in self.parts])130class Disjunction(JunctorCondition):131 def _simplified(self, parts):132 result_parts = []133 for part in parts:134 if isinstance(part, Disjunction):135 result_parts += part.parts136 elif isinstance(part, Truth):137 return Truth()138 elif not isinstance(part, Falsity):139 result_parts.append(part)140 if not result_parts:141 return Falsity()142 if len(result_parts) == 1:143 return result_parts[0]144 return Disjunction(result_parts)145 def negate(self):146 return Conjunction([p.negate() for p in self.parts])147 def has_disjunction(self):148 return True149class QuantifiedCondition(Condition):150 # Defining __eq__ blocks inheritance of __hash__, so must set it explicitly.151 __hash__ = Condition.__hash__152 def __init__(self, parameters, parts):153 self.parameters = tuple(parameters)154 self.parts = tuple(parts)155 self.hash = hash((self.__class__, self.parameters, self.parts))156 def __eq__(self, other):157 # Compare hash first for speed reasons.158 return (self.hash == other.hash and159 self.__class__ is other.__class__ and160 self.parameters == other.parameters and161 self.parts == other.parts)162 def _dump(self, indent=" "):163 arglist = ", ".join(map(str, self.parameters))164 return "%s %s" % (self.__class__.__name__, arglist)165 def _simplified(self, parts):166 if isinstance(parts[0], ConstantCondition):167 return parts[0]168 else:169 return self._propagate(parts)170 def uniquify_variables(self, type_map, renamings={}):171 renamings = dict(renamings) # Create a copy.172 new_parameters = [par.uniquify_name(type_map, renamings)173 for par in self.parameters]174 new_parts = (self.parts[0].uniquify_variables(type_map, renamings),)175 return self.__class__(new_parameters, new_parts)176 def free_variables(self):177 result = Condition.free_variables(self)178 for par in self.parameters:179 result.discard(par.name)180 return result181 def change_parts(self, parts):182 return self.__class__(self.parameters, parts)183class UniversalCondition(QuantifiedCondition):184 def _untyped(self, parts):185 type_literals = [par.get_atom().negate() for par in self.parameters]186 return UniversalCondition(self.parameters,187 [Disjunction(type_literals + parts)])188 def negate(self):189 return ExistentialCondition(self.parameters, [p.negate() for p in self.parts])190 def has_universal_part(self):191 return True192class ExistentialCondition(QuantifiedCondition):193 def _untyped(self, parts):194 type_literals = [par.get_atom() for par in self.parameters]195 return ExistentialCondition(self.parameters,196 [Conjunction(type_literals + parts)])197 def negate(self):198 return UniversalCondition(self.parameters, [p.negate() for p in self.parts])199 def instantiate(self, var_mapping, init_facts, fluent_facts, result):200 assert not result, "Condition not simplified"201 self.parts[0].instantiate(var_mapping, init_facts, fluent_facts, result)202 def has_existential_part(self):203 return True204class Literal(Condition):205 # Defining __eq__ blocks inheritance of __hash__, so must set it explicitly.206 __hash__ = Condition.__hash__207 parts = []208 def __init__(self, predicate, args):209 self.predicate = predicate210 self.args = tuple(args)211 self.hash = hash((self.__class__, self.predicate, self.args))212 def __eq__(self, other):213 # Compare hash first for speed reasons.214 return (self.hash == other.hash and215 self.__class__ is other.__class__ and216 self.predicate == other.predicate and217 self.args == other.args)218 def __ne__(self, other):219 return not self == other220 @property221 def key(self):222 return str(self.predicate), self.args223 def __lt__(self, other):224 return self.key < other.key225 def __le__(self, other):226 return self.key <= other.key227 def __str__(self):228 return "%s %s(%s)" % (self.__class__.__name__, self.predicate,229 ", ".join(map(str, self.args)))230 def __repr__(self):231 return '<%s>' % self232 def _dump(self):233 return str(self)234 def change_parts(self, parts):235 return self236 def uniquify_variables(self, type_map, renamings={}):237 return self.rename_variables(renamings)238 def rename_variables(self, renamings):239 new_args = tuple(renamings.get(arg, arg) for arg in self.args)240 return self.__class__(self.predicate, new_args)241 def replace_argument(self, position, new_arg):242 new_args = list(self.args)243 new_args[position] = new_arg244 return self.__class__(self.predicate, new_args)245 def free_variables(self):246 return set(arg for arg in self.args if arg[0] == "?")247class Atom(Literal):248 negated = False...
pretty_docs.py
Source:pretty_docs.py
1# Copyright 2015 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""A module for converting parsed doc content into markdown pages.16The adjacent `parser` module creates `PageInfo` objects, containing all data17necessary to document an element of the TensorFlow API.18This module contains one public function, which handels the conversion of these19`PageInfo` objects into a markdown string:20 md_page = build_md_page(page_info)21"""22from __future__ import absolute_import23from __future__ import division24from __future__ import print_function25import textwrap26def build_md_page(page_info):27 """Given a PageInfo object, return markdown for the page.28 Args:29 page_info: must be a `parser.FunctionPageInfo`, `parser.ClassPageInfo`, or30 `parser.ModulePageInfo`31 Returns:32 Markdown for the page33 Raises:34 ValueError: if `page_info` is an instance of an unrecognized class35 """36 if page_info.for_function():37 return _build_function_page(page_info)38 if page_info.for_class():39 return _build_class_page(page_info)40 if page_info.for_module():41 return _build_module_page(page_info)42 raise ValueError('Unknown Page Info Type: %s' % type(page_info))43def _build_function_page(page_info):44 """Given a FunctionPageInfo object Return the page as an md string."""45 parts = ['# %s\n\n' % page_info.full_name]46 if len(page_info.aliases) > 1:47 parts.append('### Aliases:\n\n')48 parts.extend('* `%s`\n' % name for name in page_info.aliases)49 parts.append('\n')50 if page_info.signature is not None:51 parts.append(_build_signature(page_info))52 if page_info.defined_in:53 parts.append('\n\n')54 parts.append(str(page_info.defined_in))55 parts.append(page_info.guides)56 parts.append(page_info.doc.docstring)57 parts.append(_build_function_details(page_info.doc.function_details))58 parts.append(_build_compatibility(page_info.doc.compatibility))59 return ''.join(parts)60def _build_class_page(page_info):61 """Given a ClassPageInfo object Return the page as an md string."""62 parts = ['# {page_info.full_name}\n\n'.format(page_info=page_info)]63 parts.append('## Class `%s`\n\n' % page_info.full_name.split('.')[-1])64 if page_info.bases:65 parts.append('Inherits From: ')66 link_template = '[`{short_name}`]({url})'67 parts.append(', '.join(68 link_template.format(**base._asdict()) for base in page_info.bases))69 parts.append('\n\n')70 if len(page_info.aliases) > 1:71 parts.append('### Aliases:\n\n')72 parts.extend('* Class `%s`\n' % name for name in page_info.aliases)73 parts.append('\n')74 if page_info.defined_in is not None:75 parts.append('\n\n')76 parts.append(str(page_info.defined_in))77 parts.append(page_info.guides)78 parts.append(page_info.doc.docstring)79 parts.append(_build_function_details(page_info.doc.function_details))80 parts.append(_build_compatibility(page_info.doc.compatibility))81 parts.append('\n\n')82 if page_info.classes:83 parts.append('## Child Classes\n')84 link_template = ('[`class {class_info.short_name}`]'85 '({class_info.url})\n\n')86 class_links = sorted(87 link_template.format(class_info=class_info)88 for class_info in page_info.classes)89 parts.extend(class_links)90 if page_info.properties:91 parts.append('## Properties\n\n')92 for prop_info in sorted(page_info.properties):93 h3 = '<h3 id="{short_name}"><code>{short_name}</code></h3>\n\n'94 parts.append(h3.format(short_name=prop_info.short_name))95 parts.append(prop_info.doc.docstring)96 parts.append(_build_function_details(prop_info.doc.function_details))97 parts.append(_build_compatibility(prop_info.doc.compatibility))98 parts.append('\n\n')99 parts.append('\n\n')100 if page_info.methods:101 parts.append('## Methods\n\n')102 # Sort the methods list, but make sure constructors come first.103 constructors = ['__init__', '__new__']104 inits = [method for method in page_info.methods105 if method.short_name in constructors]106 others = [method for method in page_info.methods107 if method.short_name not in constructors]108 for method_info in sorted(inits) + sorted(others):109 h3 = ('<h3 id="{short_name}">'110 '<code>{short_name}</code>'111 '</h3>\n\n')112 parts.append(h3.format(**method_info._asdict()))113 if method_info.signature is not None:114 parts.append(_build_signature(method_info, use_full_name=False))115 parts.append(method_info.doc.docstring)116 parts.append(_build_function_details(method_info.doc.function_details))117 parts.append(_build_compatibility(method_info.doc.compatibility))118 parts.append('\n\n')119 parts.append('\n\n')120 if page_info.other_members:121 parts.append('## Class Members\n\n')122 # TODO(markdaoust): Document the value of the members,123 # at least for basic types.124 h3 = '<h3 id="{short_name}"><code>{short_name}</code></h3>\n\n'125 others_member_headings = (h3.format(short_name=info.short_name)126 for info in sorted(page_info.other_members))127 parts.extend(others_member_headings)128 return ''.join(parts)129def _build_module_page(page_info):130 """Given a ClassPageInfo object Return the page as an md string."""131 parts = ['# Module: {full_name}\n\n'.format(full_name=page_info.full_name)]132 if len(page_info.aliases) > 1:133 parts.append('### Aliases:\n\n')134 parts.extend('* Module `%s`\n' % name for name in page_info.aliases)135 parts.append('\n')136 if page_info.defined_in is not None:137 parts.append('\n\n')138 parts.append(str(page_info.defined_in))139 parts.append(page_info.doc.docstring)140 parts.append(_build_compatibility(page_info.doc.compatibility))141 parts.append('\n\n')142 if page_info.modules:143 parts.append('## Modules\n\n')144 template = '[`{short_name}`]({url}) module'145 for item in page_info.modules:146 parts.append(template.format(**item._asdict()))147 if item.doc.brief:148 parts.append(': ' + item.doc.brief)149 parts.append('\n\n')150 if page_info.classes:151 parts.append('## Classes\n\n')152 template = '[`class {short_name}`]({url})'153 for item in page_info.classes:154 parts.append(template.format(**item._asdict()))155 if item.doc.brief:156 parts.append(': ' + item.doc.brief)157 parts.append('\n\n')158 if page_info.functions:159 parts.append('## Functions\n\n')160 template = '[`{short_name}(...)`]({url})'161 for item in page_info.functions:162 parts.append(template.format(**item._asdict()))163 if item.doc.brief:164 parts.append(': ' + item.doc.brief)165 parts.append('\n\n')166 if page_info.other_members:167 # TODO(markdaoust): Document the value of the members,168 # at least for basic types.169 parts.append('## Other Members\n\n')170 for item in page_info.other_members:171 parts.append('`{short_name}`\n\n'.format(**item._asdict()))172 return ''.join(parts)173def _build_signature(obj_info, use_full_name=True):174 """Returns a md code block showing the function signature."""175 # Special case tf.range, since it has an optional first argument176 if obj_info.full_name == 'tf.range':177 return (178 '``` python\n'179 "tf.range(limit, delta=1, dtype=None, name='range')\n"180 "tf.range(start, limit, delta=1, dtype=None, name='range')\n"181 '```\n\n')182 parts = ['``` python']183 parts.extend(['@' + dec for dec in obj_info.decorators])184 signature_template = '{name}({sig})'185 if not obj_info.signature:186 sig = ''187 elif len(obj_info.signature) == 1:188 sig = obj_info.signature[0]189 else:190 sig = ',\n'.join(' %s' % sig_item for sig_item in obj_info.signature)191 sig = '\n'+sig+'\n'192 if use_full_name:193 obj_name = obj_info.full_name194 else:195 obj_name = obj_info.short_name196 parts.append(signature_template.format(name=obj_name, sig=sig))197 parts.append('```\n\n')198 return '\n'.join(parts)199def _build_compatibility(compatibility):200 """Return the compatibility section as an md string."""201 parts = []202 sorted_keys = sorted(compatibility.keys())203 for key in sorted_keys:204 value = compatibility[key]205 # Dedent so that it does not trigger markdown code formatting.206 value = textwrap.dedent(value)207 parts.append('\n\n#### %s Compatibility\n%s\n' % (key.title(), value))208 return ''.join(parts)209def _build_function_details(function_details):210 """Return the function details section as an md string."""211 parts = []212 for detail in function_details:213 sub = []214 sub.append('#### ' + detail.keyword + ':\n\n')215 sub.append(textwrap.dedent(detail.header))216 for key, value in detail.items:217 sub.append('* <b>`%s`</b>: %s' % (key, value))218 parts.append(''.join(sub))...
daily_Parts_issuance_wizard_report.py
Source:daily_Parts_issuance_wizard_report.py
1# See LICENSE file for full copyright and licensing details.2"""Daily Parts issuance Wizard Report."""3from datetime import datetime, timedelta4from odoo import models5from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT6class DailyPartWizard(models.AbstractModel):7 """Daily Part Wizard."""8 _name = 'report.fleet_operations.daily.parts.issuance.wizard.xls'9 _description = 'Daily Parts Insurance'10 def get_heading(self):11 """Report Method."""12 head_title = {'name': '',13 'rev_no': '',14 'doc_no': '',15 }16 head_object = self.env['report.heading']17 head_ids = head_object.search([], order='id')18 if head_ids:19 head_rec = head_ids[0]20 if head_rec:21 head_title['name'] = head_rec.name or ''22 head_title['rev_no'] = head_rec.revision_no or ''23 head_title['doc_no'] = head_rec.document_no or ''24 head_title['image'] = head_rec.image or ''25 return head_title26 def get_work_order_detail(self, date_range):27 """Report Method to Get Work Order Details."""28 work_order_obj = self.env['task.line']29 start = datetime.strptime(date_range.get('date_from'), '%Y-%m-%d')30 end = datetime.strptime(date_range.get('date_to'), '%Y-%m-%d')31 step = timedelta(days=1)32 workorder_detail = []33 while start <= end:34 sdate = str(datetime.strptime(str(start.date()) + ' 00:00:00',35 DEFAULT_SERVER_DATETIME_FORMAT))36 edate = str(datetime.strptime(str(start.date()) + ' 23:59:59',37 DEFAULT_SERVER_DATETIME_FORMAT))38 work_order_ids = work_order_obj.search([('date_issued', '>=',39 sdate), ('date_issued',40 '<=', edate)])41 if work_order_ids:42 parts_data = {}43 parts_value = []44 for parts_line in work_order_ids:45 if parts_line.fleet_service_id and \46 parts_line.fleet_service_id.state == 'done':47 parts_dict = {48 'wo_name': parts_line.fleet_service_id and49 parts_line.fleet_service_id.name or '',50 'vehicle_id': parts_line.fleet_service_id and51 parts_line.fleet_service_id.vehicle_id and52 parts_line.fleet_service_id.vehicle_id.name or '',53 'part_no': parts_line.product_id and54 parts_line.product_id.default_code or '',55 'part_name': parts_line.product_id and56 parts_line.product_id.name or '',57 'vehicle_make': parts_line.vehicle_make_id and58 parts_line.vehicle_make_id.name or '',59 'qty': parts_line.qty or 0.0,60 'uom': parts_line.product_uom and61 parts_line.product_uom.name or '',62 'old_part_return': parts_line.old_part_return and63 'Yes' or 'No',64 'issued_by': parts_line.issued_by and65 parts_line.issued_by.name or '',66 'remarks': parts_line.fleet_service_id and67 parts_line.fleet_service_id.note or ''68 }69 parts_value.append(parts_dict)70 if parts_value:71 parts_value = sorted(parts_value,72 key=lambda k: k['wo_name'])73 parts_data = {74 'date': start.date(),75 'value': parts_value76 }77 workorder_detail.append(parts_data)78 start += step79 return workorder_detail80 def generate_xlsx_report(self, workbook, data, parts_data):81 """Generate xlsx format print report."""82 worksheet = workbook.add_worksheet('daily_parts_issuance_wizard')83 worksheet.set_column(0, 0, 10)84 worksheet.set_column(1, 1, 15)85 worksheet.set_column(2, 2, 20)86 worksheet.set_column(3, 3, 15)87 worksheet.set_column(4, 4, 10)88 worksheet.set_column(5, 5, 12)89 worksheet.set_column(6, 6, 10)90 worksheet.set_column(7, 7, 10)91 worksheet.set_column(8, 8, 15)92 worksheet.set_column(9, 9, 10)93 worksheet.set_column(10, 10, 15)94 worksheet.set_column(11, 11, 10)95 worksheet.set_column(12, 12, 20)96 worksheet.set_column(13, 13, 5)97 worksheet.set_column(14, 14, 5)98 worksheet.set_column(15, 15, 5)99 bold = workbook.add_format({'bold': True,100 'font_name': 'Arial',101 'font_size': '10'})102 tot = workbook.add_format({'border': 2,103 'bold': True,104 'font_name': 'Arial',105 'font_size': '10'})106 border = workbook.add_format({'border': 2,107 'font_name': 'Arial',108 'font_size': '10'})109 merge_format = workbook.add_format({'border': 2, 'align': 'center'})110 format1 = workbook.add_format({'border': 2,111 'bold': True,112 'font_name': 'Arial',113 'font_size': '10'})114 format1.set_bg_color('gray')115 date = workbook.add_format({'num_format': 'dd/mm/yy'})116 worksheet.merge_range('C3:F3', 'Merged Cells', merge_format)117 row = 0118 row += 1119 row += 1120 worksheet.write(row, 2, 'DAILY PARTS ISSUANCE', tot)121 row += 1122 worksheet.write(row, 2, 'Date From:', tot)123 worksheet.write(row, 3, data['form']['date_from'] or '', border)124 worksheet.write(row, 4, 'To:', tot)125 worksheet.write(row, 5, data['form']['date_to'] or '', border)126 row += 2127 worksheet.write(row, 0, 'CMF', bold)128 row = 3129 for objec in self.get_work_order_detail(data['form']):130 row += 3131 worksheet.write(row, 0, 'DATE ISSUED :', bold)132 worksheet.write(row, 1, objec.get('date') or '', date)133 row += 2134 worksheet.write(row, 0, 'NO.', format1)135 worksheet.write(row, 1, 'WO NO.', format1)136 worksheet.write(row, 2, 'VEHICLE ID', format1)137 worksheet.write(row, 3, 'PART NO.', format1)138 worksheet.write(row, 4, 'PART NAME', format1)139 worksheet.write(row, 5, 'VEHICLE MAKE', format1)140 worksheet.write(row, 6, 'USED', format1)141 worksheet.write(row, 7, 'UNIT TYPE', format1)142 worksheet.write(row, 8, 'OLD PART RETURND', format1)143 worksheet.write(row, 9, 'ISSUED BY', format1)144 worksheet.write(row, 10, 'REMARKS', format1)145 line_row = row + 1146 line_col = 0147 counter = 1148 for obj in objec.get('value'):149 worksheet.write(line_row, line_col, counter, border)150 line_col += 1151 worksheet.write(line_row, line_col,152 obj.get('wo_name') or '', border)153 line_col += 1154 worksheet.write(line_row, line_col,155 obj.get('vehicle_id') or '', border)156 line_col += 1157 worksheet.write(line_row, line_col,158 obj.get('part_no') or '', border)159 line_col += 1160 worksheet.write(line_row, line_col,161 obj.get('part_name') or '', border)162 line_col += 1163 worksheet.write(line_row, line_col,164 obj.get('vehicle_make') or '', border)165 line_col += 1166 worksheet.write(line_row, line_col,167 obj.get('qty') or '', border)168 line_col += 1169 worksheet.write(line_row, line_col,170 obj.get('uom') or '', border)171 line_col += 1172 worksheet.write(line_row, line_col,173 obj.get('old_part_return') or '', border)174 line_col += 1175 worksheet.write(line_row, line_col,176 obj.get('issued_by') or '', border)177 line_col += 1178 worksheet.write(line_row, line_col,179 obj.get('remarks') or '', border)180 line_col = 0181 line_row += 1182 counter += 1...
interpolation.py
Source:interpolation.py
1# -*- coding: utf-8 -*-2#3# Copyright (C) 2007 Edgewall Software4# All rights reserved.5#6# This software is licensed as described in the file COPYING, which7# you should have received as part of this distribution. The terms8# are also available at http://genshi.edgewall.org/wiki/License.9#10# This software consists of voluntary contributions made by many11# individuals. For the exact contribution history, see the revision12# history and logs, available at http://genshi.edgewall.org/log/.13import doctest14import sys15import unittest16from genshi.core import TEXT17from genshi.template.base import TemplateSyntaxError, EXPR18from genshi.template.interpolation import interpolate19class InterpolateTestCase(unittest.TestCase):20 def test_interpolate_string(self):21 parts = list(interpolate('bla'))22 self.assertEqual(1, len(parts))23 self.assertEqual(TEXT, parts[0][0])24 self.assertEqual('bla', parts[0][1])25 def test_interpolate_simple(self):26 parts = list(interpolate('${bla}'))27 self.assertEqual(1, len(parts))28 self.assertEqual(EXPR, parts[0][0])29 self.assertEqual('bla', parts[0][1].source)30 def test_interpolate_escaped(self):31 parts = list(interpolate('$${bla}'))32 self.assertEqual(1, len(parts))33 self.assertEqual(TEXT, parts[0][0])34 self.assertEqual('${bla}', parts[0][1])35 def test_interpolate_dobuleescaped(self):36 parts = list(interpolate('$$${bla}'))37 self.assertEqual(2, len(parts))38 self.assertEqual(TEXT, parts[0][0])39 self.assertEqual('$', parts[0][1])40 self.assertEqual(EXPR, parts[1][0])41 self.assertEqual('bla', parts[1][1].source)42 def test_interpolate_short(self):43 parts = list(interpolate('$bla'))44 self.assertEqual(1, len(parts))45 self.assertEqual(EXPR, parts[0][0])46 self.assertEqual('bla', parts[0][1].source)47 def test_interpolate_short_escaped(self):48 parts = list(interpolate('$$bla'))49 self.assertEqual(1, len(parts))50 self.assertEqual(TEXT, parts[0][0])51 self.assertEqual('$bla', parts[0][1])52 def test_interpolate_short_escaped_2(self):53 parts = list(interpolate('my $$bla = 2'))54 self.assertEqual(1, len(parts))55 self.assertEqual(TEXT, parts[0][0])56 self.assertEqual('my $bla = 2', parts[0][1])57 def test_interpolate_short_doubleescaped(self):58 parts = list(interpolate('$$$bla'))59 self.assertEqual(2, len(parts))60 self.assertEqual(TEXT, parts[0][0])61 self.assertEqual('$', parts[0][1])62 self.assertEqual(EXPR, parts[1][0])63 self.assertEqual('bla', parts[1][1].source)64 def test_interpolate_short_starting_with_underscore(self):65 parts = list(interpolate('$_bla'))66 self.assertEqual(1, len(parts))67 self.assertEqual(EXPR, parts[0][0])68 self.assertEqual('_bla', parts[0][1].source)69 def test_interpolate_short_containing_underscore(self):70 parts = list(interpolate('$foo_bar'))71 self.assertEqual(1, len(parts))72 self.assertEqual(EXPR, parts[0][0])73 self.assertEqual('foo_bar', parts[0][1].source)74 def test_interpolate_short_starting_with_dot(self):75 parts = list(interpolate('$.bla'))76 self.assertEqual(1, len(parts))77 self.assertEqual(TEXT, parts[0][0])78 self.assertEqual('$.bla', parts[0][1])79 def test_interpolate_short_containing_dot(self):80 parts = list(interpolate('$foo.bar'))81 self.assertEqual(1, len(parts))82 self.assertEqual(EXPR, parts[0][0])83 self.assertEqual('foo.bar', parts[0][1].source)84 def test_interpolate_short_starting_with_digit(self):85 parts = list(interpolate('$0bla'))86 self.assertEqual(1, len(parts))87 self.assertEqual(TEXT, parts[0][0])88 self.assertEqual('$0bla', parts[0][1])89 def test_interpolate_short_containing_digit(self):90 parts = list(interpolate('$foo0'))91 self.assertEqual(1, len(parts))92 self.assertEqual(EXPR, parts[0][0])93 self.assertEqual('foo0', parts[0][1].source)94 def test_interpolate_short_starting_with_digit(self):95 parts = list(interpolate('$0bla'))96 self.assertEqual(1, len(parts))97 self.assertEqual(TEXT, parts[0][0])98 self.assertEqual('$0bla', parts[0][1])99 def test_interpolate_short_containing_digit(self):100 parts = list(interpolate('$foo0'))101 self.assertEqual(1, len(parts))102 self.assertEqual(EXPR, parts[0][0])103 self.assertEqual('foo0', parts[0][1].source)104 def test_interpolate_full_nested_brackets(self):105 parts = list(interpolate('${{1:2}}'))106 self.assertEqual(1, len(parts))107 self.assertEqual(EXPR, parts[0][0])108 self.assertEqual('{1:2}', parts[0][1].source)109 def test_interpolate_full_mismatched_brackets(self):110 try:111 list(interpolate('${{1:2}'))112 except TemplateSyntaxError, e:113 pass114 else:115 self.fail('Expected TemplateSyntaxError')116 def test_interpolate_quoted_brackets_1(self):117 parts = list(interpolate('${"}"}'))118 self.assertEqual(1, len(parts))119 self.assertEqual(EXPR, parts[0][0])120 self.assertEqual('"}"', parts[0][1].source)121 def test_interpolate_quoted_brackets_2(self):122 parts = list(interpolate("${'}'}"))123 self.assertEqual(1, len(parts))124 self.assertEqual(EXPR, parts[0][0])125 self.assertEqual("'}'", parts[0][1].source)126 def test_interpolate_quoted_brackets_3(self):127 parts = list(interpolate("${'''}'''}"))128 self.assertEqual(1, len(parts))129 self.assertEqual(EXPR, parts[0][0])130 self.assertEqual("'''}'''", parts[0][1].source)131 def test_interpolate_quoted_brackets_4(self):132 parts = list(interpolate("${'''}\"\"\"'''}"))133 self.assertEqual(1, len(parts))134 self.assertEqual(EXPR, parts[0][0])135 self.assertEqual("'''}\"\"\"'''", parts[0][1].source)136 def test_interpolate_quoted_brackets_5(self):137 parts = list(interpolate(r"${'\'}'}"))138 self.assertEqual(1, len(parts))139 self.assertEqual(EXPR, parts[0][0])140 self.assertEqual(r"'\'}'", parts[0][1].source)141 def test_interpolate_mixed1(self):142 parts = list(interpolate('$foo bar $baz'))143 self.assertEqual(3, len(parts))144 self.assertEqual(EXPR, parts[0][0])145 self.assertEqual('foo', parts[0][1].source)146 self.assertEqual(TEXT, parts[1][0])147 self.assertEqual(' bar ', parts[1][1])148 self.assertEqual(EXPR, parts[2][0])149 self.assertEqual('baz', parts[2][1].source)150 def test_interpolate_mixed2(self):151 parts = list(interpolate('foo $bar baz'))152 self.assertEqual(3, len(parts))153 self.assertEqual(TEXT, parts[0][0])154 self.assertEqual('foo ', parts[0][1])155 self.assertEqual(EXPR, parts[1][0])156 self.assertEqual('bar', parts[1][1].source)157 self.assertEqual(TEXT, parts[2][0])158 self.assertEqual(' baz', parts[2][1])159def suite():160 suite = unittest.TestSuite()161 suite.addTest(doctest.DocTestSuite(interpolate.__module__))162 suite.addTest(unittest.makeSuite(InterpolateTestCase, 'test'))163 return suite164if __name__ == '__main__':...
Looking for an in-depth tutorial around pytest? LambdaTest covers the detailed pytest tutorial that has everything related to the pytest, from setting up the pytest framework to automation testing. Delve deeper into pytest testing by exploring advanced use cases like parallel testing, pytest fixtures, parameterization, executing multiple test cases from a single file, and more.
Skim our below pytest tutorial playlist to get started with automation testing using the pytest framework.
https://www.youtube.com/playlist?list=PLZMWkkQEwOPlcGgDmHl8KkXKeLF83XlrP
Get 100 minutes of automation test minutes FREE!!