예제 #1
0
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!")
예제 #2
0
 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
예제 #3
0
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
예제 #4
0
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.")
예제 #5
0
    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
예제 #6
0
 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
예제 #7
0
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.")
예제 #8
0
 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
예제 #9
0
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))
예제 #10
0
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.")
예제 #11
0
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...')
예제 #12
0
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]))
예제 #14
0
 def test_pay_tax_no_pay(self):
     nopay = Employee("Claudio", 22, 30000).pay_tax()
     self.assertEqual(nopay, "No paga impuestos")
예제 #15
0
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()
예제 #16
0
 def __init__(self, name, salary, experience, manager, effectiveness):
     Employee.__init__(self, name, salary, experience, manager)
     self.effectiveness = effectiveness
예제 #17
0
 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, '*****@*****.**')
예제 #18
0
# 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)

예제 #19
0
 def __init__(self,name,family,salary,department):
     Employee.__init__(self, name, family, salary, department)
예제 #20
0
 def setUp(self):
     # instance attributes
     # runs for every test
     print("setUp")
     self.emp1 = Employee("Roger", "Ramjet", 100)
     self.emp2 = Employee("Daisy", "Flower", 200)
예제 #21
0
 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')
예제 #22
0
 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)
예제 #23
0
 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()
예제 #24
0
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()
예제 #25
0
 def __init__(self, name, salary, experience, manager):
     Employee.__init__(self, name, salary, experience, manager)
예제 #26
0
 def __init__(self, name, salary, experience, manager):
     Employee.__init__(self, name, salary, experience, manager)
     self.team_of_managers = []
예제 #27
0
#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...')
예제 #28
0
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'])
예제 #29
0
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
예제 #30
0
 def test_pay_tax_pay(self):
     pay = Employee("Nicole", 20, 50000).pay_tax()
     self.assertEqual(pay, "Paga impuestos")