LoginSignup
4
1

More than 5 years have passed since last update.

CircleCIでModuleNotFoundError

Last updated at Posted at 2018-11-03

CircleCI上でtoxコマンドを走らせたときに、テストファイルから自作の外部ファイルを読み込めず消耗したのでメモを残す。

概要

.
├── test_apis.py
├── tox.ini
└── utils.py

test_apis.pyがテストが書かれたファイルで

test_apis.py
# coding: utf-8

from utils import HOGEAPI 
from unittest import TestCase

と書いて、utils.pyから自作クラスHOGEAPIをimportして、CircleCI上でtoxすると

==================================== ERRORS ====================================
________________________ ERROR collecting test_apis.py _________________________
ImportError while importing test module '/home/circleci/myapp/test_apis.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
test_apis.py:4: in <module>
    from utils import HOGEAPI
E   ModuleNotFoundError: No module named 'utils'
!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!
=========================== 1 error in 0.09 seconds ============================
ERROR: InvocationError for command '/home/circleci/myapp/.tox/py36/bin/py.test' (exited with code 2)

ModuleNotFoundErrorが出て自作クラスを読み込めない。ちなみにローカルでtoxした場合は上手くいく。

原因

CircleCiにsshしてパスを確認してみると、

(env) circleci@2dca847161e3:~/myapp$ python
Python 3.6.1 (default, Jul  8 2017, 05:00:20) 
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload']
>>> 

CircleCIのPythonがインポートできるパスに、ローカルが追加されていなかった。

よって、こう書いてパスを追加したら上手く言った

test_apis.py
# coding: utf-8

import os
import sys
from unittest import TestCase

sys.path.append(os.getcwd())

from utils import HOGEAPI  # noqa: E501

※ importを上部にまとめていないとflake8に引っかかるので、# noqa: E501を追記

参考

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1