Question

I'm trying to write some unittests using trial for my twisted application, I wrote my first 'empty' trial unittest class but when I try to run it I get ImportError for importing my app module.

This is as I suspect because trial changes the current working directory and when I try to import my module with the object class that I want to unittest it fails.

I keep my application modules in a single directory which I set up by myself, it's not in any directory from PYTHONPATH or else known, in my app the modules import other modules since they all are in the same dir.

The code looks similiar to this:

from twisted.trial import unittest
from twisted.spread import pb
from twisted.internet import reactor, protocol 
from MyModule import MyTestSubject

class MyTestSubjectTest(unittest.TestCase):

    def setUp(self):
        print('\nset up')


    def test_startConsoleServer(self):
        ts = MyTestSubject()
        .... # here goes the body of the test


    def tearDown(self):
        print('\ntear down')

So the error msg looks like this:
exceptions.ImportError: No module named MyModule

Maybe this is not the standard way of using trial or deploying a python app.

UPDATE: I just figured out a workaround for this, just append the app directory to sys.path so the imports part will look like this:

from twisted.trial import unittest
from twisted.spread import pb
from twisted.internet import reactor, protocol 
import sys, os; sys.path.append(os.path.abspath(os.path.curdir))
from MyModule import MyTestSubject
Was it helpful?

Solution

How are your modules / packages organised? Perhaps try a structure like the following, then you won't need to do any path hackery:

$ ls -R mypackage
mypackage:
__init__.py  __init__.pyc  mymodule.py  mymodule.pyc  test

mypackage/test:
__init__.py  __init__.pyc  test_mymodule.py  test_mymodule.pyc

run tests from just above the mypackage package dir:

$ trial mypackage
mypackage.test.test_mymodule
  MyModuleTestCase
    test_something ...                                                     [OK]

-------------------------------------------------------------------------------
Ran 1 tests in 0.002s

PASSED (successes=1)

inside file test_mymodule.py:

from twisted.trial import unittest

from mypackage.mymodule import MyTestSubject

class MyModuleTestCase(unittest.TestCase):
    def test_something(self):
        pass
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top