How to use log_check method in Lemoncheesecake

Best Python code snippet using lemoncheesecake

test_projector_pjlink_commands_02.py

Source:test_projector_pjlink_commands_02.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# vim: autoindent shiftwidth=4 expandtab textwidth=120 tabstop=4 softtabstop=43###############################################################################4# OpenLP - Open Source Lyrics Projection #5# --------------------------------------------------------------------------- #6# Copyright (c) 2008-2015 OpenLP Developers #7# --------------------------------------------------------------------------- #8# This program is free software; you can redistribute it and/or modify it #9# under the terms of the GNU General Public License as published by the Free #10# Software Foundation; version 2 of the License. #11# #12# This program is distributed in the hope that it will be useful, but WITHOUT #13# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or #14# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for #15# more details. #16# #17# You should have received a copy of the GNU General Public License along #18# with this program; if not, write to the Free Software Foundation, Inc., 59 #19# Temple Place, Suite 330, Boston, MA 02111-1307 USA #20###############################################################################21"""22Package to test the openlp.core.projectors.pjlink commands package.23"""24from unittest import TestCase, skip25from unittest.mock import patch, call26import openlp.core.projectors.pjlink27from openlp.core.projectors.constants import PJLINK_PORT, S_CONNECTED, S_OFF, S_ON28from openlp.core.projectors.db import Projector29from openlp.core.projectors.pjlink import PJLink, PJLinkUDP30from tests.resources.projector.data import TEST_HASH, TEST_PIN, TEST_SALT, TEST1_DATA, TEST2_DATA31class TestPJLinkCommands(TestCase):32 """33 Tests for the PJLinkCommands class part 234 """35 def test_projector_reset_information(self):36 """37 Test reset_information() resets all information and stops timers38 """39 # GIVEN: Test object40 with patch.object(openlp.core.projectors.pjlink, 'log') as mock_log:41 pjlink = PJLink(Projector(**TEST1_DATA), no_poll=True)42 log_debug_calls = [call('({ip}): Calling poll_timer.stop()'.format(ip=pjlink.name)),43 call('({ip}): Calling socket_timer.stop()'.format(ip=pjlink.name))]44 # timer and socket_timer not available until instantiation, so mock here45 with patch.object(pjlink, 'socket_timer') as mock_socket_timer, \46 patch.object(pjlink, 'poll_timer') as mock_timer:47 pjlink.power = S_ON48 pjlink.pjlink_name = 'OPENLPTEST'49 pjlink.manufacturer = 'PJLINK'50 pjlink.model = '1'51 pjlink.shutter = True52 pjlink.mute = True53 pjlink.lamp = True54 pjlink.fan = True55 pjlink.source_available = True56 pjlink.other_info = 'ANOTHER TEST'57 pjlink.send_queue = True58 pjlink.send_busy = True59 # WHEN: reset_information() is called60 pjlink.reset_information()61 # THEN: All information should be reset and timers stopped62 assert pjlink.power == S_OFF, 'Projector power should be OFF'63 assert pjlink.pjlink_name is None, 'Projector pjlink_name should be None'64 assert pjlink.manufacturer is None, 'Projector manufacturer should be None'65 assert pjlink.model is None, 'Projector model should be None'66 assert pjlink.shutter is None, 'Projector shutter should be None'67 assert pjlink.mute is None, 'Projector shuttter should be None'68 assert pjlink.lamp is None, 'Projector lamp should be None'69 assert pjlink.fan is None, 'Projector fan should be None'70 assert pjlink.source_available is None, 'Projector source_available should be None'71 assert pjlink.source is None, 'Projector source should be None'72 assert pjlink.other_info is None, 'Projector other_info should be None'73 assert pjlink.send_queue == [], 'Projector send_queue should be an empty list'74 assert pjlink.send_busy is False, 'Projector send_busy should be False'75 assert mock_timer.stop.called is True, 'Projector timer.stop() should have been called'76 assert mock_socket_timer.stop.called is True, 'Projector socket_timer.stop() should have been called'77 mock_log.debug.assert_has_calls(log_debug_calls)78 def test_process_pjlink_normal(self):79 """80 Test initial connection prompt with no authentication81 """82 # GIVEN: Initial mocks and data83 mock_log = patch.object(openlp.core.projectors.pjlink, "log").start()84 mock_disconnect_from_host = patch('openlp.core.projectors.pjlink.PJLink.disconnect_from_host').start()85 mock_send_command = patch('openlp.core.projectors.pjlink.PJLink.send_command').start()86 mock_readyRead = patch('openlp.core.projectors.pjlink.PJLink.readyRead').start()87 mock_change_status = patch('openlp.core.projectors.pjlink.PJLink.change_status').start()88 pjlink = PJLink(Projector(**TEST1_DATA), no_poll=True)89 pjlink.pin = None90 log_check = [call('({ip}) process_pjlink(): Sending "CLSS" initial command'.format(ip=pjlink.name)), ]91 # WHEN: process_pjlink called with no authentication required92 pjlink.process_pjlink(data="0")93 # THEN: proper processing should have occured94 mock_log.debug.has_calls(log_check)95 mock_disconnect_from_host.assert_not_called()96 assert 1 == mock_readyRead.connect.call_count, 'Should have only been called once'97 mock_change_status.assert_called_once_with(S_CONNECTED)98 mock_send_command.assert_called_with(cmd='CLSS', priority=True, salt=None)99 def test_process_pjlink_authenticate(self):100 """101 Test initial connection prompt with authentication102 """103 # GIVEN: Initial mocks and data104 mock_log = patch.object(openlp.core.projectors.pjlink, "log").start()105 mock_disconnect_from_host = patch('openlp.core.projectors.pjlink.PJLink.disconnect_from_host').start()106 mock_send_command = patch('openlp.core.projectors.pjlink.PJLink.send_command').start()107 mock_readyRead = patch('openlp.core.projectors.pjlink.PJLink.readyRead').start()108 mock_change_status = patch('openlp.core.projectors.pjlink.PJLink.change_status').start()109 pjlink = PJLink(Projector(**TEST1_DATA), no_poll=True)110 pjlink.pin = TEST_PIN111 log_check = [call('({ip}) process_pjlink(): Sending "CLSS" initial command'.format(ip=pjlink.name)), ]112 # WHEN: process_pjlink called with no authentication required113 pjlink.process_pjlink(data='1 {salt}'.format(salt=TEST_SALT))114 # THEN: proper processing should have occured115 mock_log.debug.has_calls(log_check)116 mock_disconnect_from_host.assert_not_called()117 assert 1 == mock_readyRead.connect.call_count, 'Should have only been called once'118 mock_change_status.assert_called_once_with(S_CONNECTED)119 mock_send_command.assert_called_with(cmd='CLSS', priority=True, salt=TEST_HASH)120 def test_process_pjlink_normal_pin_set_error(self):121 """122 Test process_pjlinnk called with no authentication but pin is set123 """124 # GIVEN: Initial mocks and data125 mock_log = patch.object(openlp.core.projectors.pjlink, 'log').start()126 mock_disconnect_from_host = patch('openlp.core.projectors.pjlink.PJLink.disconnect_from_host').start()127 mock_send_command = patch('openlp.core.projectors.pjlink.PJLink.send_command').start()128 pjlink = PJLink(Projector(**TEST1_DATA), no_poll=True)129 pjlink.pin = TEST_PIN130 log_check = [call('({ip}) Normal connection but PIN set - aborting'.format(ip=pjlink.name)), ]131 # WHEN: process_pjlink called with invalid authentication scheme132 pjlink.process_pjlink(data='0')133 # THEN: Proper calls should be made134 mock_log.error.assert_has_calls(log_check)135 assert 1 == mock_disconnect_from_host.call_count, 'Should have only been called once'136 mock_send_command.assert_not_called()137 def test_process_pjlink_normal_with_salt_error(self):138 """139 Test process_pjlinnk called with no authentication but pin is set140 """141 # GIVEN: Initial mocks and data142 mock_log = patch.object(openlp.core.projectors.pjlink, 'log').start()143 mock_disconnect_from_host = patch('openlp.core.projectors.pjlink.PJLink.disconnect_from_host').start()144 mock_send_command = patch('openlp.core.projectors.pjlink.PJLink.send_command').start()145 pjlink = PJLink(Projector(**TEST1_DATA), no_poll=True)146 pjlink.pin = TEST_PIN147 log_check = [call('({ip}) Normal connection with extra information - aborting'.format(ip=pjlink.name)), ]148 # WHEN: process_pjlink called with invalid authentication scheme149 pjlink.process_pjlink(data='0 {salt}'.format(salt=TEST_SALT))150 # THEN: Proper calls should be made151 mock_log.error.assert_has_calls(log_check)152 assert 1 == mock_disconnect_from_host.call_count, 'Should have only been called once'153 mock_send_command.assert_not_called()154 def test_process_pjlink_invalid_authentication_scheme_length_error(self):155 """156 Test initial connection prompt with authentication scheme longer than 1 character157 """158 # GIVEN: Initial mocks and data159 mock_log = patch.object(openlp.core.projectors.pjlink, 'log').start()160 mock_disconnect_from_host = patch('openlp.core.projectors.pjlink.PJLink.disconnect_from_host').start()161 mock_send_command = patch('openlp.core.projectors.pjlink.PJLink.send_command').start()162 pjlink = PJLink(Projector(**TEST1_DATA), no_poll=True)163 log_check = [call('({ip}) Invalid initial authentication scheme - aborting'.format(ip=pjlink.name)), ]164 # WHEN: process_pjlink called with invalid authentication scheme165 pjlink.process_pjlink(data='01')166 # THEN: socket should be closed and invalid data logged167 mock_log.error.assert_has_calls(log_check)168 assert 1 == mock_disconnect_from_host.call_count, 'Should have only been called once'169 mock_send_command.assert_not_called()170 def test_process_pjlink_invalid_authentication_data_length_error(self):171 """172 Test initial connection prompt with authentication no salt173 """174 # GIVEN: Initial mocks and data175 mock_log = patch.object(openlp.core.projectors.pjlink, 'log').start()176 mock_disconnect_from_host = patch('openlp.core.projectors.pjlink.PJLink.disconnect_from_host').start()177 mock_send_command = patch('openlp.core.projectors.pjlink.PJLink.send_command').start()178 pjlink = PJLink(Projector(**TEST1_DATA), no_poll=True)179 log_check = [call('({ip}) Authenticated connection but not enough info - aborting'.format(ip=pjlink.name)), ]180 # WHEN: process_pjlink called with no salt181 pjlink.process_pjlink(data='1')182 # THEN: socket should be closed and invalid data logged183 mock_log.error.assert_has_calls(log_check)184 assert 1 == mock_disconnect_from_host.call_count, 'Should have only been called once'185 mock_send_command.assert_not_called()186 def test_process_pjlink_authenticate_pin_not_set_error(self):187 """188 Test process_pjlink authentication but pin not set189 """190 # GIVEN: Initial mocks and data191 mock_log = patch.object(openlp.core.projectors.pjlink, 'log').start()192 mock_disconnect_from_host = patch('openlp.core.projectors.pjlink.PJLink.disconnect_from_host').start()193 mock_send_command = patch('openlp.core.projectors.pjlink.PJLink.send_command').start()194 pjlink = PJLink(Projector(**TEST1_DATA), no_poll=True)195 pjlink.pin = None196 log_check = [call('({ip}) Authenticate connection but no PIN - aborting'.format(ip=pjlink.name)), ]197 # WHEN: process_pjlink called with no salt198 pjlink.process_pjlink(data='1 {salt}'.format(salt=TEST_SALT))199 # THEN: socket should be closed and invalid data logged200 mock_log.error.assert_has_calls(log_check)201 assert 1 == mock_disconnect_from_host.call_count, 'Should have only been called once'202 mock_send_command.assert_not_called()203 @skip('Change to pjlink_udp.get_datagram() call')204 @patch.object(openlp.core.projectors.pjlink, 'log')205 def test_process_ackn_duplicate(self, mock_log):206 """207 Test process_ackn method with multiple calls with same data208 """209 # TODO: Change this to call pjlink_udp.get_datagram() so ACKN can be processed properly210 # GIVEN: Test setup211 pjlink = PJLink(projector=self.test_list[0])212 check_list = {TEST1_DATA['ip']: {'data': TEST1_DATA['mac_adx'], 'port': PJLINK_PORT}}213 log_warn_calls = [call('(___TEST_ONE___) Host {host} already replied - '214 'ignoring'.format(host=TEST1_DATA['ip']))]215 log_debug_calls = [call('PJlinkCommands(args=() kwargs={})'),216 call('(___TEST_ONE___) reset_information() connect status is S_NOT_CONNECTED'),217 call('(___TEST_ONE___) Processing ACKN packet'),218 call('(___TEST_ONE___) Adding {host} to ACKN list'.format(host=TEST1_DATA['ip'])),219 call('(___TEST_ONE___) Processing ACKN packet')]220 # WHEN: process_ackn called twice with same data221 pjlink.process_ackn(data=TEST1_DATA['mac_adx'], host=TEST1_DATA['ip'], port=PJLINK_PORT)222 pjlink.process_ackn(data=TEST1_DATA['mac_adx'], host=TEST1_DATA['ip'], port=PJLINK_PORT)223 # THEN: pjlink_udp.ack_list should equal test_list224 # NOTE: This assert only returns AssertionError - does not list differences. Maybe add a compare function?225 if pjlink.ackn_list != check_list:226 # Check this way so we can print differences to stdout227 print('\nackn_list: ', pjlink.ackn_list)228 print('test_list: ', check_list, '\n')229 assert pjlink.ackn_list == check_list230 mock_log.debug.assert_has_calls(log_debug_calls)231 mock_log.warning.assert_has_calls(log_warn_calls)232 @skip('Change to pjlink_udp.get_datagram() call')233 @patch.object(openlp.core.projectors.pjlink, 'log')234 def test_process_ackn_multiple(self, mock_log):235 """236 Test process_ackn method with multiple calls237 """238 # TODO: Change this to call pjlink_udp.get_datagram() so ACKN can be processed properly239 # GIVEN: Test setup240 pjlink_udp = PJLinkUDP(projector_list=self.test_list)241 check_list = {TEST1_DATA['ip']: {'data': TEST1_DATA['mac_adx'], 'port': PJLINK_PORT},242 TEST2_DATA['ip']: {'data': TEST2_DATA['mac_adx'], 'port': PJLINK_PORT}}243 log_debug_calls = [call('(UDP) PJLinkUDP() Initialized'),244 call('(UDP) Processing ACKN packet'),245 call('(UDP) Adding {host} to ACKN list'.format(host=TEST1_DATA['ip'])),246 call('(UDP) Processing ACKN packet'),247 call('(UDP) Adding {host} to ACKN list'.format(host=TEST2_DATA['ip']))]248 # WHEN: process_ackn called twice with different data249 pjlink_udp.process_ackn(data=TEST1_DATA['mac_adx'], host=TEST1_DATA['ip'], port=PJLINK_PORT)250 pjlink_udp.process_ackn(data=TEST2_DATA['mac_adx'], host=TEST2_DATA['ip'], port=PJLINK_PORT)251 # THEN: pjlink_udp.ack_list should equal test_list252 # NOTE: This assert only returns AssertionError - does not list differences. Maybe add a compare function?253 if pjlink_udp.ackn_list != check_list:254 # Check this way so we can print differences to stdout255 print('\nackn_list: ', pjlink_udp.ackn_list)256 print('test_list: ', check_list)257 assert pjlink_udp.ackn_list == check_list258 mock_log.debug.assert_has_calls(log_debug_calls)259 @skip('Change to pjlink_udp.get_datagram() call')260 @patch.object(openlp.core.projectors.pjlink, 'log')261 def test_process_ackn_single(self, mock_log):262 """263 Test process_ackn method with single call264 """265 # TODO: Change this to call pjlink_udp.get_datagram() so ACKN can be processed properly266 # GIVEN: Test setup267 pjlink_udp = PJLinkUDP(projector_list=self.test_list)268 check_list = {TEST1_DATA['ip']: {'data': TEST1_DATA['mac_adx'], 'port': PJLINK_PORT}}269 log_debug_calls = [call('(UDP) PJLinkUDP() Initialized'),270 call('(UDP) Processing ACKN packet'),271 call('(UDP) Adding {host} to ACKN list'.format(host=TEST1_DATA['ip']))]272 # WHEN: process_ackn called twice with different data273 pjlink_udp.process_ackn(data=TEST1_DATA['mac_adx'], host=TEST1_DATA['ip'], port=PJLINK_PORT)274 # THEN: pjlink_udp.ack_list should equal test_list275 # NOTE: This assert only returns AssertionError - does not list differences. Maybe add a compare function?276 if pjlink_udp.ackn_list != check_list:277 # Check this way so we can print differences to stdout278 print('\nackn_list: ', pjlink_udp.ackn_list)279 print('test_list: ', check_list)280 assert pjlink_udp.ackn_list == check_list281 mock_log.debug.assert_has_calls(log_debug_calls)282 @skip('Change to pjlink_udp.get_datagram() call')283 @patch.object(openlp.core.projectors.pjlink, 'log')284 def test_process_srch(self, mock_log):285 """286 Test process_srch method287 """288 # TODO: Change this to call pjlink_udp.get_datagram() so ACKN can be processed properly289 # GIVEN: Test setup290 log_warn_calls = [call('(UDP) SRCH packet received from {ip} - ignoring'.format(ip=TEST1_DATA['ip'])), ]291 log_debug_calls = [call('(UDP) PJLinkUDP() Initialized'), ]292 pjlink_udp = PJLinkUDP(projector_list=self.test_list)293 # WHEN: process_srch called294 pjlink_udp.process_srch(data=None, host=TEST1_DATA['ip'], port=PJLINK_PORT)295 # THEN: log entries should be entered296 mock_log.warning.assert_has_calls(log_warn_calls)...

