ねじれたアプリケーションのトライアルを使用していくつかのユニットテストを作成しようとしています。最初の「空の」トライアルユニットテストクラスを作成しましたが、実行しようとすると、アプリモジュールをインポートするために ImportError が発生します。
これは、トライアルが現在の作業ディレクトリを変更し、ユニットテストしたいオブジェクトクラスでモジュールをインポートしようとすると失敗するためだと思われます。
私は自分で設定した単一のディレクトリにアプリケーション モジュールを保持します。それは、PYTHONPATH のディレクトリや他の既知のディレクトリにはありません。私のアプリでは、モジュールはすべて同じディレクトリにあるため、他のモジュールをインポートします。
コードは次のようになります。
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')
したがって、エラー メッセージは次のようになります:
exceptions.ImportError: No module named MyModule
おそらく、これは試用版を使用したり、Python アプリをデプロイしたりする標準的な方法ではありません。
更新: これに対する回避策を見つけたところです。app ディレクトリを sys.path に追加するだけで、インポート部分は次のようになります。
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