I am learning python and wrote a program to understand about testing code.
Code 1:
import pytest
class Employee:
"""Represent an employee"""
def __init__(self, f_name, l_name, salary):
self.f_name = f_name.title()
self.l_name = l_name.title()
self.salary = salary
def give_raise(self, amount = 5000):
"""Give the employee a raise"""
self.amount = amount
self.r_salary = self.salary + self.amount
@pytest.fixture
def make_employee():
"""Creates an instance of an employee"""
employee = Employee('wolfgang', 'mozart', 1_00_000_000)
return employee
def test_give_default_raise(make_employee):
"""Test that a default raise works properly"""
make_employee.give_raise()
assert make_employee.r_salary == (make_employee.salary + make_employee.amount)
def test_give_custom_raise(make_employee):
"""Test that a custom raise works properly"""
make_employee.give_raise(amount= 10_000)
assert make_employee.r_salary == (make_employee.salary + make_employee.amount)
Code 2:
class Employee:
"""Represent an employee"""
def __init__(self, f_name, l_name, salary):
self.f_name = f_name.title()
self.l_name = l_name.title()
self.salary = salary
def give_raise(self, amount = 5000):
"""Give the employee a raise"""
self.amount = amount
self.r_salary = self.salary + self.amount
def make_employee():
"""Creates an instance of an employee"""
employee = Employee('wolfgang', 'mozart', 1_00_000_000)
return employee
def test_give_default_raise(func = make_employee):
"""Test that a default raise works properly"""
make_employee.give_raise()
assert make_employee.r_salary == (make_employee.salary + make_employee.amount)
def test_give_custom_raise(func = make_employee):
"""Test that a custom raise works properly"""
make_employee.give_raise(amount= 10_000)
assert make_employee.r_salary == (make_employee.salary + make_employee.amount)
Question 1: Why does Code 2 fail the pytest? What am I doing wrong?
My purpose for writing Code 2 was that I was curious about an alternative way to pass a function as an argument in the definition of a test function without using fixtures. So with that in mind –
Question 2: What modifications do I need to do to fulfill the above purpose?
6