Full Screen

Full Screen

bms.py

Source:bms.py Github

copy

Full Screen

1import datetime2import os3import time456def balance_sheet(when):7 if when == '':8 when = datetime.datetime.now().strftime('%d-%m-%y')9 fhand = open('data.txt')10 os.system('cls')11 print('Sno.\t Name \t Date and Time \tCredited/Debited\tNew Balance')12 print('====\t===================\t=====================\t================\t===========')13 c=114 for i in fhand:15 x = i.split('#')16 if x[2] == when:17 print(c,'\t',x[1].strip(),'\t\t',x[2],'',x[3],'\t',x[5],'\t\t\t',x[4])18 c += 119 fhand.close()2021def createaccount():22 os.system('cls')23 name = input('Name of customer')24 fhand = open('accounts.txt')25 print('Select a username please')26 while True:27 cond = True28 username = input('')29 for i in fhand:30 x = i.split('<.>')31 if username == x[0]:32 print('Please choose a different username as this username already exist')33 cond = False34 break35 if cond == True:36 break37 amount = '0'3839 while int(amount) <= 0:40 amount = input('Please deposit some amount of money to get started: ')41 try:42 int(amount)43 except:44 continue45 xim = open('no_acc.txt',"r")46 for i in xim:47 x = int(i)48 break49 acc_num = x+150 xim.close()51 mi = open('no_acc.txt',"w")52 mi.write(str(acc_num))53 mi.close()54 password = input('What should be your password\n*NOTE* Please let the customer write the password by himself/herself and give him/her private space.\n')55 accountstore = open('accounts.txt','a')56 accountstore.write(str(acc_num)+'<.>'+password+'<.>C\n')57 accountstore.close()58 datainput = open('data.txt',"a")59 date = datetime.datetime.now().strftime('%d-%m-%y')60 tym = datetime.datetime.now().strftime('%H:%M:%S')61 principle = amount62 by = 'Bank'63 store = str(acc_num)+'#'+name+'#'+date+'#'+tym+'#'+principle+'#'+amount+'#self#'+by+'\n'64 datainput.write(store)65 datainput.close()66 print('Your account number is: ',acc_num)67 return [str(acc_num),name]68os.system('cls')69while True:70 acc_type = ''71 print('Please enter the following details to get started. If you don\'t have an account and want to create one contact any bank employee')72 print('================================================================================================================================')73 usern = input('Enter your i\'d/account number here: ')74 passw = input('Enter your password here: ')75 fhand = open('accounts.txt',"r")76 passcheck = None77 for i in fhand:78 acc = i.split('<.>')79 if usern.strip() == acc[0]:80 acc_type = acc[2].rstrip()81 passcheck = acc[1]82 if passcheck == passw.strip() and acc_type != '':83 break84 os.system('cls')85 print('Etiher username or password you have entered is wrong')86os.system('cls')87while acc_type == 'B':88 ip = input('Please enter number corresponding to your work: \n1.Specific day\'s balance sheet \n2.Today\'s balance sheet\n3.Balance sheet of a customer\n4.Create an account of customer\n')89 if ip == '1':90 os.system('cls')91 when = input('Which date entries do you need?')92 balance_sheet(when)93 log = usern+'checked the balance sheet for '+when+' on '+datetime.datetime.now().strftime('%d-%m-%y at %H:%d:%S')+'####\n'94 log_check = open('data.txt','a')95 log_check.write(log)96 log_check.close()97 break98 elif ip == '2':99 balance_sheet('')100 log = usern+' checked the balance sheet for '+datetime.datetime.now().strftime('%d-%m-%y')+' on '+datetime.datetime.now().strftime('%d-%m-%y at %H:%d:%S')+'####\n'101 log_check = open('data.txt','a')102 log_check.write(log)103 log_check.close()104 break105 elif ip == '3':106 acc_num = input('Enter account number of customer\t')107 info = open('data.txt')108 os.system('cls')109 print('Sno.\tTransaction through\t Date and Time \tCredited/Debited\tNew Balance')110 print('====\t===================\t=====================\t================\t===========')111 c=1112 for i in info:113 x = i.split('#')114 if x[0] == acc_num:115 name = x[1]116 print(c,'\t',x[7].strip() if x[6] == 'self' else x[6],'\t\t\t',x[2],'',x[3],'\t',x[5],'\t\t\t',x[4])117 c += 1118119 print('The balance sheet of Mr./Mrs.',name)120 log = usern+' checked the balance sheet of account number '+acc_num+' on '+datetime.datetime.now().strftime('%d-%m-%y at %H:%d:%S')+'####\n'121 log_check = open('data.txt','a')122 log_check.write(log)123 log_check.close()124 break125 elif ip == '4':126 x = createaccount()127 log = usern+' created an account for Mr./Mrs. '+x[1]+' with account number '+x[0]+' on '+datetime.datetime.now().strftime('%d-%m-%y at %H:%d:%S')+'####\n'128 log_check = open('data.txt','a')129 log_check.write(log)130 log_check.close()131 break132 else:133 os.system('cls')134 print('!!!->Enter a valid input<-!!!')135136while acc_type == 'C':137 ip = input('Please enter a number corresponding to your work: \n1.Withdraw or Deposit Money\n2.Check Balance\n3.Mini statement\n4.Money Transfer\n5.Password change\n')138 if ip == '1':139 os.system('cls')140 fhand = open('data.txt',"r")141 acc_num = usern.strip()142 for i in fhand:143 if i[:16] == acc_num:144 info = i145 data = info.split('#')146 fhand.close()147 con = input('Confirm name by pressing any key other than \'NO\'\n'+data[1]+'\n')148 if con in ['NO','no','No','nO']:149 print('Try again then')150 os.startfile('bms.py')151 exit()152 date = datetime.datetime.now().strftime('%d-%m-%y')153 tym = datetime.datetime.now().strftime('%H:%M:%S')154 amount = input('amount')155 if amount[0] == '-' and amount > data[4]:156 print('Not enough money in your account.')157 time.sleep(4)158 print('Leaving...')159 time.sleep(4)160 break161 principle = str(int(data[4])+int(amount))162 by = input('By what means:')163 store = acc_num+'#'+data[1]+'#'+date+'#'+tym+'#'+principle+'#'+amount+'#self'+'#'+by+'\n'164 os.system('cls')165 print('Please confirm the below given info: \nYou are Mr./Mrs.',data[1],'\b.Your account number is',acc_num,'you are',"withdrawing ₹" if amount[0]== '-' else "depositing ₹",amount[1:] if amount[0] in ['+','-'] else amount,'\nEnter \'YES\' to confirm\n')166 check = input('Enter YES to confirm or any other key to cancel the transaction\t')167 if check.lower() != 'yes':168 print('Transaction failed!')169 check = input('Do you want to withdraw/deposit money now?\nTo confirm enter YES or any other key to quit\t')170 if check.lower() == 'yes':171 continue172 else:173 print('quiting...')174 time.sleep(2)175 print('Thanks')176 time.sleep(2)177 quit()178 time.sleep(0.5)179 print('processing...')180 time.sleep(2)181 storing = open('data.txt',"a")182 storing.write(store)183 print('Transaction successfull!')184 storing.close()185 break186 elif ip == '2':187 os.system('cls')188 acc_num = usern189 fhand = open('data.txt')190 for i in fhand:191 if i[:16] == acc_num:192 info = i193 data = info.split('#')194 print('Welcome Mr./Mrs.',data[1],'Your last transaction was on',data[2],data[3],'you debited ₹' if data[5][0] == '-' else 'you credited ₹',data[5][1:] if data[5][0] == '-' else data[5] ,'\b. Now your total balance is ₹',data[4],'\nThanks')195 input('press Enter to exit')196 break197 elif ip == '3':198 acc_num = usern199 info = open('data.txt')200 os.system('cls')201 print('Sno.\tTransaction through\t Date and Time \tCredited/Debited\tNew Balance')202 print('====\t===================\t=====================\t================\t===========')203 c=1204 for i in info:205 x = i.split('#')206 if x[0] == acc_num:207 print(c,'\t',x[7].strip() if x[6] == 'self' else x[6],'\t\t\t',x[2],'',x[3],'\t',x[5],'\t\t\t',x[4])208 c += 1209 break210 elif ip == '4':211 acc_num = usern212 send_to = input('Enter the account number of the person you need to send money.\t')213 amount = input('How much money do you want to transfer?\t')214 if int(amount) <1:215 print('Not Valid!')216 break217 fhand = open('data.txt')218 to = ''219 for i in fhand:220 if i[:16] == acc_num:221 info = i222 if i[:16] == send_to:223 to = i224 if to == '':225 print('Account number you have entered is wrong.\nLeaving')226 time.sleep(5)227 quit()228 fhand.close()229 data = info.split('#')230 address = to.split('#')231 by = input('By what means are you going to pay?')232 if int(amount) > int(data[4]):233 print('You don\'t have enough money in your account to make this payment.')234 time.sleep(4)235 print('leaving...')236 break237 date = datetime.datetime.now().strftime('%d-%m-%y#%H:%M:%S')238 principle = str(int(data[4])-int(amount))239 store = acc_num+'#'+data[1]+'#'+date+'#'+principle+'#-'+amount+'#'+send_to+'#'+by+'\n'+send_to+'#'+address[1]+'#'+date+'#'+str(int(address[4])+int(amount))+'#'+amount+'#'+acc_num+'#'+by+'\n'240 os.system('cls')241 print('Confirm the following statement:\nYou are Mr./Mrs.',data[1],',your account number is',acc_num,'you are going to transfer ₹',amount,'to Mr./Mrs.',address[1],'account with account number',send_to,'\nPress Enter to continue any other key to exit')242 check = input('')243 if check != '':244 print('Exiting the transfer!')245 print('leaving...')246 break247 print('processing')248 storing = open('data.txt',"a")249 storing.write(store)250 time.sleep(1.5)251 print('Transfer succesfull')252 break253 elif ip == '5':254 os.system('cls')255 while True:256 check = True257 acc_num = usern258 pa = input('Enter your new password here:\t')259 con = input('Confirm your new password here:\t')260 fhand = open('accounts.txt')261 if pa != con:262 os.system('cls')263 print('New passwords not match! Please do it again')264 continue265 for i in fhand:266 x = i.split('<.>')267 if x[0] == usern and pa == x[1]:268 chec = False269 os.system('cls')270 print('New password can\'t be one of the previous passwords')271 break272 fhand.close()273 if check == True:274 appe = open('accounts.txt','a')275 appe.write(acc_num+'<.>'+pa+'<.>C\n')276 else: ...

