Writing Unit Tests for the __init__ Class Method

I am very new to unit testing and writing / using exceptions. I am currently working hard to learn about best practices and integrate them into my projects. As a test of some of the things I read, I wrote a simple contract module. The following is a contract class initiative that has several arguments that depend on each other.

How 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 is not suitable for SO, where can I be better?

+4
source share
1 answer

I would consider __init__ , like any other (not class- or static-) method - the expected test result based on various input combinations. But in addition to this, I would also check it to return (or not return, depending on the requirements that you have) a Singleton object. However, you might prefer to extradite tests with a singleton test as __new__ related tests.

In the end, you will have tests for:

  • Processing types of invalid arguments (empty / non-empty strings, integers, tuples, voice recorders, etc.).
  • Incorrect handling of argument combinations (in case it occurred due to an exception).
  • Additional arguments: the presence / absence of processing (the default values ​​work, custom ones do the same, etc.).
  • Processing valid combinations of arguments (positive stream works).
  • The resulting attributes of the objects are present / absent and their values ​​(of course, you rely on them in other methods).
  • The resulting object is single-point (or not).
  • ???

One more tip: extracting contract_types = ['item','vendor'] into a class attribute will help in organizing business logic.

+3
source

Source: https://habr.com/ru/post/1395995/


All Articles