Best Python code snippet using localstack_python
fpagui.py
Source:fpagui.py
1import os2import sys3from collections import namedtuple4from PySide6 import QtCore, QtGui, QtPrintSupport, QtWidgets5from PySide6.QtCore import Qt6import fpagui_rc7from calculate2html import html_final8from fpagui_ui import Ui_MainWindow9from ini_handle import APP_PATH, INI10from isozygio_parse import parse_filtered11from moving_codes_e2 import E2CODES12from parse_template import ParserTemplate13IsoSelector = namedtuple('IsoSelector', 'row start end size')14class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):15 def __init__(self):16 super().__init__()17 self.setupUi(self)18 self.setAcceptDrops(True)19 self.isozygio.setFont(INI.value('isozygio_font'))20 self.parse_template = ParserTemplate()21 self.open_template_file(22 INI.value('parse_template_file', defaultValue=''))23 self.isozygio_file_name = ''24 self.matched = {}25 self.res = {}26 self.pistotiko = 027 self.is_template_editing = False28 # self.load_parse_positions_from_ini()29 self.create_connections()30 def create_connections(self):31 self.actionopenfpa.triggered.connect(self.open)32 self.btn_grammatoseira.clicked.connect(self.select_font)33 self.isozygio.selectionChanged.connect(34 self.handleIsozygioSelectionChanged)35 self.isozygio.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)36 self.isozygio.customContextMenuRequested.connect(37 self.on_isozygio_context)38 self.btn_parse.clicked.connect(self.handle_parse)39 self.btnmatch.clicked.connect(self.handle_match)40 self.btnprint.clicked.connect(self.printpreviewDialog)41 self.btn_template_toggle.clicked.connect(self.template_toggle)42 self.btn_open_template.clicked.connect(self.select_template_file)43 self.btn_edit_template.clicked.connect(self.edit_template)44 self.btn_recalculate.clicked.connect(self.recalculate)45 def edit_template(self):46 if self.is_template_editing:47 self.fr3_iso_footer.setStyleSheet("")48 self.le_protypo_name.setReadOnly(True)49 self.le_fpa.setReadOnly(True)50 self.le_fpa_ektos.setReadOnly(True)51 self.le_omades.setReadOnly(True)52 self.le_omades_negative.setReadOnly(True)53 self.parse_template.set_name(self.le_protypo_name.text().strip())54 self.parse_template.set_fpa(self.le_fpa.text().strip())55 self.parse_template.set_fpa_exception(56 self.le_fpa_ektos.text().strip())57 self.parse_template.set_omades(self.le_omades.text().strip())58 self.parse_template.set_omades_negative(59 self.le_omades_negative.text().strip())60 if self.parse_template.is_saved2disk == False:61 spath = os.path.join(62 APP_PATH, f'{self.parse_template.name}.tml')63 self.parse_template.save2file(spath)64 self.lbl_template_name.setText(self.parse_template.name)65 INI.setValue('parse_template_file', spath)66 self.btn_edit_template.setText('ÎÏεξεÏγαÏία')67 self.is_template_editing = False68 return69 self.fr3_iso_footer.setStyleSheet(70 "QLineEdit{background-color: rgb(255, 222, 222);}")71 self.le_protypo_name.setReadOnly(False)72 self.le_fpa.setReadOnly(False)73 self.le_fpa_ektos.setReadOnly(False)74 self.le_omades.setReadOnly(False)75 self.le_omades_negative.setReadOnly(False)76 self.btn_edit_template.setText('ÎÏοθήκεÏ
Ïη')77 self.is_template_editing = True78 def template_toggle(self):79 if self.fr3_iso_footer.maximumHeight() == 0:80 self.fr3_iso_footer.setMaximumHeight(200)81 self.fr3_iso_footer.setMinimumHeight(200)82 self.btn_template_toggle.setIcon(QtGui.QIcon(83 ':/icons/icons/angle-down-solid.svg'))84 else:85 self.fr3_iso_footer.setMaximumHeight(0)86 self.fr3_iso_footer.setMinimumHeight(0)87 self.btn_template_toggle.setIcon(QtGui.QIcon(88 ':/icons/icons/angle-up-solid.svg'))89 def select_font(self):90 opval = QtWidgets.QFontDialog.MonospacedFonts91 options = QtWidgets.QFontDialog.FontDialogOptions(opval)92 ok, font = QtWidgets.QFontDialog.getFont(93 self.isozygio.font(), self, 'ÎÏιλογή γÏμμαÏοÏειÏάÏ', options)94 if ok:95 self.isozygio.setFont(font)96 INI.setValue('isozygio_font', font)97 def handle_parse(self):98 if not self.isozygio.toPlainText():99 QtWidgets.QMessageBox.critical(100 self,101 "Error",102 "Please open isozygio ..."103 )104 return105 if self.parse_template.is_saved2disk == False:106 QtWidgets.QMessageBox.critical(107 self,108 "Το ÏÏÏÏÏ
Ïο ÏάÏÏÏÎ·Ï ÎÏει αλλάξει",109 "ÎÏοθηκεÏÏÏε ÏÏÏÏα ÏÎ¹Ï Î±Î»Î»Î±Î³ÎÏ ÏοÏ
Îγιναν ÏÏο ÏÏÏÏÏ
Ïο."110 )111 return112 self.res = parse_filtered(113 self.isozygio.toPlainText(), self.parse_template)114 accounts = [f'{i.acc} - {i.per}' for i in self.res['lines']]115 self.accounts.setColumnCount(2)116 self.accounts.setRowCount(len(accounts))117 self.accounts.setHorizontalHeaderLabels(['ÎογαÏιαÏμÏÏ', 'ÎÏδικÏÏ'])118 self.accounts.setColumnWidth(0, 400)119 self.accounts.horizontalHeader().setStretchLastSection(True)120 self.matched = self.load_account_e2_matching()121 e2codes_reverse = {val: key for key, val in E2CODES.items()}122 for i, acc in enumerate(accounts):123 item = QtWidgets.QTableWidgetItem(acc)124 item.setFlags(QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsEnabled)125 self.accounts.setItem(i, 0, item)126 combo = QtWidgets.QComboBox()127 combo.wheelEvent = lambda event: None128 combo.addItems(E2CODES)129 acclean, *_ = acc.split('-')130 dcode = self.matched.get(acclean.strip(), '-')131 combo.setCurrentText(e2codes_reverse[dcode])132 self.accounts.setCellWidget(i, 1, combo)133 self.accounts.resizeRowsToContents()134 self.accounts.resizeColumnsToContents()135 self.tabWidget.setCurrentIndex(1)136 self.btnmatch.setEnabled(True)137 self.handle_match()138 def set_pistotiko(self):139 self.tabWidget.setCurrentIndex(2)140 # self.fpa.setHtml('')141 pistotiko, ok = QtWidgets.QInputDialog.getDouble(142 self,143 "ΠιÏÏÏÏÎ¹ÎºÏ Î¥ÏÏλοιÏο",144 "ΠοÏÏ:",145 self.pistotiko,146 0,147 10000000,148 2149 )150 if ok:151 self.pistotiko = pistotiko152 def recalculate(self):153 self.set_pistotiko()154 self.handle_match()155 def handle_match(self):156 row_number = self.accounts.rowCount()157 not_matched = []158 for i in range(row_number):159 account_with_perigrafi = self.accounts.item(i, 0).text()160 acc, *_ = account_with_perigrafi.split('-')161 e2code = E2CODES[self.accounts.cellWidget(i, 1).currentText()]162 if e2code == '-':163 not_matched.append(account_with_perigrafi)164 else:165 self.matched[acc.strip()] = e2code166 if not_matched:167 not_matched_str = '\n'.join(not_matched)168 QtWidgets.QMessageBox.critical(169 self,170 "Îεν ÎÏει γίνει ανÏιÏÏοίÏιÏη κÏδικÏν λογιÏÏικήÏ",171 ("Îι ÏαÏακάÏÏ Î»Î¿Î³Î±ÏιαÏμοί δεν ÎÏοÏ
ν ανÏιÏÏοίÏιÏη με κÏδικοÏÏ Î¦Î Î\n"172 f"{not_matched_str}"173 )174 )175 return176 if not self.save_account_e2_matching():177 QtWidgets.QMessageBox.critical(178 self,179 "ÎάθοÏ",180 "Îεν Îγινε αÏοθήκεÏ
Ïη ÏοÏ
αÏÏείοÏ
ανÏιÏÏοίÏιÏηÏ"181 )182 return183 self.tabWidget.setCurrentIndex(2)184 fpa_final = {185 'epon': self.res['name'],186 'apo': self.res['apo'],187 'eos': self.res['eos'],188 'D401': self.pistotiko,189 'D5400': self.res['D5400'],190 }191 for line in self.res['lines']:192 key = self.matched[line.acc]193 fpa_final[key] = round(fpa_final.get(key, 0) + line.normal_ypo, 2)194 self.fpa.setHtml(html_final(fpa_final))195 self.btnprint.setEnabled(True)196 def load_account_e2_matching(self):197 dict1 = {}198 if os.path.exists(self.res['gname']):199 with open(self.res['gname'], encoding='utf8') as fil:200 for line in fil.readlines():201 acc, e2code = line.split()202 dict1[acc] = e2code203 return dict1204 QtWidgets.QMessageBox.critical(205 self, 'Î ÏοÏοÏή', f"ΠεÏαιÏεία {self.res['name']} δεν είναι ÏαÏαμεÏÏοÏοιημÎνη")206 return dict1207 def save_account_e2_matching(self):208 sort_vals = [f"{k} {self.matched[k]}" for k in sorted(self.matched)]209 try:210 with open(self.res['gname'], 'w', encoding='utf8') as fil:211 fil.write('\n'.join(sort_vals))212 return True213 except Exception:214 return False215 def on_isozygio_context(self, point):216 setcompany = QtGui.QAction(217 'ÎÏÏνÏ
μία',218 self,219 statusTip='ÎÏαμμή και θÎÏη εÏÏνÏ
μίαÏ',220 triggered=self.set_company221 )222 setapo = QtGui.QAction(223 'ÎÏÏ',224 self,225 statusTip='ΦÏαμμή και θÎÏη ÏεÏιÏδοÏ
αÏÏ',226 triggered=self.set_apo227 )228 seteos = QtGui.QAction(229 'ÎÏÏ',230 self,231 statusTip='ÎÏαμμή και θÎÏη ÏεÏιÏδοÏ
ÎÏÏ',232 triggered=self.set_eos233 )234 setaccount = QtGui.QAction(235 'ÎογαÏιαÏμÏÏ',236 self,237 statusTip='ÎÎÏη λογαÏιαÏμοÏ',238 triggered=self.set_account239 )240 setper = QtGui.QAction(241 'ΠεÏιγÏαÏή',242 self,243 statusTip='ÎÎÏη ÏεÏιγÏαÏÎ®Ï Î»Î¿Î³Î±ÏιαÏμοÏ',244 triggered=self.set_per245 )246 setdebit = QtGui.QAction(247 'ΧÏÎÏÏη',248 self,249 statusTip='ÎÎÏη ÏÏÎÏÏηÏ',250 triggered=self.set_debit251 )252 setcredit = QtGui.QAction(253 'ΠίÏÏÏÏη',254 self,255 statusTip='ÎÎÏη ÏίÏÏÏÏηÏ',256 triggered=self.set_credit257 )258 menu = QtWidgets.QMenu("Menu", self)259 menu.addAction(setcompany)260 menu.addAction(setapo)261 menu.addAction(seteos)262 menu.addAction(setaccount)263 menu.addAction(setper)264 menu.addAction(setdebit)265 menu.addAction(setcredit)266 menu.exec(self.isozygio.mapToGlobal(point))267 def set_company(self):268 data = self.handleIsozygioSelectionChanged()269 self.codata = (data.row, data.start, data.end)270 self.parse_template.set_pname(data.row, data.start, data.end)271 self.le_eponymia.setText(self.parse_template.pname_txt)272 def set_apo(self):273 data = self.handleIsozygioSelectionChanged()274 self.apo = (data.row, data.start, data.end)275 self.parse_template.set_papo(data.row, data.start, data.end)276 self.le_apo.setText(self.parse_template.papo_txt)277 def set_eos(self):278 data = self.handleIsozygioSelectionChanged()279 self.eos = (data.row, data.start, data.end)280 self.parse_template.set_peos(data.row, data.start, data.end)281 self.le_eos.setText(self.parse_template.peos_txt)282 def set_account(self):283 data = self.handleIsozygioSelectionChanged()284 self.account = (data.start, data.end)285 self.parse_template.set_pacc(data.start, data.end)286 self.le_account.setText(self.parse_template.pacc_txt)287 def set_per(self):288 data = self.handleIsozygioSelectionChanged()289 self.per = (data.start, data.end)290 self.parse_template.set_pper(data.start, data.end)291 self.le_per.setText(self.parse_template.pper_txt)292 def set_debit(self):293 data = self.handleIsozygioSelectionChanged()294 self.debit = (data.start, data.end)295 self.parse_template.set_pxre(data.start, data.end)296 self.le_debit.setText(self.parse_template.pxre_txt)297 def set_credit(self):298 data = self.handleIsozygioSelectionChanged()299 self.credit = (data.start, data.end)300 self.parse_template.set_ppis(data.start, data.end)301 self.le_credit.setText(self.parse_template.ppis_txt)302 def select_template_file(self):303 inif = INI.value('parse_template_file', defaultValue='')304 file_name, _ = QtWidgets.QFileDialog.getOpenFileName(305 self, 'ÎÏιλογή ÏÏοÏÏÏοÏ
', inif, "*.tml")306 if file_name:307 self.open_template_file(file_name)308 def open_template_file(self, file_name: str):309 self.parse_template = ParserTemplate().load_from_file(file_name)310 INI.setValue('parse_template_file', file_name)311 self.lbl_template_name.setText(self.parse_template.name)312 self.le_protypo_name.setText(self.parse_template.name)313 self.le_fpa.setText(self.parse_template.fpa)314 self.le_fpa_ektos.setText(self.parse_template.fpa_exception)315 self.le_omades.setText(self.parse_template.omades)316 self.le_omades_negative.setText(self.parse_template.omades_negative)317 self.le_eponymia.setText(self.parse_template.pname_txt)318 self.le_apo.setText(self.parse_template.papo_txt)319 self.le_eos.setText(self.parse_template.peos_txt)320 self.le_account.setText(self.parse_template.pacc_txt)321 self.le_per.setText(self.parse_template.pper_txt)322 self.le_debit.setText(self.parse_template.pxre_txt)323 self.le_credit.setText(self.parse_template.ppis_txt)324 def open(self):325 # fnam, _ = qw.QFileDialog.getOpenFileName(self, "Open", self.fnam, "")326 inif = INI.value('isozygio_file', defaultValue='')327 file_name, _ = QtWidgets.QFileDialog.getOpenFileName(328 self, 'Open', inif, "*.txt")329 if file_name:330 self.open_isozygio_file(file_name)331 self.handle_parse()332 def open_isozygio_file(self, file_name):333 encoding_from_ini = INI.value('encoding', defaultValue='WINDOWS-1253')334 with open(file_name, encoding=encoding_from_ini) as fil:335 self.isozygio.setPlainText(fil.read())336 INI.setValue('isozygio_file', file_name)337 self.fpa.setHtml('')338 self.accounts.setRowCount(0)339 self.accounts.setColumnCount(0)340 self.tabWidget.setCurrentIndex(0)341 self.isozygio_file_name = file_name342 self.btn_parse.setEnabled(True)343 self.btnprint.setEnabled(False)344 self.btnmatch.setEnabled(False)345 def handleIsozygioSelectionChanged(self) -> IsoSelector:346 cursor = self.isozygio.textCursor()347 row = cursor.blockNumber()348 size = cursor.selectionEnd() - cursor.selectionStart()349 if cursor.position() == cursor.selectionStart():350 start = cursor.columnNumber()351 end = start + size352 # print(row, start, end, size)353 return IsoSelector(row, start, end, size)354 start = cursor.columnNumber() - size355 end = cursor.columnNumber()356 # print(row, start, end, size)357 return IsoSelector(row, start, end, size)358 def dragEnterEvent(self, event):359 if event.mimeData().hasText():360 event.accept()361 else:362 event.ignore()363 def dropEvent(self, event):364 dropped_txt = event.mimeData().text().replace('file:///', '')365 if not dropped_txt.lower().endswith('.txt'):366 QtWidgets.QMessageBox.critical(367 self,368 "ÎάθοÏ",369 "ΠαÏÎ±ÎºÎ±Î»Ï Î´ÏÏÏε ÏοÏ
λάÏιÏÏον Îνα αÏÏείο κειμÎνοÏ
")370 if os.path.exists(dropped_txt):371 self.open_isozygio_file(dropped_txt)372 self.handle_parse()373 def printpreviewDialog(self):374 if self.isozygio_file_name == '':375 return376 fname = '.'.join(self.isozygio_file_name.split('.')[:-1])377 pdfname = f'{fname}.pdf'378 printer = QtPrintSupport.QPrinter(379 QtPrintSupport.QPrinter.HighResolution)380 printer.setPageSize(QtGui.QPageSize.A3)381 printer.setColorMode(QtPrintSupport.QPrinter.Color)382 printer.setOutputFormat(QtPrintSupport.QPrinter.PdfFormat)383 fileName, filtr = QtWidgets.QFileDialog.getSaveFileName(self,384 "ÎÏοθήκεÏ
Ïη",385 pdfname,386 "PDF Files (*.pdf)")387 if fileName:388 printer.setOutputFileName(fileName)...
test_templating.py
Source:test_templating.py
...17 },18}19class TestResolve(unittest.TestCase):20 def test_resolve(self):21 template = parse_template("{.refURIs => .}")22 actual = resolve(template, data_0, data_index)23 expected = [data_1, data_2, data_3, data_4, data_5]24 self.assertEqual(actual, expected)25 def test_resolve_double_object_path(self):26 template = parse_template("{.refURIs => .links.objURIs => .}")27 actual = resolve(template, data_0, data_index)28 expected = [data_1, data_2, data_3, data_4, data_6]29 self.assertEqual(actual, expected)30 def test_resolve_field_join(self):31 template = parse_template("{.refURIs => .a}")32 actual = resolve(template, data_0, data_index)33 expected = ["a", "b", "b"]34 self.assertEqual(actual, expected)35 def test_resolve_self(self):36 template = parse_template("{.}")37 actual = resolve(template, data_0, data_index)38 expected = data_039 self.assertEqual(actual, expected)40 def test_resolve_field(self):41 template = parse_template("{.foo}")42 actual = resolve(template, data_0, data_index)43 expected = [1, 2, 3]44 self.assertEqual(actual, expected)45 def test_resolve4(self):46 template = parse_template("{.genus + .species+.baz}")47 actual = resolve(template, data_0, data_index)48 expected = ["Zea mays"]49 self.assertEqual(actual, expected)50 def test_resolve5(self):51 template = parse_template("{.genus + .species+.baz}")52 actual = resolve(template, data_1, data_index)53 expected = ["Zea mays"]54 self.assertEqual(actual, expected)55 def test_resolve6(self):56 template = parse_template("{.refURIs => .g.genus + .g.species + .baz}")57 actual = resolve(template, data_0, data_index)58 expected = ['Populus', 'Triticum aestivum']59 self.assertEqual(actual, expected)60 def test_resolve7(self):61 template = parse_template("{.links.objURIs => .g.genus + .g.species + .g.subtaxa}")62 actual = resolve(template, data_5, data_index)63 expected = ['Populus', 'Triticum aestivum', 'Zea mays subsp. mexicana']64 self.assertEqual(actual, expected)65 def test_resolve8(self):66 template = parse_template("The species is {.genus + .species+.baz}")67 actual = resolve(template, data_0, data_index)68 expected = "The species is Zea mays"69 self.assertEqual(actual, expected)70 def test_resolve9(self):71 template = parse_template("{.foo}{.genus + .species+.baz}")72 actual = resolve(template, data_0, data_index)73 expected = "123Zea mays"74 self.assertEqual(actual, expected)75 def test_resolve10(self):76 template = parse_template("foo")77 actual = resolve(template, data_0, data_index)78 expected = "foo"79 self.assertEqual(actual, expected)80 def test_resolve_list1(self):81 template = parse_template(["foo", "bar"])82 actual = resolve(template, data_0, data_index)83 expected = template84 self.assertEqual(actual, expected)85 def test_resolve_list2(self):86 template = parse_template(["{.foo}", "bar"])87 actual = resolve(template, data_0, data_index)88 expected = [[1, 2, 3], "bar"]89 self.assertEqual(actual, expected)90 def test_resolve_join0(self):91 template = parse_template({"{join}": ["foo"]})92 actual = resolve(template, None, None)93 expected = "foo"94 self.assertEqual(actual, expected)95 def test_resolve_join1(self):96 template = parse_template({"{join}": ["foo", "bar"]})97 actual = resolve(template, data_0, data_index)98 expected = "foobar"99 self.assertEqual(actual, expected)100 def test_resolve_join2(self):101 template = parse_template({"{join}": ["foo", "{.foo}"]})102 actual = resolve(template, data_0, data_index)103 expected = "foo123"104 self.assertEqual(actual, expected)105 def test_resolve_join3(self):106 template = parse_template({"{join}": ["foo", "{.foo}", ["foo", "{.foo}"]]})107 actual = resolve(template, data_0, data_index)108 expected = "foo123foo123"109 self.assertEqual(actual, expected)110 def test_resolve_if1(self):# this test is supicious, it passes whatever the value of "foo" in `"{if}": "foo"` maybe because "foo" is truthy111 template = parse_template({"{if}": "foo", "{then}": "then"})112 actual = resolve(template, data_0, data_index)113 expected = "then"114 self.assertEqual(actual, expected)115 def test_resolve_if2(self):116 template = parse_template({"{if}": "{.nonExistingField}", "{then}": "then"})117 actual = resolve(template, data_0, data_index)118 expected = None119 self.assertEqual(actual, expected)120 def test_resolve_if3(self):121 template = parse_template({"{if}": "{.foo}", "{then}": "bar"})122 actual = resolve(template, data_0, data_index)123 expected = "bar"124 self.assertEqual(actual, expected)125 def test_resolve_if4(self):126 template = parse_template({"{if}": "{.nonExistingField}", "{then}": "bar", "{else}": "else"})127 actual = resolve(template, data_0, data_index)128 expected = "else"129 self.assertEqual(actual, expected)130 def test_resolve_if5(self):131 template = parse_template({"{if}": "{.falseField}", "{then}": "bar", "{else}": "else"})132 actual = resolve(template, data_0, data_index)133 expected = "else"134 self.assertEqual(actual, expected)135 def test_resolve_if6(self):136 template = parse_template({"{if}": "{.studyTypeName}", "{then}": "{.studyTypeName}"})137 actual = resolve(template, data_0, data_index)138 expected = "gnomic"139 self.assertEqual(actual, expected)140 def test_resolve_if6_ko(self):141 template = parse_template({"{if}": "{.studyTypeName}", "{then}": "{.studyTypeName}"})142 actual = resolve(template, data_0, data_index)143 expected = "gnomicus"144 self.assertNotEqual(actual, expected)145 def test_resolve_if7(self):146 template = parse_template({"{if}": {"{equals}":["{.source}", "URGI"]}, "{then}": "gotcha", "{else}": "{.source}"})147 actual = resolve(template, data_1, data_index)148 expected = "URGI"149 self.assertEqual(actual, expected)150 def test_resolve_replace_with(self):151 template = parse_template({152 "{replace}": {153 "possible_terms": ["geno", "genotyping study", "Gnomic", "genotyping"]154 },155 "{with}": {156 "replaced_by": "Genotyping Study"157 }158 })159 actual = resolve(template, data_0, data_index)160 expected = "Genotyping Study"161 self.assertEqual(actual, expected)162 def test_resolve_dict1(self):163 template = parse_template({"a": "a"})164 actual = resolve(template, data_0, data_index)165 expected = template166 self.assertEqual(actual, expected)167 def test_resolve_dict2(self):168 template = parse_template({"a": "a", "b": "{.foo}"})169 actual = resolve(template, data_0, data_index)170 expected = {"a": "a", "b": [1, 2, 3]}171 self.assertEqual(actual, expected)172 def test_resolve_flatten1(self):173 template = parse_template({"{flatten_distinct}": ["foo", "foo", "bar"]})174 actual = resolve(template, data_0, data_index)175 expected = ["foo", "bar"]176 self.assertEqual(actual, expected)177 def test_resolve_flatten2(self):178 template = parse_template({"{flatten_distinct}": ["foo", "bar", ["baz", ["fizz", "foo", "buzz"], "bar"]]})179 actual = resolve(template, data_0, data_index)180 expected = ["foo", "bar", "baz", "fizz", "buzz"]181 self.assertEqual(actual, expected)182 def test_resolve_or1(self):183 template = parse_template({"{or}": ["foo", "bar", "baz"]})184 actual = resolve(template, data_0, data_index)185 expected = "foo"186 self.assertEqual(actual, expected)187 def test_resolve_or2(self):188 template = parse_template({"{or}": ["{.falseField}", "{.nonExistingField}", "baz"]})189 actual = resolve(template, data_0, data_index)190 expected = "baz"191 self.assertEqual(actual, expected)192 def test_resolve_non_existing_field_in_join_without_none_template(self):193 template = parse_template({"{join}": ["The species is ", "{.nonExistingField}"], "{accept_none}": False})194 actual = resolve(template, data_0, data_index)195 expected = None196 self.assertEqual(actual, expected)197 def test_resolve_non_existing_field_in_string_template(self):198 template = parse_template("The species is {.nonExistingField}")199 actual = resolve(template, data_0, data_index)200 expected = None201 self.assertEqual(actual, expected)202 def test_resolve_join_with_separator(self):203 template = parse_template({"{join}": ["foo", "{.foo}"], "{separator}": ", "})204 actual = resolve(template, data_0, data_index)205 expected = "foo, 1, 2, 3"206 self.assertEqual(actual, expected)207 def test_resolve_capitalize(self):208 template = parse_template({"{list}": ["foo", "foo", "bar"], "{transform}": ["capitalize"]})209 actual = resolve(template, data_0, data_index)210 expected = ["Foo", "Foo", "Bar"]211 self.assertEqual(actual, expected)212 def test_resolve_capitalize2(self):213 template = parse_template({"{list}": ["foo", ["foo", "foo", "bar"], "bar"], "{transform}": ["capitalize"]})214 actual = resolve(template, data_0, data_index)215 expected = ["Foo", ["Foo", "Foo", "Bar"], "Bar"]216 self.assertEqual(actual, expected)217 def test_resolve_flatten_capitalize(self):218 template = parse_template(219 {"{list}": ["foo", ["foo", "foo", "bar"], "bar"], "{transform}": ["capitalize", "flatten"]})220 actual = resolve(template, data_0, data_index)221 expected = ["Foo", "Foo", "Foo", "Bar", "Bar"]222 self.assertEqual(actual, expected)223 def test_resolve_map_empty(self):224 template = parse_template({225 "studies": {226 "{map}": "{.nonExistingField}", "{to}": {"id": "{.}"}227 },228 "foo": "bar"229 })230 actual = resolve(template, data_0, data_index)231 expected = {"foo": "bar"}232 self.assertEqual(actual, expected)233 def test_resolve_map(self):234 template = parse_template({235 "studies": {236 "{map}": "{.refURIs}", "{to}": {"id": "{.}"}237 }238 })239 actual = resolve(template, data_0, data_index)240 expected = {241 'studies': [242 {'id': 1},243 {'id': 2},244 {'id': 3},245 {'id': '4'},246 {'id': 5}247 ]248 }249 self.assertEqual(actual, expected)250 def test_resolve_merge_value(self):251 template = parse_template({252 "{merge}": {253 "foo": "bar",254 "baz": "fizz"255 },256 "{with}": {257 "foo": "fuzz"258 }259 })260 actual = resolve(template, None, None)261 expected = {262 "foo": "fuzz",263 "baz": "fizz"264 }265 self.assertEqual(actual, expected)266 def test_resolve_merge_resolved(self):267 template = parse_template({268 "{merge}": {269 "foo": "{.foo}",270 "baz": "{.species}"271 },272 "{with}": {273 "foo": "{.genus}"274 }275 })276 actual = resolve(template, data_0, data_index)277 expected = {278 "foo": "Zea",279 "baz": "mays"280 }281 self.assertEqual(actual, expected)...
evaluator_test.py
Source:evaluator_test.py
1from pyrake.template_parser import parse_template2from pyrake.evaluator import evaluate_template3def test_evaluate_scalar_literal():4 template = parse_template('hello')5 res = evaluate_template(template, None)6 assert res == 'hello'7def test_evaluate_scalar_term():8 data = {'bar': 'hello world'}9 template = parse_template('$(bar)')10 res = evaluate_template(template, data)11 assert res == 'hello world'12def test_evaluate_scalar_mixed():13 data = {'greeting': 'hello', 'name': 'san'}14 template = parse_template('$(greeting) world, $(name)!')15 res = evaluate_template(template, data)16 assert res == 'hello world, san!'17def test_evaluate_scalar_error():18 data = {'bar': 'hello world'}19 template = parse_template('other text $(non_existent_key)hello world')20 res = evaluate_template(template, data)21 assert res == "other text $(err: KeyError: 'non_existent_key')hello world"22def test_evaluate_scalar_to_int():23 data = {'bar': 777}24 template = parse_template('$int:$(bar)')25 res = evaluate_template(template, data)26 assert res == 77727def test_evaluate_scalar_to_float():28 data = {'bar': 777.7}29 template = parse_template('$float:$(bar)')30 res = evaluate_template(template, data)31 assert res == 777.732def test_evaluate_scalar_to_true():33 data = {'bar': True}34 template = parse_template('$bool:$(bar)')35 res = evaluate_template(template, data)36 assert isinstance(res, bool)37 assert res38def test_evaluate_scalar_to_false():39 data = {'bar': False}40 template = parse_template('$bool:$(bar)')41 res = evaluate_template(template, data)42 assert isinstance(res, bool)43 assert not res44def test_evaluate_dict():45 data = {'bar': 'hello world'}46 template = parse_template({'field1': 'hi', 'field2': '$(bar)'})47 res = evaluate_template(template, data)48 assert res == {'field1': 'hi', 'field2': 'hello world'}49def test_evaluate_dict_empty():50 data = {}51 template = parse_template({})52 res = evaluate_template(template, data)53 assert res == {}54def test_evaluate_list():55 data = {56 'lelist': [57 {58 'var': 059 },60 {61 'var': 162 },63 {64 'var': 265 },66 ]67 }68 template = parse_template(['$each lelist', 'hey$(var)'])69 res = evaluate_template(template, data)70 assert res == ['hey0', 'hey1', 'hey2']71def test_evaluate_list_multi_groups():72 data = {73 'lelist': [74 {75 'var': 076 },77 {78 'var': 179 },80 ],81 'leotherlist': [82 {83 'foo': 'abc'84 },85 {86 'foo': 'def'87 },88 ]89 }90 template = parse_template(91 ['$each lelist', 'hey$(var)', '$each leotherlist', 'omg$(foo)'])92 res = evaluate_template(template, data)93 assert res == ['hey0', 'hey1', 'omgabc', 'omgdef']94def test_evaluate_nested_list():95 data = {96 'outerlist': [{97 'innerlist': [98 {99 'var': '0.0'100 },101 {102 'var': '0.1'103 },104 ]105 }, {106 'innerlist': [107 {108 'var': '1.0'109 },110 {111 'var': '1.1'112 },113 ]114 }],115 }116 template = parse_template(117 ['$each outerlist', ['$each innerlist', '$(var)']])118 res = evaluate_template(template, data)119 assert res == [['0.0', '0.1'], ['1.0', '1.1']]120def test_evaluate_list_without_group():121 data = {'var': '0'}122 template = parse_template(['hey$(var)'])123 res = evaluate_template(template, data)124 assert res == ['hey0']125def test_evaluate_list_error():126 data = {}127 template = parse_template(['$each lelist', 'hey$(var)'])128 res = evaluate_template(template, data)129 assert res == ["$(err: KeyError: 'lelist')"]130def test_evaluate_list_error_in_one_group():131 data = {132 'leotherlist': [133 {134 'foo': 'abc'135 },136 {137 'foo': 'def'138 },139 ]140 }141 template = parse_template(142 ['$each lelist', 'hey$(var)', '$each leotherlist', 'omg$(foo)'])143 res = evaluate_template(template, data)...
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!!