Full Screen

Full Screen

ManReport.py

Source:ManReport.py Github

copy

Full Screen

1"""2* Title: ManReport.py3* Project: ManEz4* Team: TAP2J5* Report Module6* Description: Module with all the reporting functions7* Date: 21 Feb 20218* Last Created by: Jay Shin9* Edit History: 25 Feb 2021 - Jay Shin10* v1.0: Creating all the function.11 10 March 2021 - Jay Shin12 v1.5: wrap up.13 11 March 2021 - Jay Shin14 v2.0: Add employee managing function.15"""16import datetime17import ManDB18'''19 This is report module20 Whenever user request report from one of these functions21 this module returns analysis of input date period22'''23def get_sale_list(start_date, end_date):24 """25 This function read all receipts in input date period26 """27 try:28 receiptdb = ManDB.ReceiptDatabase()29 receiptdb.start_session()30 ret = receiptdb.get_period(start_date, end_date)31 except ValueError:32 print("Invalid Input")33 ret = False34 return ret35def total_sale_by_date(start_date, end_date):36 """37 This function read all the receipts between input dates38 Returns total sale amount by date in range39 """40 sales = get_sale_list(start_date, end_date)41 if sales:42 delta = datetime.timedelta(days=1)43 while start_date <= end_date:44 if sales[start_date]:45 total_sale = sales[start_date][-1][0]46 sales[start_date] = total_sale47 start_date += delta48 return sales49 else:50 print("Invalid Input")51 return False52def total_profit_by_date(start_date, end_date):53 """54 This function read all the receipts between input dates55 Returns total profit made in each date56 """57 sales = get_sale_list(start_date, end_date)58 if sales:59 delta = datetime.timedelta(days=1)60 while start_date <= end_date:61 tot = 0.062 prev_num = 063 for sale in sales[start_date]:64 # check if the sale is still in same order65 if sale.number != prev_num:66 prev_num = sale.number67 tot += sale.price68 sales[start_date] = tot69 start_date += delta70 return sales71 else:72 print("Invalid Input")73 return False74def report_by_item(start_date, end_date):75 """76 This function read all the receipts between input dates77 Returns total amount of each sold item by date in range78 """79 sales = get_sale_list(start_date, end_date)80 if sales:81 delta = datetime.timedelta(days=1)82 while start_date <= end_date:83 item_dic = {}84 for sale in sales[start_date]:85 if sale.orders not in item_dic:86 item_dic[sale.orders] = sale.amount87 else:88 item_dic[sale.orders] += sale.amount89 sales[start_date] = item_dic90 start_date += delta91 return sales92 else:93 print("Invalid Input")94 return False95def report_by_category(start_date, end_date):96 """97 This function read all the receipts between input dates98 Returns total amount of each sold category by date in range99 """100 sales = get_sale_list(start_date, end_date)101 if sales:102 delta = datetime.timedelta(days=1)103 # reading ItemDatabase to make category check dictionary104 itemdb = ManDB.ItemDatabase()105 itemdb.start_session()106 items = itemdb.read_db()107 category_check = {}108 for item in items:109 category_check[item.name] = item.category110 # Checking and adding category and its amount111 while start_date <= end_date:112 category_dic = {}113 for sale in sales[start_date]:114 category = category_check[sale.orders]115 if category not in category_dic:116 category_dic[category] = sale.amount117 else:118 category_dic[category] += sale.amount 119 sales[start_date] = category_dic120 start_date += delta121 return sales122 else:123 print("Invalid Input")124 return False125def daily_worktime_report(name, start_date, end_date):126 """127 This function read all the employee log data between input dates128 Returns total amount of individual work time by date in range129 """130 if isinstance(name, str):131 delta = datetime.timedelta(days=1)132 # reading WorkTimeDatabase133 wtdb = ManDB.WorkTimeDatabase()134 wtdb.start_session()135 wts = wtdb.read_db()136 log_check = {}137 for wt in wts:138 if wt.name == name:139 if wt.date not in log_check:140 log_check[wt.date] = wt.work_time141 else:142 log_check[wt.date] += wt.work_time143 else:144 print("Invalid Input")145 return False146 # Checking and adding worktime and its sum147 ret_dic = {}148 while start_date <= end_date:149 if start_date in log_check:150 ret_dic[start_date] = log_check[start_date]151 start_date += delta152 return ret_dic153 else:154 print("Invalid Input")155 return False156def total_worktime_report(name, start_date, end_date):157 """158 This function read all the employee log data between input dates159 Returns total amount of individual work time by input period160 """161 if isinstance(name, str):162 delta = datetime.timedelta(days=1)163 # reading WorkTimeDatabase164 wtdb = ManDB.WorkTimeDatabase()165 wtdb.start_session()166 wts = wtdb.read_db()167 log_check = {}168 for wt in wts:169 if wt.name == name:170 if wt.date not in log_check:171 log_check[wt.date] = wt.work_time172 else:173 log_check[wt.date] += wt.work_time174 else:175 print("Invalid Name")176 return False177 # Checking and adding worktime to get total178 ret = {}179 while start_date <= end_date:180 if start_date in log_check:181 ret = log_check[start_date]182 start_date += delta183 while start_date <= end_date:184 if start_date in log_check:185 ret += log_check[start_date]186 start_date += delta187 return ret188 else:189 print("Invalid Input")190 return False191def pay_employee(name, wage, start_date, end_date):192 """193 calculate total payment for the employee194 wage must be bigger than zero195 """196 if isinstance(name, str):197 if wage > 0.0:198 wt = total_worktime_report(name, start_date, end_date)199 # datetime delta need to be changed into seconds200 # to calculate hours and minutes201 wtsec = wt.seconds202 wthour = wtsec // 3600203 wtmin = (wtsec // 60) % 60204 wt = wthour + (wtmin / 60)205 pay = wage * wt206 return pay207 else:208 print("Invalid Wage")209 return False 210 else:211 print("Invalid Name")...

