编写一个名为Employee的类,其__init__()方法接受名、姓和年薪,并将它们都存储在
属性中。编写一个名为give_raise()的方法,它默认将年薪增加5000美元,同时能够接受其
他的年薪增加量。
为Employee类编写一个测试文件,其中包含两个测试函数:
test_give_default_raise()和test_give_custom_raise()。在不使用夹具的情况下编
写这两个测试,并确保它们都通过了。然后,编写一个夹具,以免在每个测试函数中都创建一
个Employee对象。重新运行测试,确认两个测试都通过了。
编写的Employee类:
employee.py
class Employee:
def __init__(self, name, annual_salary):
self.name = name
self.annual_salary = annual_salary
def give_raise(self, add_salary=5000):
self.annual_salary += add_salary
运行Employee类:
employee_salary.py
from employee import Employee
name = 'Jack'
annual_salary = 1000000
employee_salary = Employee(name, annual_salary)
employee_salary.give_raise()
add_salary = int(input('salary:'))
annual_salary += add_salary
print(f'增加了{add_salary},现在年薪是{annual_salary}')
employee_salary.give_raise()
为Employee类编写的测试文件:
import pytest
import source.employee as employee
def test_give_default_raise():
# 增加薪水为默认值
salary_amount = employee.Employee('Jack', 55000)
salary_amount.give_raise()
assert salary_amount.annual_salary == 60000
def test_give_custom_raise():
# 增加薪水为其他值
salary_amount = employee.Employee('Jack', 55000)
salary_amount.give_raise(10000)
assert salary_amount.annual_salary == 65000
编写一个夹具:
import pytest
import source.employee as employee
@pytest.fixture
def salary_amount():
salary_amount = employee.Employee('Jack', 55000)
return salary_amount
def test_give_default_raise(salary_amount):
# 增加薪水为默认值
salary_amount.give_raise()
assert salary_amount.annual_salary == 60000
def test_give_custom_raise(salary_amount):
# 增加薪水为其他值
salary_amount.give_raise(10000)
assert salary_amount.annual_salary == 65000