**Basics. **
Classes, variables and functions
Classes and variables should be named as nouns. Classes get a capital letter and variables are lowercase with underscores
functions are lowercase verbs with underscores.
PEP-8 has more specifics
Docstrings
placed at the beginning of a module, function or class. As long as it’s the first thing, Python will interpret it as a docstring
def find_words(text, word):
__”"”doc string can span multiple lines”””
accessible in code with the __doc__ attribute.
Docstrings should:
describe what the function does - preferably in one sentence
explain the arguments
explain the return value
include any expected exceptions
Docutils
Certainly seems pretty handy and should probably be learned.
Restructured text looks cool.
Sphinx looks better.
Doctests
places tests in the documentation string of any module, class, function, etc.
Pretty limited, I don’t think I’m interested in this just yet.
def times2(value):
__”””
__multiplies everything by 2. Be it a number, list
__or tuple
__>>> times2(5)
__10
__>>> times2(‘test’)
__‘testtest’
__>>> times2((‘a’, 1))
__(‘a’, 1, ‘a’, 1)
__”””
__ return value * 2
if __name__ == ‘__main__’:
__import doctest
__doctest.testmod()
unittest module basics
generally means esstablish values, make connections to dbs, open files, load data.
values that setUp defines cannot be returned, they must be attached to the object itself.
Tests are mthods on this object.
import unittest
class MultTestcase(unittest.TestCase):
__def setUp(self):
____self.factor = 2
Writing tests for unittest
no single method that must implement all the tests.
the framework looks at your test case class for methods whose names start with test
for each of these methods, the framework executes setUp() before executing the test method.
utility methods describe how the code is supposed to work. These are inherited from unittest.TestCase. Each represents a condition that must be true in order to continue:
More unittest.TestCase methods
17 methods
Testing exceptions - verify unsuccessful outcomes.
Testing identity - checks if two objects are the same, not just equivalent values
Handy for when you cache some stuff. Can test if value returned from cache is the same value that was placed in it rather than an equivalent copy.
Tearing down a test case
tearDown() is conducted by a unittest.TestCase object when it’s tests have been run.
If writing to a DB or some other outside source is necessary for the tests, this allows you to undo all that.