Having some trouble figuring out the correct, python 2.x preferred way to do relative imports so that I can keep test scripts together in one subpackage, and have those test scripts be able to test my library.
$ farm\testpad\testpad.py
Traceback (most recent call last):
File "C:\farm\testpad\testpad.py", line 4, in <module>
from ..animals.dog import dog
ValueError: Attempted relative import in non-package
$ python -m farm\testpad\testpad
C:\Python27\python.exe: No module named farm\testpad\testpad
In the following example, what do I need to modify to do what I want? Please, and thanks for any help given.
e.g.
Package structure:
farm/
__init__.py # empty
animals/
__init__.py # empty
dog.py
testpad/
__init__.py # empty
testpad.py
dog.py
import sys
import os
class dog():
def __init__(self, name):
self.name = name
def speak(self):
print "woof"
testpad.py
import os
import sys
from ..animals.dog import dog
# create a dog and test its speak action
def testpad():
d = dog("Allen")
d.speak()
if __name__ == "__main__":
testpad()
Three things:
-m
option forpython
expects module in dotted formApplying this to your code
Modify
testpad.py
Call it from
python -m <module>
Bonus - testing from
nose
For my testing I use following pattern
test
or bettertests
nose
testing frameworkBeing in root of your project
Install
nose
:What creates a command
nosetests
Reorganize your code
Run the tests (currently just one)
The simples way, wich does the work, but tries to keep the output minimal:
As you see, nose is discovering test cases on his own (searching for whatever starts with
test
)Make it a bit more verbose:
Now you know, what tests were run.
To see captured outut, use
-s
switch:Add more tests to
test_animals.py
Test it:
Add
--pdb
switch to jump to debugger (if you installipdbplugin
, you might use--ipdb
):Use
h
or find some tutorial for debugger, it is great toolReal test cases shall assert that behaviour is as expected.
Assert printed values are as expected
As you are printing to stdout, we can capture the output using mocking (in Python 2.x you have to install it, in Python 3.x you
from unittest import mock
):And modify your
test_animals.py
:Final test case of my taste
test_mytaste.py
This requires you refactor your code (class names starting uppercase,
speak
method not printing but returning the sound).In fact, you may start writing your code from test cases and adding tested modules later on, this often leads to nicer design as you start thinking of real use from the very beginning.
Selective call of test cases
nose is great in searching for test cases (generally whatever starts with
test
), but sometime you might focus on particular test or use differently named python file. You can tellnose
to use just one test file:or even target
nose
to run specific test from it: