Tiger140304
@Tiger140304

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

pytest ModleNotFoundError

Q&A

Closed

解決したいこと

pytest を実行できるようにしたい。

発生している問題・エラー

ModuleNotFoundError: No module named 'source'

該当するソースコード

   import source.my_functions as my_functions 
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

例)

import source.my_functions as my_functions 

def test_add():
   result = my_functions.add(number_one = 1, number_two = 2)
   
   assert result == 5

自分で試したこと

同列のfolder(source)にmy_functions.pyをいれて、folder(tests)のtest_my_functions.pyにimportしようとした

0

1Answer

同列のfile(source)にmy_functions.pyをいれて

ファイル名sourceを、source.pyにリネームして、importの書き方を変更したらどうでしょうか。

from source import my_functions 
0Like

Comments

  1. @Tiger140304

    Questioner

    '''
    import pytest
    from source import my_functions as my_functions

    def test_add():
    result = my_functions.add(number_one = 1, number_two = 2)

    assert result == 2
    '''

    my_functions.pyについては下のcodeです。
    '''
    def add(number_one, number_two):

    return number_one + number_two
    

    def divide(number_one, number_two):

    return number_one / number_two
    

    '''
    とやってみましたが、errorが変わりませんでした。

  2. 同列のfolder(source)にmy_functions.pyをいれて、folder(tests)のtest_my_functions.pyにimportしようとした

    sourcetestsは、フォルダ名だったんですね。だとすると、話は違います。
    source.pyへのリネームと、importの変更は、元に戻してください。

    以下は、sourcetestsが、同階層のフォルダであるとしてお答えします。

    フォルダ構成
    . ←カレントディレクトリとする
    ├── source
    │   └── my_functions.py
    └── tests
        └── test_my_functions.py
    

    ターミナルかDOSプロンプトを開いて、source testsの親フォルダをカレントディレクトリとします。次に、pythonを "-m"オプションを指定してtest_my_functions.pyを起動します。

    cd xxx (←カレントディレクトリを変更)
    python -m tests.test_my_functions
    

    ("-m"オプションを指定しているので、".py"の拡張子は指定しないことに注意)

  3. @Tiger140304

    Questioner

    ありがとうございます。
    @nak435様のおかげで、実行することができました。

  4. 解決してよかったです。

    よろしければ、当Q&Aをクローズしてください。

Your answer might help someone💌