I am very new to unit testing and writing/using exceptions. I am currently making a huge effort to learning about best practices and integrating them into my projects. As a test of some things I have been reading about I wrote a simple Contracts module. Below is the init of the contract class which has several arguments that depend on each other.
How would/should I write a test for the init method based on its argument dependencies.
Thanks in advance!
def __init__(self, code, description ,contract_type,
start_date ,end_date ,reminder_date,
customer=None, isgroup=False, vendor=None,
discount_perc=None):
contract_types = ['item','vendor']
self.code = code
self.description = description
self.contract_type = contract_type
self.start_date = start_date
self.end_date = end_date
self.reminder_date = reminder_date
if contract_type not in contract_types:
raise AttributeError("Valid contract types are 'item' & 'vendor'")
if isgroup:
if customer:
raise AttributeError("Group contracts should not have 'customer' passed in")
self.is_group_contract = True
else:
if customer:
self.add_customer(customer)
else:
raise AttributeError('Customer required for non group contracts.')
if contract_type == 'vendor':
if vendor and discount_perc:
self.vendor = vendor
self.discount_perc = discount_perc
else:
if not vendor:
raise AttributeError('Vendor contracts require vendor to be passed in')
if not discount_perc:
raise AttributeError('Vendor contracts require discount_perc(Decimal)')
If this type of question isn’t a good fit for SO, where might I be better of going?
I’d treat
__init__similar to any other (not class- or static-) method – test expected output based on various input combinations. But in addition to that, I’d also test it for returning (or not returning, depending on the requirements you have) singleton object.However one may prefer to extract singleton tests as the
__new__-related test cases.Eventually you will have tests for:
Another tip: extracting
contract_types = ['item','vendor']to the class attribute will help in business logic tests organization.