Best Python code snippet using pyatom_python
Gewicht.py
Source:Gewicht.py
1#!/usr/bin/python32# -*- coding: utf-8 -*-3#########################################################4import csv5from PyQt5.QtCore import (QFile, QSize, Qt, QUrl, QDate, QDir, QSettings)6from PyQt5.QtGui import QIcon, QFont, QImage, QPixmap, QDesktopServices7from PyQt5.QtWidgets import (QAction, QApplication, QMainWindow, QLineEdit, QFileDialog, QAbstractItemView, 8 QTableWidget, QTableWidgetItem, QLabel, QInputDialog, QDateEdit, QDateTimeEdit, QComboBox)9from os import path10from subprocess import Popen, run11#########################################################12class PyDateEdit(QDateEdit):13 def __init__(self, *args):14 super(PyDateEdit, self).__init__(*args)15 self.setCalendarPopup(False)16 self.setDisplayFormat("dd.MM.yy")17 self.setStyleSheet(stylesheet(self))18 self.installEventFilter(self)19 def eventFilter(self, obj, event):20 if obj == self:21 if QApplication.mouseButtons() == Qt.LeftButton:22 self.setSelectedSection(QDateTimeEdit.DaySection)23 return True24 else:25 return False26 else:27 return PyDateEdit.eventFilter(obj, event)28 29 def clearDate(self):30 self.findChild(QLineEdit).setText('')31class MainWindow(QMainWindow):32 def __init__(self):33 super(MainWindow, self).__init__()34 self.setWindowIcon(QIcon("waage.png"))35 self.layout().setContentsMargins(0, 0, 0, 0)36 self.myfile = 'Gewicht.csv'37 self.isChanged = False38 39 self.settings = QSettings("Gewicht", "gewicht")40 self.setMinimumWidth(500)41 self.setMinimumHeight(550)42 self.setContentsMargins(10, 2, 10, 2)43 self.setStyleSheet(stylesheet(self))44 self.list = []45 self.date = ""46 self.time = ""47 self.setWindowTitle("Gewicht")48 49 self.is_imported = False50 self.canGnuplot = False51 52 self.imgLabel = QLabel()53 self.imgLabel.setScaledContents(True)54 self.createStatusBar()55 self.statusBar().hide()56 self.tableview = QTableWidget()57 self.tableview.setColumnCount(3)58 self.tableview.cellDoubleClicked.connect(self.beginTableEditing)59 self.setHeaders()60 self.tableview.verticalHeader().setVisible(False)61 self.tableview.horizontalHeader().setVisible(False)62 self.tableview.setSelectionBehavior(self.tableview.SelectRows)63 self.tableview.setSelectionMode(self.tableview.SingleSelection)64 self.setCentralWidget(self.tableview)65 66 self.start_date = "20000101"67 self.end_date = QDate.currentDate().toString("yyyyMMdd")68 69 self.date_edit_start = PyDateEdit()70 self.date_edit_start.setContextMenuPolicy(Qt.PreventContextMenu)71 self.date_edit_start.setButtonSymbols(2)72 self.date_edit_start.setToolTip("Startdatum")73 self.date_edit_start.setFixedWidth(200)74 self.date_edit_start.editingFinished.connect(self.editDate)75 76 self.date_edit_end = PyDateEdit()77 self.date_edit_end.setContextMenuPolicy(Qt.PreventContextMenu)78 self.date_edit_end.setButtonSymbols(2)79 self.date_edit_end.setToolTip("Enddatum")80 self.date_edit_end.setFixedWidth(200)81 self.date_edit_end.editingFinished.connect(self.editDate)82 self.createToolBars()83 self.show()84 85 if QFile.exists(self.myfile):86 print("file exists")87 self.loadCsvOnOpen()88 else:89 print("file not exists")90 self.setHeaders()91 self.addRow("")92 def setDatesFromTable(self):93 #print("def DatesFrom Table")94 self.canGnuplot = False95 if self.tableview.rowCount() > 0:96 sd = self.tableview.item(0, 0).text()97 ed = self.tableview.item(self.tableview.rowCount() - 1, 0).text()98 self.date_edit_end.setDate(QDate.fromString(ed, "dddd, dd.MMMM yyyy")) 99 self.date_edit_start.setDate(QDate.fromString(sd, "dddd, dd.MMMM yyyy"))100 sqldate_start = self.date_edit_start.date().toString("yyyyMMdd")101 self.end_date = self.date_edit_end.date().toString("yyyyMMdd")102 self.canGnuplot = True103 self.callGnuplot()104 105 def editDate(self):106 print("def editDate")107 self.canGnuplot = False108 self.start_date = self.date_edit_start.date().toString("yyyyMMdd")109 self.end_date = self.date_edit_end.date().toString("yyyyMMdd")110 sqldate_start = self.date_edit_start.date().toString("yyyyMMdd")111 self.start_date = sqldate_start112 sqldate_end = self.date_edit_end.date().toString("yyyyMMdd")113 self.end_date = sqldate_end114 print("Start Tag:", self.start_date, "End Tag:", self.end_date)115 self.updateTable()116 117 def beginTableEditing(self): 118 print("begin editing")119 self.canGnuplot = False120 self.isChanged = True121 122 def tableEditFinished(self):123 return124 def setHeaders(self):125 self.tableview.horizontalHeader().setVisible(True)126 font = QFont()127 font.setPointSize(8)128 self.tableview.horizontalHeader().setFont(font)129 self.tableview.setColumnWidth(0, 190)130 self.tableview.setColumnWidth(1, 55)131 self.tableview.setColumnWidth(2, 180)132 self.tableview.setColumnWidth(3, 0)133 self.tableview.setHorizontalHeaderItem(0, QTableWidgetItem("Datum"))134 self.tableview.setHorizontalHeaderItem(1, QTableWidgetItem("kg"))135 self.tableview.setHorizontalHeaderItem(2, QTableWidgetItem("Bemerkungen"))136 self.tableview.setHorizontalHeaderItem(3, QTableWidgetItem("SQL Datum"))137 self.tableview.horizontalHeader().setDefaultAlignment(Qt.AlignCenter)138 self.tableview.hideColumn(3)139 self.tableview.setAlternatingRowColors(True)140 def showMessage(self, message):141 self.statusBar().showMessage(message)142 def closeEvent(self, event):143 if self.isChanged == True and self.is_imported == False:144 self.writeCSV()145 self.settings.setValue("geo", self.geometry())146 self.settings.setValue("chartStatus", self.btnChart.text())147 event.accept()148 def createToolBars(self):149 self.tb = self.addToolBar("Buttons")150 self.tb.setToolButtonStyle(2)151 self.tb.setMovable(False)152 self.tb.setFloatable(False)153 self.tb.setIconSize(QSize(16, 16))154 self.btnAdd = QAction(QIcon.fromTheme('add'), "neuer Eintrag", self,155 toolTip="neue Messung",156 triggered=self.insertNewRow)157 self.tb.addAction(self.btnAdd)158 self.btnRemove = QAction(QIcon.fromTheme('edit-delete'), "Zeile löschen", self,159 toolTip="Zeile löschen",160 triggered=self.removeRow)161 self.tb.addAction(self.btnRemove)162 self.tb.addSeparator()163 164 self.folderAct = QAction(QIcon.fromTheme('folder'), "", self,165 toolTip="Programmordner öffnen",166 triggered=self.openFolder)167 self.folderAct.setIconText("Programmordner öffnen")168 self.tb.addAction(self.folderAct)169 ### Import170 self.importAct = QAction(QIcon.fromTheme('document-open'), "", self,171 toolTip="CSV importieren",172 triggered=self.importCSV)173 self.importAct.setIconText("Import")174 self.tb.addAction(self.importAct)175 ### Export Zeitraum176 self.exportAct = QAction(QIcon.fromTheme('document-save-as'), "", self,177 toolTip="Zeitraum als CSV exportieren",178 triggered=self.exportCSV)179 self.exportAct.setIconText("Export")180 self.tb.addAction(self.exportAct)181 self.tb.addSeparator()182 ### Export Zeitraum183 self.manualAct = QAction(QIcon.fromTheme('browser'), "", self,184 toolTip="Manual",185 triggered=self.showManual)186 self.manualAct.setIconText("Manual")187 self.tb.addAction(self.manualAct) 188 189 ### Toolbar 2190 self.addToolBarBreak(Qt.TopToolBarArea) 191 self.tbd = self.addToolBar("Date")192 self.tbd.setMovable(False)193 self.tbd.setFloatable(False)194 self.tbd.setIconSize(QSize(16, 16)) 195 self.tbd.addWidget(self.date_edit_start)196 self.tbd.addSeparator()197 self.tbd.addWidget(self.date_edit_end)198 self.tbd.addSeparator()199 ### externes Diagramm200 self.extern = QAction(QIcon("gnuplot_icon"), "", self, 201 toolTip="externes Diagramm öffnen", 202 triggered = self.callGnuplotExtern) 203 self.extern.setIconText("externes Diagramm öffnen")204 self.tbd.addAction(self.extern)205 ### internes Diagramm206 self.btnChart = QAction(QIcon("plot_icon"), "Diagramm anzeigen", self, 207 toolTip="internes Diagramm anzeigen/ausblenden", 208 triggered = self.toggleChart)209 self.tbd.addSeparator()210 self.btnChart.setIconText("Diagramm anzeigen")211 self.tbd.addAction(self.btnChart) 212 213 ### ComboBox Jahre214 self.btnYears = QComboBox()215 self.btnYears.setFixedWidth(80)216 self.btnYears.currentIndexChanged.connect(self.toggleYear)217 self.tbd.addWidget(self.btnYears)218 219 def showManual(self):220 manual = "manual.html"221 QDesktopServices.openUrl(QUrl(manual))222 def toggleYear(self):223 if self.tableview.rowCount() > 0 and self.btnYears.currentIndex() > 0:224 if self.btnYears.currentIndex() == self.btnYears.count() - 1:225 print("alles anzeigen")226 for row in range(self.tableview.rowCount() - 1):227 self.tableview.showRow(row)228 self.setDatesFromTable()229 self.callGnuplot()230 self.selectLastRow()231 self.tableview.scrollToBottom()232 else:233 ed = f'{self.btnYears.currentText()}1231'234 sd = f'{self.btnYears.currentText()}0101'235 self.canGnuplot = False236 self.date_edit_start.setDate(QDate.fromString(sd, "yyyyMMdd"))237 self.date_edit_end.setDate(QDate.fromString(ed, "yyyyMMdd"))238 self.editDate()239 self.canGnuplot = True240 self.callGnuplot()241 self.selectLastRow()242 243 def toggleChart(self):244 if self.btnChart.text() == "Diagramm anzeigen":245 self.statusBar().show()246 self.btnChart.setText("Diagramm ausblenden")247 self.btnChart.setIcon(QIcon("plot_icon_dis"))248 self.updateImage()249 else:250 self.btnChart.setText("Diagramm anzeigen")251 self.statusBar().hide()252 self.btnChart.setIcon(QIcon("plot_icon"))253 254 def callGnuplot(self):255 if self.tableview.rowCount() > 0 and self.canGnuplot == True:256 liste = []257 for row in range(self.tableview.rowCount()):258 if int(self.tableview.item(row, 3).text()) >= int(self.start_date) \259 and int(self.tableview.item(row, 3).text()) <= int(self.end_date):260 self.tableview.showRow(row)261 tag = self.tableview.item(row, 3).text()262 gew = self.tableview.item(row, 1).text()263 liste.append(f"{tag}\t{gew}")264 #else:265 #self.tableview.hideRow(row)266 temp_file = 'zeitraum.csv'267 gnuplot_file = 'preview_intern.gnuplot'268 with open(temp_file , 'w') as f:269 f.write('\n'.join(liste))270 f.close()271 272 cmd = "gnuplot"273 if run([cmd, gnuplot_file]):274 print("gnuplot intern finished")275 self.updateImage()276 277 def updateImage(self):278 print("update Image")279 myimage = QImage("messung_intern.png")280 if myimage.isNull():281 self.showMessage("Cannot load messung_intern.png")282 return283 else:284 self.imgLabel.setPixmap(QPixmap.fromImage(myimage))285 self.imgLabel.show()286 287 # externes Diagramm 288 def callGnuplotExtern(self):289 if self.tableview.rowCount() > 0 and self.canGnuplot == True:290 liste = []291 for row in range(self.tableview.rowCount()):292 if int(self.tableview.item(row, 3).text()) >= int(self.start_date) \293 and int(self.tableview.item(row, 3).text()) <= int(self.end_date):294 self.tableview.showRow(row)295 tag = self.tableview.item(row, 3).text()296 gew = self.tableview.item(row, 1).text()297 liste.append(f"{tag}\t{gew}")298 #else:299 #self.tableview.hideRow(row)300 temp_file = 'zeitraum.csv'301 gnuplot_file = 'preview_extern.gnuplot'302 with open(temp_file , 'w') as f:303 f.write('\n'.join(liste))304 f.close()305 306 cmd = "gnuplot"307 run([cmd, "-p", gnuplot_file])308 def updateTable(self):309 for row in range(self.tableview.rowCount()):310 if int(self.tableview.item(row, 3).text()) >= int(self.start_date) \311 and int(self.tableview.item(row, 3).text()) <= int(self.end_date):312 self.tableview.showRow(row)313 else:314 self.tableview.hideRow(row)315 self.selectLastRow() 316 self.canGnuplot = True317 self.callGnuplot()318 319 def selectLastRow(self):320 last = self.tableview.rowCount() - 1321 self.tableview.selectRow(last) 322 last_item = self.tableview.item(self.tableview.rowCount() - 1, 0) 323 last_item.setSelected(True)324 self.tableview.scrollToBottom()325 326 def openFolder(self):327 myfolder = path.dirname(sys.argv[0])328 QDesktopServices.openUrl(QUrl.fromLocalFile(myfolder))329 def createStatusBar(self):330 self.statusBar().addWidget(self.imgLabel)331 def loadCsvOnOpen(self):332 self.canGnuplot = False333 filename = self.myfile334 if QFile.exists(filename):335 f = open(filename, 'r')336 self.tableview.setRowCount(0)337 self.tableview.setColumnCount(3)338 for rowdata in csv.reader(f, delimiter='\t'):339 row = self.tableview.rowCount()340 self.tableview.insertRow(row)341 if len(rowdata) == 0:342 self.tableview.setColumnCount(len(rowdata) + 1)343 else:344 self.tableview.setColumnCount(len(rowdata))345 for column, data in enumerate(rowdata):346 item = QTableWidgetItem(data)347 self.tableview.setItem(row, column, item)348 self.setTableAignment()349 self.tableview.horizontalHeader().setStretchLastSection(True)350 self.setHeaders()351 self.tableview.resizeRowsToContents()352 self.selectLastRow()353 self.isChanged = False354 self.fillCombo()355 356 def fillCombo(self):357 ### Combobox leeren358 self.btnYears.clear()359 ### Combobox füllen360 yearList = []361 for row in range(self.tableview.rowCount() - 1):362 yearList.append(self.tableview.item(row, 3).text()[:4])363 mylist = sorted(list(set(yearList)))364 self.btnYears.addItem("Jahre")365 self.btnYears.addItems(mylist)366 self.setDatesFromTable()367 self.btnYears.addItem("alles")368 def setTableAignment(self):369 for x in range(self.tableview.rowCount()):370 self.tableview.item(x, 0).setTextAlignment(Qt.AlignRight)371 self.tableview.item(x, 1).setTextAlignment(Qt.AlignRight)372 self.tableview.item(x, 2).setTextAlignment(Qt.AlignCenter)373 def removeRow(self):374 row = self.selectedRow()375 self.tableview.removeRow(row)376 self.isChanged = True377 self.tableview.selectRow(row)378 def selectedRow(self):379 if self.tableview.selectionModel().hasSelection():380 row = self.tableview.selectionModel().selectedIndexes()[0].row()381 return int(row)382 383 def insertNewRow(self):384 dlg = QInputDialog()385 last = self.tableview.item(self.tableview.rowCount() - 1, 1).text()386 syst, ok = dlg.getDouble(self, 'neuer Eintrag', "Gewicht", float(last))387 if ok:388 self.addRow(str(syst))389 def addRow(self, syst):390 row = self.tableview.rowCount()391 if row > 0:392 lastdate = self.tableview.item(self.tableview.rowCount() - 1, 0).text()393 self.tableview.insertRow(row)394 self.tableview.horizontalHeader().setStretchLastSection(True)395 396 column = 0397 print("lastdate: ", lastdate)398 d = QDate.fromString(lastdate, "dddd, dd.MMMM yyyy")399 dt = d.addDays(1)400 sqldate = dt.toString("yyyyMMdd")401 newItem = QTableWidgetItem(dt.toString("dddd, dd.MMMM yyyy"))402 newItem.setTextAlignment(Qt.AlignRight)403 self.tableview.setItem(row,column, newItem)404 405 column = 1406 newItem = QTableWidgetItem(syst)407 newItem.setTextAlignment(Qt.AlignRight)408 self.tableview.setItem(row,column, newItem)409 410 column = 2411 newItem = QTableWidgetItem("")412 self.tableview.setItem(row,column, newItem)413 414 column = 3415 newItem = QTableWidgetItem(sqldate)416 self.tableview.setItem(row,column, newItem)417 418 self.isChanged = True419 self.selectLastRow()420 else:421 self.tableview.setColumnCount(4)422 self.tableview.hideColumn(3)423 lastdate = QDate.currentDate().toString("dddd, dd.MMMM yyyy")424 self.tableview.insertRow(0)425 self.tableview.horizontalHeader().setStretchLastSection(True)426 newItem = QTableWidgetItem(QDate.currentDate().toString("dddd, dd.MMMM yyyy"))427 newItem.setTextAlignment(Qt.AlignRight)428 self.tableview.setItem(row,0, newItem)429 sqlItem = QTableWidgetItem(QDate.currentDate().toString("yyyyMMdd"))430 self.tableview.setItem(row,3, sqlItem)431 def writeCSV(self):432 with open(self.myfile, 'w') as stream:433 print("saving", self.myfile)434 writer = csv.writer(stream, delimiter='\t')435 for row in range(self.tableview.rowCount()):436 rowdata = []437 for column in range(self.tableview.columnCount()):438 item = self.tableview.item(row, column)439 if item is not None:440 rowdata.append(item.text())441 else:442 rowdata.append('')443 writer.writerow(rowdata)444 self.isChanged = False445 446 def exportCSV(self):447 daterange = f'{self.date_edit_start.text().replace(".", "_")}-{self.date_edit_end.text().replace(".", "_")}'448 filename = f"Gewicht_{daterange}"449 print(filename)450 exportfile, _ = QFileDialog.getSaveFileName(self, "Zeitraum speichern", f'QDir.homePath()/{filename}.csv',451 "CSV Dateien (*.csv)")452 if (exportfile != ""):453 with open(exportfile, 'w') as stream:454 print("saving", self.myfile)455 writer = csv.writer(stream, delimiter='\t')456 for row in range(self.tableview.rowCount()):457 ### nur Zeilen die angezeigt werden458 if int(self.tableview.item(row, 3).text()) >= int(self.start_date) \459 and int(self.tableview.item(row, 3).text()) <= int(self.end_date): 460 rowdata = []461 for column in range(self.tableview.columnCount()):462 item = self.tableview.item(row, column)463 if item is not None:464 rowdata.append(item.text())465 else:466 rowdata.append('')467 writer.writerow(rowdata)468 self.isChanged = False 469 470 def importCSV(self):471 filename, _ = QFileDialog.getOpenFileName(self, "Import CSV", "","CSV Dateien (*.csv)")472 if filename:473 f = open(filename, 'r')474 self.tableview.setRowCount(0)475 for rowdata in csv.reader(f, delimiter='\t'):476 row = self.tableview.rowCount()477 self.tableview.insertRow(row)478 if len(rowdata) == 0:479 self.tableview.setColumnCount(len(rowdata) + 1)480 else:481 self.tableview.setColumnCount(len(rowdata))482 for column, data in enumerate(rowdata):483 item = QTableWidgetItem(data)484 self.tableview.setItem(row, column, item)485 self.setTableAignment()486 self.tableview.horizontalHeader().setStretchLastSection(True)487 self.setHeaders()488 self.tableview.resizeRowsToContents()489 self.selectLastRow()490 self.isChanged = False491 self.is_imported = True492 self.setDatesFromTable()493 self.fillCombo()494 495def stylesheet(self):496 return """497 QTableWidget498 {499 border: 0.5px solid lightgrey;500 border-radius: 0px;501 font-size: 8pt;502 background-color: #e4eef6;503 } 504 QMainWindow505 {506 background: #e9e9e9;507 } 508 QToolBar509 {510 background: #e9e9e9;511 border: 0px;512 }513 QDateEdit514 {515 font-size: 9pt;516 }517 """518if __name__ == '__main__':519 import sys520 app = QApplication(sys.argv)521 geo = app.desktop().screenGeometry()522 print(geo)523 mainWin = MainWindow()524 if mainWin.settings.contains("geo"):525 mainWin.setGeometry(mainWin.settings.value("geo"))526 else:527 mainWin.setGeometry(0, 0, 900, geo.height() - 60)528 if mainWin.settings.contains("chartStatus"):529 if mainWin.settings.value("chartStatus") == "Diagramm ausblenden":530 mainWin.statusBar().show()531 mainWin.btnChart.setText("Diagramm ausblenden")532 mainWin.btnChart.setIcon(QIcon("plot_icon_dis"))533 mainWin.updateImage()534 else:535 mainWin.btnChart.setText("Diagramm anzeigen")536 mainWin.statusBar().hide()537 mainWin.btnChart.setIcon(QIcon("plot_icon")) 538 ...
demo.py
Source:demo.py
1# -*- coding: UTF-8 -*-2import acsv;3import json;4import os;5class Demo:6 def __init__(self):7 srcDir = os.path.dirname(__file__)8 f = open(srcDir + "/../../release/csvs/standard_format_text.csv", "r")9 self._tab1 = acsv.Table.Parse(f.read())10 self.test_standard_csv_format()11 f = open(srcDir + "/../../release/csvs/enhanced_format_text.csv", "r")12 self._tab2 = acsv.Table.Parse(f.read())13 self.test_enhanced_csv_format()14 def P(self, cmd, o):15 print(cmd)16 if (o is None):17 print(str(None))18 else:19 print(o)20 #print(json.dumps(o, ensure_ascii=False))21 print('\n')22 def test_standard_csv_format(self):23 self.P("select ALL to rows",self._tab1.selectAll().toRows())24 self.P("select ALL to objs",self._tab1.selectAll().toObjs())25 self.P("select first row",self._tab1.selectFirstRow().toFirstRow())26 self.P("select first obj",self._tab1.selectFirstRow().toFirstObj())27 self.P("select last row",self._tab1.selectLastRow().toFirstRow())28 self.P("select last obj",self._tab1.selectLastRow().toFirstObj())29 self.P("selectWhenE (id) = \"2\"",self._tab1.selectWhenE(1,"2").toFirstObj())30 self.P("selectWhenE (id) = \"3\" and (id2) = \"21\"",self._tab1.selectWhenE2(1,"3","21").toFirstObj())31 self.P("selectWhenE (id) = \"4\" and (id2) = \"21\" and (id3) = \"200\"",self._tab1.selectWhenE3(1,"4","21","200").toFirstObj())32 self.P("selectWhenE ALL (id2) = \"20\"",self._tab1.selectWhenE(0,"20",1).toObjs())33 self.P("merge tables",self._tab1.merge(self._tab1).selectAll().toRows())34 def test_enhanced_csv_format(self):35 self.P("[E] select ALL to rows",self._tab2.selectAll().toRows())36 self.P("[E] select ALL to objs",self._tab2.selectAll().toObjs())37 self.P("[E] select first row",self._tab2.selectFirstRow().toFirstRow())38 self.P("[E] select first obj",self._tab2.selectFirstRow().toFirstObj())39 self.P("[E] select last row",self._tab2.selectLastRow().toFirstRow())40 self.P("[E] select last obj",self._tab2.selectLastRow().toFirstObj())41 self.P("[E] selectWhenE (id) = 2",self._tab2.selectWhenE(1,2).toFirstObj())42 self.P("[E] selectWhenE (id) = -1",self._tab2.selectWhenE(1,-1).toFirstObj())43 self.P("[E] selectWhenE2 (id) = 3 and (id2) = 22",self._tab2.selectWhenE2(1,3,22).toFirstObj())44 self.P("[E] selectWhenE2 (id) = 3 and (id2) = -1",self._tab2.selectWhenE2(1,3,-1).toFirstObj())45 self.P("[E] selectWhenE3 (id) = 4 and (id2) = 22 and (id3) = 200",self._tab2.selectWhenE3(1,4,22,200).toFirstObj())46 self.P("[E] selectWhenE3 (id) = 4 and (id2) = 22 and (id3) = -1",self._tab2.selectWhenE3(1,4,22,-1).toFirstObj())47 self.P("[E] selectWhenE ALL (id2) = 21",self._tab2.selectWhenE(0,21,1).toObjs())48 self.P("[E] selectWhenE ALL (id2) = -1",self._tab2.selectWhenE(0,-1,1).toObjs())49 self.P("[E] selectWhenG ALL (id2) > 25",self._tab2.selectWhenG(0,False,25,1).toObjs())50 self.P("[E] selectWhenG ALL (id2) >= 25",self._tab2.selectWhenG(0,True,25,1).toObjs())51 self.P("[E] selectWhenG ALL (id2) > 30",self._tab2.selectWhenG(0,False,30,1).toObjs())52 self.P("[E] selectWhenL ALL (id2) < 22",self._tab2.selectWhenL(0,False,22,1).toObjs())53 self.P("[E] selectWhenL ALL (id2) <= 22",self._tab2.selectWhenL(0,True,22,1).toObjs())54 self.P("[E] selectWhenL ALL (id2) < 20",self._tab2.selectWhenL(0,True,20,1).toObjs())55 self.P("[E] selectWhenGreaterAndLess ALL (id2) > 21 and (id2) < 24",self._tab2.selectWhenGreaterAndLess(0,False,False,21,24,1).toObjs())56 self.P("[E] selectWhenGreaterAndLess ALL (id2) >= 21 and (id2) <= 24",self._tab2.selectWhenGreaterAndLess(0,True,True,21,24,1).toObjs())57 self.P("[E] selectWhenLessOrGreater ALL (id2) < 22 or (id2) > 25",self._tab2.selectWhenLessOrGreater(0,False,False,22,25,1).toObjs())58 self.P("[E] selectWhenLessOrGreater ALL (id2) <= 22 or (id2) >= 25",self._tab2.selectWhenLessOrGreater(0,True,True,22,25,1).toObjs())59 self.P("[E] selectWhenIn (id) in 3,4,5",self._tab2.selectWhenIn(1,[3, 4, 5]).toObjs())60 self.P("[E] selectAt rows at 0,1,10",self._tab2.selectAt([0, 1, 10]).toObjs())61 self.P("[E] multi selects (id3) = 100 and (id2) < 22",self._tab2.selectWhenE(0,100,2).selectWhenL(0,False,22,1).toObjs())62 self.P("[E] sort by (id3) = 300 desc (id)",self._tab2.selectWhenE(0,300,2).sortBy(0,1).toObjs())63 self._tab2.createIndexAt(0)64 self.P("[E] (indexed) 1st row name",self._tab2.selectWhenE(1,"Dwi",self._tab2.getColIndexBy("name")).toObjs()[0]["name"])65 self.P("[E] (indexed) id=6 education.CC",self._tab2.id(6)["education"]["CC"])66 self.P("[E] (indexed) id=6 tags #2",self._tab2.id(6)["tags"][1])67 self.P("[E] (indexed) 99th row",self._tab2.selectWhenE(1, 99).toObjs())...
table.py
Source:table.py
1#!/usr/bin/env python2#3# Linux Desktop Testing Project http://www.gnomebangalore.org/ldtp4#5# Description:6# This set of test scripts will test the LDTP framework for correct7# functioning of its APIs. This is a Regression Suite.8#9# Author:10# Prashanth Mohan <prashmohan@gmail.com>11#12#13# This test script is free software; you can redistribute it and/or14# modify it under the terms of the GNU Library General Public15# License as published by the Free Software Foundation; either16# version 2 of the License, or (at your option) any later version.17#18# This library is distributed in the hope that it will be useful,19# but WITHOUT ANY WARRANTY; without even the implied warranty of20# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU21# Library General Public License for more details.22#23# You should have received a copy of the GNU Library General Public24# License along with this library; if not, write to the25# Free Software Foundation, Inc., 59 Temple Place - Suite 330,26# Boston, MA 02111-1307, USA.27#28from regression import *29import random, os30try:31 open_evo ()32except:33 raise34data_object = LdtpDataFileParser (datafilename)35rows = data_object.gettagvalue ('rowcount')36evo_win = '*Evolution*'37pref = '*EvolutionPreferences'38acnt_tab = 'tblMailAccounts'39log ('getrowcount','teststart')40try:41 selectmenuitem (evo_win, 'mnuEdit;mnuPreferences')42 if waittillguiexist (pref) == 0:43 log ('Preferences Window not open yet','cause')44 raise LdtpExecutionError (str (traceback.format_exc ()))45 row_count = getrowcount (pref, acnt_tab)46 if rows != [] and rows != row_count:47 log ('No of rows does not match with input','cause')48 raise LdtpExecutionError (str (traceback.format_exc ()))49except:50 testfail ('getrowcount')51 raise LdtpExecutionError (str (traceback.format_exc ()))52testpass ('getrowcount')53acnts = []54log ('getcellvalue', 'teststart')55try:56 for index in range (row_count):57 val = getcellvalue (pref, acnt_tab, index, 1)58## http://bugzilla.gnome.org/show_bug.cgi?id=35222059# if verifytablecell (pref, acnt_tab, index, 1, val) == 0:60# log ('problem in getcellvalue','cause')61# raise LdtpExecutionError (str (traceback.format_exc ()))62 acnts.append (val)63except:64 testfail ('getcellvalue')65 raise LdtpExecutionError (str (traceback.format_exc ()))66testpass ('getcellvalue')67log ('selectrowindex','teststart')68try:69 for index in range (row_count):70 if selectrowindex (pref, acnt_tab, index) != 1:71 log ('Unable to select index','cause')72 raise LdtpExecutionError (str (traceback.format_exc ()))73 #time.sleep (1)74 if gettablerowindex (pref, acnt_tab, acnts[index]) != index:75 log ('Index not selected','cause')76 raise LdtpExecutionError (str (traceback.format_exc ()))77except:78 testfail ('selectrowindex')79 raise LdtpExecutionError (str (traceback.format_exc ()))80testpass ('selectrowindex')81log ('selectrow','teststart')82try:83 index = 084 for acnt in acnts:85 if doesrowexist (pref, acnt_tab, acnt) == 1 and selectrow (pref, acnt_tab, acnt) != 1:86 log ('Unable to select row','cause')87 raise LdtpExecutionError (str (traceback.format_exc ()))88 #time.sleep (1)89 if gettablerowindex (pref, acnt_tab, acnt) != index:90 log ('Index not selected','cause')91 raise LdtpExecutionError (str (traceback.format_exc ()))92 index += 193except:94 testfail ('selectrow')95 raise LdtpExecutionError (str (traceback.format_exc ()))96testpass ('selectrow')97log ('selectlastrow','teststart')98try:99 if selectlastrow (pref,acnt_tab) != 1:100 log ('selectlastrow failed','cause')101 raise LdtpExecutionError (str (traceback.format_exc ()))102 #time.sleep (1)103 if gettablerowindex (pref, acnt_tab, acnt) != (len (acnts)-1):104 log ('Index not selected','cause')105 raise LdtpExecutionError (str (traceback.format_exc ()))106except:107 testfail ('selectlastrow')108 raise LdtpExecutionError (str (traceback.format_exc ()))109testpass ('selectlastrow')110log ('checkrow','teststart')111try:112 for index in range (row_count):113 if uncheckrow (pref, acnt_tab, index) == 0:114 log ('Unable to uncheck row','cause')115 raise LdtpExecutionError (str (traceback.format_exc ()))116 #time.sleep (2)117 if checkrow (pref, acnt_tab, index) == 0:118 log ('Unable to check row','cause')119 raise LdtpExecutionError (str (traceback.format_exc ()))120except:121 testfail ('checkrow')122 raise LdtpExecutionError (str (traceback.format_exc ()))123testpass ('checkrow')...
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!!