Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python...testing classes?

Tags:

python

testing

In python, how do we write test cases for our classes? For example:

class Employee(object):
  num_employees = 0


# numEmployess is incremented each time an employee is constructed
  def __init__(self, salary=0.0, firstName="", lastName="", ssID="", DOB=datetime.fromordinal(1), startDate=datetime.today()): #Employee attributes
    self.salary=salary
    self.firstName = firstName
    self.lastName = lastName
    self.ssID = ssID
    self.DOB = DOB
    self.startDate = startDate
    Employee.num_employees += 1 #keep this 

  def __str__(self): #returns the attributes of employee for print
    return str(self.salary) + ', ' + self.firstName + ' ' + self.lastName + ', ' + self.ssID + ', ' + str(self.DOB) + ', ' + str(self.startDate)

I know there is something called unit testing. But I'm not sure how it works at all. Could not find a good explanation I understood online.

like image 827
VPNTIME Avatar asked May 10 '12 00:05

VPNTIME


People also ask

How do I test a class in Python?

First you need to create a test file. Then import the unittest module, define the testing class that inherits from unittest. TestCase, and lastly, write a series of methods to test all the cases of your function's behavior. First, you need to import a unittest and the function you want to test, formatted_name() .

What is testing in Python?

Unit testing is a method for testing software that looks at the smallest testable pieces of code, called units, which are tested for correct operation. By doing unit testing, we can verify that each part of the code, including helper functions that may not be exposed to the user, works correctly and as intended.


1 Answers

doctest is the simplest. Tests are written in the docstring, and look like REPL episodes.

 ...

  def __str__(self):
    """Returns the attributes of the employee for printing

    >>> import datetime
    >>> e = Employee(10, 'Bob', 'Quux', '123', startDate=datetime.datetime(2009, 1, 1))
    >>> print str(e)
    10, Bob Quux, 123, 0001-01-01 00:00:00, 2009-01-01 00:00:00
    """
    return (str(self.salary) + ', ' +
            self.firstName + ' ' + 
            self.lastName + ', ' +
            self.ssID + ', ' + 
            str(self.DOB) + ', ' +
            str(self.startDate)
            )

if __name__ == '__main__':
  import doctest
  doctest.testmod()
like image 193
Ignacio Vazquez-Abrams Avatar answered Sep 19 '22 01:09

Ignacio Vazquez-Abrams