Best Python code snippet using assertpy_python
derivations.py
Source:derivations.py
1import grammar2import copy3import json4import re5from paradigm import Paradigm6def deriv_for_paradigm(paradigm):7 """8 Generate a Derivation object for the given paradigm.9 """10 derivLinks = {} # recurs_class -> set of Derivation names11 maxRecursClass = 012 for derivLink in paradigm.derivLinks:13 recursClass, derivLink = get_recurs_class(derivLink)14 # print(recursClass, derivLink['value'])15 if maxRecursClass < recursClass:16 maxRecursClass = recursClass17 pName = fork_deriv(derivLink, paradigm.name)18 if len(pName) > 0:19 try:20 derivLinks[recursClass].add(pName)21 except KeyError:22 derivLinks[recursClass] = {pName}23 handle_recurs_classes(derivLinks, maxRecursClass)24 unifiedDerivContent = []25 for derivNamesSet in derivLinks.values():26 for derivName in derivNamesSet:27 unifiedDerivContent.append({'name': 'paradigm',28 'value': derivName,29 'content': []})30 if len(unifiedDerivContent) <= 0:31 return32 unifiedName = '#deriv#paradigm#' + paradigm.name33 unifiedDeriv = Derivation({'name': 'deriv-type', 'value': unifiedName,34 'content': unifiedDerivContent})35 grammar.Grammar.derivations[unifiedName] = unifiedDeriv36def fork_deriv(derivLink, paradigmName):37 """38 Create a new derivation with customized properties on the basis39 of an existing one.40 Return the name of the resulting derivation.41 """42 derivName = derivLink['value']43 try:44 newDeriv = copy.deepcopy(grammar.Grammar.derivations['#deriv#' +45 derivName])46 except KeyError:47 grammar.Grammar.raise_error('No derivation named ' + derivName)48 return ''49 existingParadigms = newDeriv.find_property('paradigm')50 if len(existingParadigms) <= 0:51 newDeriv.add_property('paradigm', paradigmName)52 if derivLink['content'] is not None:53 for propName in {obj['name'] for obj in derivLink['content']}:54 newDeriv.del_property(propName)55 for obj in derivLink['content']:56 newDeriv.add_property(obj['name'], obj['value'])57 newDerivName = newDeriv.dictDescr['value'] + '#paradigm#' + paradigmName58 newDeriv.dictDescr['value'] = newDerivName59 grammar.Grammar.derivations[newDerivName] = newDeriv60 return newDerivName61def get_recurs_class(derivLink):62 """Find the recurs_class property in the contents.63 Return its value and the dictionary with recurs_value removed."""64 recursClass = 065 if derivLink['content'] is None or len(derivLink['content']) <= 0:66 return 0, derivLink67 newDerivLink = copy.deepcopy(derivLink)68 for iObj in range(len(newDerivLink['content']))[::-1]:69 obj = newDerivLink['content'][iObj]70 if obj['name'] == 'recurs_class':71 try:72 recursClass = int(obj['value'])73 except ValueError:74 grammar.Grammar.raise_error('Incorrect recurs_class value: ' +75 obj['value'])76 newDerivLink['content'].pop(iObj)77 return recursClass, newDerivLink78def handle_recurs_classes(derivLinks, maxRecursClass):79 """80 For every derivation in the dictionary, add links to the derivations81 with recurs_class less than recurs_class of that derivation.82 """83 links = []84 restrictedDerivs = set([re.sub('#paradigm#[^#]+$', '', dv)85 for s in derivLinks.values() for dv in s])86 prevDerivLinks = set()87 for recursClass in range(maxRecursClass + 1):88 try:89 curDerivLinks = derivLinks[recursClass]90 restrictedDerivs -= set([re.sub('#paradigm#[^#]+$', '', dv)91 for dv in prevDerivLinks])92 curRestrictedDerivs = copy.deepcopy(restrictedDerivs)93 prevDerivLinks = curDerivLinks94 except KeyError:95 # print('No recurs_class ' + str(recursClass))96 continue97 linksExtension = []98 for derivName in curDerivLinks:99 try:100 deriv = grammar.Grammar.derivations[derivName]101 except KeyError:102 grammar.Grammar.raise_error('No derivation named ' + derivName)103 continue104 for link in links:105 deriv.add_dict_property(link)106 deriv.restrictedDerivs = curRestrictedDerivs107 if recursClass < maxRecursClass:108 newLink = {'name': 'paradigm', 'value': derivName,109 'content': [copy.deepcopy(p)110 for p in deriv.find_property('paradigm')]}111 for link in links:112 newLink['content'].append(copy.deepcopy(link))113 linksExtension.append(newLink)114 links += linksExtension115def add_restricted(recursCtr, restrictedDerivs):116 recursCtr = recursCtr.copy()117 for rd in restrictedDerivs:118 recursCtr[rd] = grammar.Grammar.RECURS_LIMIT + 1119 return recursCtr120def extend_leaves(data, sourceParadigm, recursCtr=None,121 removeLong=False, depth=0):122 # recursCtr: derivation name -> number of times it has been used123 if recursCtr is None:124 recursCtr = {}125 depth += 1126 data2add = []127 # print(json.dumps(recursCtr, indent=1))128 # print(len(recursCtr), max([0] + recursCtr.values()))129 for iObj in range(len(data))[::-1]:130 obj = data[iObj]131 if obj['name'] != 'paradigm':132 continue133 elif obj['value'].startswith('#deriv#'):134 shortName = re.sub('#paradigm#[^#]+$', '',135 obj['value'], flags=re.U)136 try:137 recursCtr[shortName] += 1138 except KeyError:139 recursCtr[shortName] = 1140 if recursCtr[shortName] > grammar.Grammar.RECURS_LIMIT or \141 depth > grammar.Grammar.DERIV_LIMIT:142 if removeLong:143 data.pop(iObj)144 continue145 try:146 deriv = grammar.Grammar.derivations[obj['value']]147 except KeyError:148 continue149 recursCtrNext = add_restricted(recursCtr, deriv.restrictedDerivs)150 extend_leaves(obj['content'], sourceParadigm,151 recursCtrNext, removeLong, depth)152 else:153 # print obj['value']154 if depth > grammar.Grammar.DERIV_LIMIT or obj['value'] == sourceParadigm:155 continue156 try:157 deriv = grammar.Grammar.derivations['#deriv#paradigm#' +158 obj['value']]159 except KeyError:160 continue161 subsequentDerivs = copy.deepcopy(deriv.find_property('paradigm'))162 # print(json.dumps(subsequentDerivs, indent=1))163 recursCtrNext = add_restricted(recursCtr, deriv.restrictedDerivs)164 extend_leaves(subsequentDerivs, sourceParadigm,165 recursCtrNext, True, depth)166 data2add += subsequentDerivs167 data += data2add168class Derivation:169 """170 An auxiliary class where derivations are represented by dictionaries.171 After priorities are handled, all derivations should be transformed into172 paradigms.173 """174 def __init__(self, dictDescr, errorHandler=None):175 self.dictDescr = copy.deepcopy(dictDescr)176 if self.dictDescr['content'] is None:177 self.dictDescr['content'] = []178 if errorHandler is None:179 self.errorHandler = grammar.Grammar.errorHandler180 else:181 self.errorHandler = errorHandler182 self.restrictedDerivs = set()183 def raise_error(self, message, data=None):184 if self.errorHandler is not None:185 self.errorHandler.raise_error(message, data)186 def content(self):187 return self.dictDescr['content']188 def find_property(self, propName):189 return [el for el in self.content() if el['name'] == propName]190 def add_property(self, name, value):191 self.dictDescr['content'].append({'name': name, 'value': value,192 'content': []})193 def add_dict_property(self, dictProperty):194 self.dictDescr['content'].append(copy.deepcopy(dictProperty))195 def del_property(self, propName):196 for iObj in range(len(self.dictDescr['content']))[::-1]:197 obj = self.dictDescr['content'][iObj]198 if obj['name'] == propName:199 self.dictDescr['content'].pop(iObj)200 def __str__(self):201 return json.dumps(self.dictDescr, ensure_ascii=False, indent=2)202 def build_links(self):203 """Add the links from all subsequent derivations to self."""204 newDerivLinks = []205 for derivLink in self.find_property('paradigm'):206 if (not derivLink['value'].startswith('#deriv#')) or\207 (derivLink['content'] is not None and208 len(derivLink['content']) > 0):209 newDerivLinks.append(derivLink)210 continue211 newDerivLink = copy.deepcopy(derivLink)212 try:213 targetDeriv = grammar.Grammar.derivations[newDerivLink['value']]214 except KeyError:215 self.raise_error('No derivation named ' + newDerivLink['value'])216 continue217 newDerivLink['content'] = \218 copy.deepcopy(targetDeriv.find_property('paradigm'))219 newDerivLinks.append(newDerivLink)220 self.del_property('paradigm')221 for newDerivLink in newDerivLinks:222 self.add_dict_property(newDerivLink)223 def extend_leaves(self):224 """225 For the leaves in the subsequent derivation tree, which are226 real paradigms, add their subsequent derivations, if needed.227 """228 m = re.search('#deriv#paradigm#([^#]+$)', self.dictDescr['value'],229 flags=re.U)230 if m is None:231 return232 paradigmName = m.group(1)233 recursCtr = {}234 for derivName in self.restrictedDerivs:235 recursCtr[derivName] = grammar.Grammar.RECURS_LIMIT + 1236 extend_leaves(self.dictDescr['content'], paradigmName, recursCtr)237 def to_paradigm(self):238 """239 Create a paradigm from self.dictDescr and return it.240 """...
test_levenshtein.py
Source:test_levenshtein.py
1from lib import levenshtein_recurs, levenshtein_recurs_mem2def test_empty_strings() -> None:3 str1, str2 = '', ''4 correct_answer = 05 assert correct_answer == levenshtein_recurs(str1, str2)[0]6 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]7def test_with_one_empty() -> None:8 str1, str2 = '', 'ÐаÑманка'9 correct_answer = len(str2)10 assert correct_answer == levenshtein_recurs(str1, str2)[0]11 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]12 assert correct_answer == levenshtein_recurs(str2, str1)[0]13 assert correct_answer == levenshtein_recurs_mem(str2, str1)[0]14def test_equal_strings() -> None:15 str1, str2 = 'ÐаÑманка', 'ÐаÑманка'16 correct_answer = 017 assert correct_answer == levenshtein_recurs(str1, str2)[0]18 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]19def test_equal_length() -> None:20 str1, str2 = 'ÐаÑманка', 'ÐвÑманкк'21 correct_answer = 222 assert correct_answer == levenshtein_recurs(str1, str2)[0]23 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]24def test_equal_length_with_transpose() -> None:25 str1, str2 = 'ÐаÑманка', 'ÐаÑманак'26 correct_answer = 227 assert correct_answer == levenshtein_recurs(str1, str2)[0]28 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]29def test_different_strings() -> None:30 str1, str2 = 'ÐаÑманка', 'Ðомонка'31 correct_answer = 332 assert correct_answer == levenshtein_recurs(str1, str2)[0]33 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]34def test_full_rewrite() -> None:35 str1, str2 = 'ÐÐТУ', 'аÑмии'36 correct_answer = 537 assert correct_answer == levenshtein_recurs(str1, str2)[0]38 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]39def test_several_transposes() -> None:40 str1, str2 = 'ÐлекÑандÑ', 'ÐелкÑанÑд'41 correct_answer = 442 assert correct_answer == levenshtein_recurs(str1, str2)[0]43 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]44def test_delete() -> None:45 str1, str2 = 'ÐÐТУ', 'ÐÐТ'46 correct_answer = 147 assert correct_answer == levenshtein_recurs(str1, str2)[0]48 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]49def test_add() -> None:50 str1, str2 = 'ÐÐТ', 'ÐÐТУ'51 correct_answer = 152 assert correct_answer == levenshtein_recurs(str1, str2)[0]53 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]54def test_replace() -> None:55 str1, str2 = 'ÐÐТ', 'ÐÐТУ'56 correct_answer = 157 assert correct_answer == levenshtein_recurs(str1, str2)[0]58 assert correct_answer == levenshtein_recurs_mem(str1, str2)[0]59def test_eng() -> None:60 str1, str2 = 'Hello', 'Hi'61 correct_answer = 462 assert correct_answer == levenshtein_recurs(str1, str2)[0]...
urls.py
Source:urls.py
1from django.urls import re_path2from aula.apps.material import views as recurs_views3urlpatterns = [4 re_path(r'^lesMevesReservesDeRecurs/$', recurs_views.reservaRecursList,5 name="gestio__reserva_recurs__list"),6 # wizard per recurs7 re_path(r'^consultaRecursPerRecurs/$', recurs_views.consultaRecursPerRecurs,8 name="gestio__reserva_recurs__consulta"),9 re_path(r'^detallRecursReserves/(?P<year>\d{4})/(?P<month>\d+)/(?P<day>\d+)/(?P<pk>\d+)/$',10 recurs_views.detallRecursReserves,11 name="gestio__reserva_recurs__detallrecursreserves"),12 # # wizard per franja13 re_path(r'^consultaRecursPerFranja/$', recurs_views.consultaRecursPerFranja,14 name="gestio__reserva_recurs__consulta"),15 re_path(r'^detallMassiuFranjaReserves/(?P<year_inici>\d{4})/(?P<year_fi>\d{4})/(?P<month_inici>\d+)/(?P<month_fi>\d+)/(?P<day_inici>\d+)/(?P<day_fi>\d+)/(?P<pk>\d+)/$',16 recurs_views.detallMassiuFranjaReserves,17 name="gestio__reserva_recurs__detallfranjareserves"),18 re_path(r'^detallFranjaReserves/(?P<year>\d{4})/(?P<month>\d+)/(?P<day>\d+)/(?P<pk>\d+)/$',19 recurs_views.detallFranjaReserves,20 name="gestio__reserva_recurs__detallfranjareserves"),21 re_path(r'^consultaMassivaRecurs/$', recurs_views.consultaMassivaRecurs,22 name="gestio__reserva_massiva_recurs__consulta"),23 # wizard last step24 re_path(r'^tramitarReservaRecurs/(?P<pk_recurs>\d+)/(?P<pk_franja>\d+)/(?P<year>\d{4})/(?P<month>\d+)/(?P<day>\d+)/$',25 recurs_views.tramitarReservaRecurs,26 name="gestio__reserva_recurs__tramitarreservarecurs"),27 re_path(r'^tramitarReservaMassivaRecurs/(?P<pk_recurs>\d+)/(?P<pk_franja>\d+)/(?P<year_inici>\d{4})/(?P<year_fi>\d{4})/(?P<month_inici>\d+)/(?P<month_fi>\d+)/(?P<day_inici>\d+)/(?P<day_fi>\d+)/$',28 recurs_views.tramitarReservaMassivaRecurs,29 name="gestio__reserva_massiva_recurs__tramitarreservamassivarecurs"),30 re_path(r'^eliminarReservaRecurs/(?P<pk>\d+)/$',31 recurs_views.eliminarReservaRecurs,32 name="gestio__reserva_recurs__eliminarreservarecurs"),33 re_path(r'^assignaComentaris/',34 recurs_views.assignaComentarisARecurs,35 name="gestio__recurs__assignacomentari"),...
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!!