class TestEmp(unittest.TestCase): @classmethod def setUpClass(cls): # useful to do once set up task only once print("setUpClass") print("I run ONCE at the START of this test suite") @classmethod def tearDownClass(cls): print("tearDownClass") print("I run ONCE at the END of this test suite") def setUp(self): # instance attributes # runs for every test print("setUp") self.emp1 = Employee("Roger", "Ramjet", 100) self.emp2 = Employee("Daisy", "Flower", 200) def tearDown(self): # removes for each test # tear down databases etc here print("tearDown") def test_full_name(self): self.assertEqual(self.emp1.fullname, "Roger Ramjet") self.assertEqual(self.emp2.fullname, "Daisy Flower") self.assertNotEqual(self.emp1.fullname, "Daisy Flower") def test_email(self): self.assertEqual(self.emp1.email, "*****@*****.**") self.assertEqual(self.emp2.email, "*****@*****.**") def test_apply_raise(self): # apply the raise and check it self.emp1.apply_raise() self.assertNotEqual(self.emp1.pay, 100) self.assertEqual(self.emp1.pay, 105) self.assertEqual(self.emp2.pay, 200) self.assertNotEqual(self.emp2.pay, 210) def test_monthly_sched(self): # mock out calls to things which are out of our control, # or resource intensive. We are testing our code not the endpoint etc. with patch("emp.requests.get") as mocked_get: mocked_get.return_value.ok = True mocked_get.return_value.text = "Success" sched = self.emp1.get_schedule("May") mocked_get.assert_called_with("https://website.com/Ramjet/May") self.assertEqual(sched, "Success") mocked_get.return_value.ok = False mocked_get.return_value.text = "Bad response!" sched = self.emp2.get_schedule("October") mocked_get.assert_called_with("https://website.com/Flower/October") self.assertEqual(sched, "Bad response!")
def add_one(self, emp_id, emp_name, emp_phone, emp_bdate): emp = Employee(emp_id, emp_name, emp_phone, emp_bdate) self.emp_dict[emp.id] = emp # add to dict where key = emp_id self.first_row_ind = False # emp1 = Employee.create_emp_row(emp) self.append_new_row( emp.format_emp_row() ) # save to file with create_emp_row that create a list with the values to insert
def createEmployee(records): # Gather inputs to create employee object firstName = input("Employee first name: ") lastName = input("Employee last name: ") employeeID = input("Employee ID Number: ") status = input("Employment status (pt, ft, hourly): ") payRate = input("Pay Rate (ft in annual terms, pt in rate per class, hourly in rate per hour): ") # Create employee record and set key for dictionary storage emp = Employee(firstName, lastName, employeeID, status, payRate) empRec = emp.addRecord(firstName, lastName, employeeID, status, payRate) records[employeeID] = empRec print("\n Employee Record Added.") return records
def getEmployeeInfo(records): try: # Retrieve employee information employeeID = input("What is the ID number of the employee? ") record = records.get(employeeID) # Generate employee firstName, lastName, employeeID, status, payRate = record[0], record[1], record[2], record[3], record[4] emp = Employee(firstName, lastName, employeeID, status, payRate) # Request employee info empInfo = emp.employeeInfo(firstName, lastName, employeeID, status, payRate) # Return employee info print(empInfo) except: print("Error: Please enter a valid employee ID.")
def add_bulk( self, in_file ): # will get the input csv name frorm the user and peform a loop that will send every line to Employee.create_new with open(in_file, "r") as f: for line in f: id, name, phone, bdate = line.strip().split( ',') #split each line by "," to columns if id in self.emp_dict: # verify that employee doesn't exists in the file print('Employee already exists', id, name) # here enter insert to error file, and continue loop continue success = self.check_validity(phone=phone) if not success: print('invalid phone', id, phone) break success = self.check_validity(bdate=bdate) if not success: print('invalid bdate', id, bdate) break emp_obj = self.emp_dict[id] = Employee(id, name, phone, bdate) self.append_new_row( emp_obj.format_emp_row() ) # save to file with create_emp_row that create a list with the values to insert
def load_data(self): with open(self.csvfile_emp, "r+") as f: for line in f: id, name, phone, bdate = line.strip().split( ',') #split each line by "," to columns self.emp_dict[id] = Employee( id, name, phone, bdate ) # insert into dictionary where id is the key and other values is a list self.first_row_ind = False
def getPayRate(records): try: # Retrieve employee information employeeID = input("What is the ID number of the employee? ") record = records.get(employeeID) # Generate employee firstName, lastName, employeeID, status, payRate = record[0], record[1], record[2], record[3], record[4] emp = Employee(firstName, lastName, employeeID, status, payRate) # Calculate Gross Pay grossPay = emp.calculatePay(status, payRate) # Return Gross Pay info dependent on employment status if status == "ft": print("$", grossPay, " per month, at $", payRate, " per year.", sep="") elif status == "pt": print("$", grossPay, ", at $", payRate, " per class.", sep="") elif status == "hourly": print("$", grossPay, ", at $", payRate, " per hour.", sep="") except: print("Error: Please enter a valid employee ID.")
def main(): e1 = Employee(101, 'Annie') print("object is ready") try: Serialization.file = open("abc.txt", mode='wb') pickle.dump(e1, Serialization.file) print("Serialized") except Exception as msg: print("Error:", msg) finally: if Serialization.file != None: Serialization.file.close() return
def load_emp(): with open('emp.txt') as f: data = f.readlines() for l in data: lst = l.strip('\n').split(',') eid = lst[0] name = lst[1] qual = lst[2] sal = lst[3] dept = lst[4] emp1 = Employee(eid, name, qual, sal, dept) lst_emp.append(emp1) print(len(lst_emp))
def delEmployee(records): try: # Retrieve employee information employeeID = input("What is the ID number of the employee? ") record = records.get(employeeID) # Generate employee firstName, lastName, employeeID, status, payRate = record[0], record[1], record[2], record[3], record[4] emp = Employee(firstName, lastName, employeeID, status, payRate) # Verify employee info verifyDelStr = "Are you sure you want to delete " + firstName + " " + lastName + ", ID: " + employeeID + ", from records (y/n)?" verifyDel = input(verifyDelStr) # If yes, remove employee record if verifyDel[0] in "Yy": del records[employeeID] print("Record Deleted.") except: print("Error: Please enter a valid employee ID.")
from emp import Employee import pickle with open('emp.det', 'wb') as f: while True: # we want add multiple emp data so we use while loop. eNo = int(input('enter emp no:')) eName = input('enter the emp name:') eSal = float(input('enter the sal:')) eAddr = input('enter the emp addr:') e = Employee( eNo, eName, eSal, eAddr) # we get dynamic type input,so we have to creat object pickle.dump(e, f) #that created object we have to send emp.det file option = input('if you want add more employee [yes/no]:') if option.lower() == 'no': break print('all emp object serialization...')
import sys sys.path.append("C:/Users/shaik/PycharmProjects/pythonBasics/pack1") sys.path.append("C:/Users/shaik/PycharmProjects/pythonBasics/pack4") from emp import Employee from deptmodule import * e = Employee(100, "suri", 50000) e.displayemp() display()
# Andrew Hein # Advanced Programming - Week 8 # 2021/3/15 # emp_test.py from emp import Employee employees = [ Employee("Susan Meyers", 47899, "Accounting", "Vice President"), Employee("Mark Jones", 39119, "IT", "Programmer"), Employee("Joy Rogers", 81774, "Manufacturing", "Engineer") ] for num in range(0, len(employees)): print("Employee {}:\n{}\n".format(num + 1, employees[num]))
def test_pay_tax_no_pay(self): nopay = Employee("Claudio", 22, 30000).pay_tax() self.assertEqual(nopay, "No paga impuestos")
import sys sys.path.append("C:/Users/shaik/PycharmProjects/pythonBasics/pack1") sys.path.append("C:/Users/shaik/PycharmProjects/pythonBasics/pack1/pack1sub1") sys.path.append("C:/Users/shaik/PycharmProjects/pythonBasics/pack2") from emp import Employee e = Employee(101, "scott", 40000) e.displayemp() import stu stu.display() import pack2.stu #since there are 2 stu modules in different packages,we need to specify package name for differenciate s = pack2.stu.Student(101, "abc", "A") s.displaystu()
def __init__(self, name, salary, experience, manager, effectiveness): Employee.__init__(self, name, salary, experience, manager) self.effectiveness = effectiveness
def test_email(self): empt1 = Employee('TESTER1','LA',13,300,41) empt2 = Employee('TESTER2','LA',13,2000,32) self.assertEqual(empt1.email_add, '*****@*****.**') self.assertEqual(empt2.email_add, '*****@*****.**')
# import base class Employee using the concept of inheritance from emp import Employee # create a child class class Fulltime(Employee): # define the default constructor for the class and pass the arguments def __init__(self,name,family,salary,department): Employee.__init__(self, name, family, salary, department) def working_hours(self,start,end): print("{} working hours today are {} a.m to {} p.m".format(self._n,start,end)) if __name__ == "__main__": # create a instance and pass the parameters to base class x=Employee("sravs",{'wife':5000,'child':2000},7899,"Account") x.avg_sal() x.insurance_details() # create an instance and pass the parameters to child class y= Fulltime("sandy",{'wife':5000,'child':2000},9999, "Management") y.avg_sal() # print the insurance details y.insurance_details() y. working_hours(8,4)
def __init__(self,name,family,salary,department): Employee.__init__(self, name, family, salary, department)
def setUp(self): # instance attributes # runs for every test print("setUp") self.emp1 = Employee("Roger", "Ramjet", 100) self.emp2 = Employee("Daisy", "Flower", 200)
def test_fullname(self): empt1 = Employee('TESTER1','LA',13,300,41) empt2 = Employee('TESTER2','LA',13,2000,32) self.assertEqual(empt1.full_name, 'TESTER1 LA') self.assertEqual(empt2.full_name, 'TESTER2 LA')
def test_get_employee(self, name, age, surname, phone, salary, result): employee1 = Employee(name, age, surname, phone, salary) listEmployee = employee1.get_employee() self.assertEqual(listEmployee, result)
def test_yearlysalary(self): empt1 = Employee('TESTER1','LA',13,300,41) self.assertEqual(empt1.yearly_salary(),3600) empt2 = Employee('TESTER1','LA',13,0,32) with self.assertRaises(ValueError): #context manager: can be used for testing exceptions empt2.yearly_salary()
from emp import Employee if __name__ == '__main__': emp1 = Employee(1, 'Shash', 'BE', 30000, 'IS') emp2 = Employee(2, 'abcd', 'MTech', 50000, 'CS') emp1.show_info() emp2.increment_sal(2000) emp2.show_info()
def __init__(self, name, salary, experience, manager): Employee.__init__(self, name, salary, experience, manager)
def __init__(self, name, salary, experience, manager): Employee.__init__(self, name, salary, experience, manager) self.team_of_managers = []
#Sender is responsible to save Employee objects to the file import pickle from emp import Employee f = open('emp.dat', 'wb') while True: eno = int(input('Enter the employee Number: ')) ename = input('Enter the employee Name: ') esal = float(input('Enter the employee Salary: ')) eaddr = input('Enter the employee adress: ') e = Employee(eno, ename, esal, eaddr) pickle.dump(e, f) option = input('Do you want to enter some more Employee object [Yes|No]:') if option.lower() == 'no': break print() print('All employees serialized...')
def fake_absences(date_of_empl): init_date = random_date(date_of_empl, date_str(datetime.date.today())) init_date = datetime.datetime.strptime(init_date, '%Y-%m-%d') if (randrange(1) == 0): # 30 dias end_date = init_date + datetime.timedelta(days=30) else: # 15 dias end_date = init_date + datetime.timedelta(days=15) return date_str(init_date), date_str(end_date) empl_list = [] for i in range(AMOUNT): empl = Employee(fake_employee_number(empl_list)) empl.set_telephone(fake_telephone()) f_name, m_name, l_name = fake_employee_name() empl.set_name(f_name, m_name, l_name) addr_desc, addr_city, addr_state, addr_zip = fake_address() empl.set_address(addr_desc, addr_city, addr_state, addr_zip) pos_title, pos_hours, pos_dt = fake_position() pos_salary = fake_salary() empl.set_position(pos_title, pos_salary, pos_hours, pos_dt) for i in range(randrange(3)): ab_init, ab_end = fake_absences(empl.position['date_of_employment'])
from emp import Employee # declare an empty list empList = list() # append instances of class to the empList empList.append(Employee(100, "Praveen", 4500, "Bangalore")) empList.append(Employee(200, "Vydehi", 5000, "Hyd")) empList.append(Employee(300, "Naveen", 5500, "Chennai")) # print employee list using membership operator 'in' for i in empList: print("List values are ", i.eno, i.ename, i.esal, i.eAddr) print("*" * 25) # print employee list using instance attributes for i in range(len(empList)): print(empList[i].eno, empList[i].ename, empList[i].esal, empList[i].eAddr) i = i + 1
def test_pay_tax_pay(self): pay = Employee("Nicole", 20, 50000).pay_tax() self.assertEqual(pay, "Paga impuestos")