Full Screen

Full Screen

banking.py

Source:banking.py Github

copy

Full Screen

1import random2import sqlite334connection = sqlite3.connect('card.s3db')5cur = connection.cursor()6card_number, pin, log_check = [], 0, 0789def main():10 global log_check11 while True:12 if log_check == 0:13 if not main_menu():14 break15 elif log_check == 1:16 if not log_menu():17 break181920def create_account():21 global card_number, pin22 card_number = list("400000{0}".format(random.randint(100000000, 999999999)))23 luhn_algorithm(card_number, "create")24 pin = random.randint(1000, 9999)25 cur.execute("INSERT INTO card (number, pin) VALUES ({0}, {1})".format(card_number, pin))26 connection.commit()27 print("\nYour card has been created\nYour card number:\n{0}\nYour card PIN:\n{1}\n".format(card_number, pin))282930def log():31 global card_number, pin, log_check32 print("\nEnter your card number:")33 check_card = int(input())34 print("Enter your PIN:")35 check_pin = int(input())36 cur.execute("SELECT number FROM card WHERE number = {0};".format(check_card))37 if bool(cur.fetchone()):38 cur.execute("SELECT number, pin FROM card WHERE number = {0};".format(check_card))39 card_db, pin_db = cur.fetchone()40 if check_card == int(card_db) and check_pin == int(pin_db):41 print("\nYou have successfully logged in!\n")42 log_check, card_number, pin = 1, card_db, pin_db43 else:44 print("\nWrong card number or PIN!\n")45 else:46 print("\nWrong card number or PIN!\n")474849def main_menu():50 print("1. Create an account\n2. Log into account\n0. Exit")51 number = int(input())52 if number == 1:53 create_account()54 elif number == 2:55 log()56 elif number == 0:57 print("\nBye!")58 return False59 return True606162def log_menu():63 global log_check64 print("1. Balance\n2. Add income\n3. Do transfer\n4. Close account\n5. Log out\n0. Exit")65 number = int(input())66 if number == 1:67 balance()68 elif number == 2:69 add_income()70 elif number == 3:71 do_transfer()72 elif number == 4:73 close_account()74 elif number == 5:75 print("\nYou have successfully logged out!\n")76 log_check = 077 elif number == 0:78 print("\nBye!")79 return False80 return True818283def luhn_algorithm(card_n, act):84 global card_number85 checksum, sum_v, card_str, card_copy = 0, 0, "", list(card_n)86 if act == "transfer":87 card_copy.pop()88 card_copy = [int(card_copy[x]) for x in range(len(card_copy))]89 card_copy = [card_copy[x] * 2 if x % 2 == 0 else card_copy[x] for x in range(len(card_copy))]90 card_copy = [card_copy[x] - 9 if card_copy[x] > 9 else card_copy[x] for x in range(len(card_copy))]91 for x in range(len(card_copy)):92 sum_v += card_copy[x]93 while True:94 if sum_v % 10 == 0:95 break96 else:97 sum_v += 198 checksum += 199 if act == "create":100 card_number.append(checksum)101 card_number = [str(card_number[x]) for x in range(len(card_number))]102 for x in range(len(card_number)):103 card_str += card_number[x]104 card_number = int(card_str)105 return True106 elif act == "transfer":107 if checksum == int(card_n[-1]):108 return True109 else:110 return False111112113def balance():114 cur.execute("SELECT balance FROM card WHERE number = {0};".format(card_number))115 print("\nBalance: {0}\n".format((cur.fetchone())[0]))116117118def add_income():119 print("\nEnter income:")120 income = int(input())121 cur.execute("UPDATE card SET balance = balance + {0} WHERE number = {1};".format(income, card_number))122 connection.commit()123 print("Income was added!\n")124125126def do_transfer():127 print("\nTransfer\nEnter card number:")128 card_n = int(input())129 cur.execute("SELECT number FROM card WHERE number = {0};".format(card_n))130 if card_n == card_number:131 print("You can't transfer money to the same account!\n")132 return True133 elif not luhn_algorithm(list(str(card_n)), "transfer"):134 print("Probably you made a mistake in the card number. Please try again!\n")135 return True136 elif not bool(cur.fetchone()):137 print("Such a card does not exist.\n")138 return True139 print("Enter how much money you want to transfer:")140 money = int(input())141 cur.execute("SELECT balance FROM card WHERE number = {0};".format(card_number))142 if (cur.fetchone())[0] < money:143 print("Not enough money!\n")144 return True145 cur.execute("UPDATE card SET balance = balance + {0} WHERE number = {1};".format(money, card_n))146 connection.commit()147 cur.execute("UPDATE card SET balance = balance - {0} WHERE number = {1};".format(money, card_number))148 connection.commit()149 print("Success!\n")150151152def close_account():153 global log_check, card_number154 print("\nThe account has been closed!\n")155 cur.execute("DELETE FROM card WHERE number = {0};".format(card_number))156 connection.commit()157 log_check, card_number = 0, []158159 ...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Lemoncheesecake automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful