0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Django】testファイルをtestsディレクトリ内に移動したらtestが実行されない

Posted at

目的

DjangoRestframeworkでAPIを作成している際にやはり単体testを行う必要があると感じた。

デフォルトではアプリディレクトリにtests.pyが一つあるだけで、正直個人で遊ぶにはそれでも良いかもしれないが多くのテストがある実務を想定してtestsディレクトリの中にtest_●●●●.pyというファイルを作成した。

が、python manage.py testでこのファイルが認識されていない模様。。。
これをなんとかしたい。

.
├── __init__.py
├── admin.py
├── apps.py
├── migrations
├── models.py
├── serializer.py
├── tests
│   └── test_models.py
├── urls.py
└── views.py

結論

単純明快。
空の__init__.pyを同ディレクトリに追加することで解決できる。

実施環境

ハードウェア環境

項目 情報
OS macOS Catalina(10.15.7)
ハードウェア MacBook Air (11-inch, Early 2015)
プロセッサ 1.6 GHz デュアルコアIntel Core i5
メモリ 4 GB 1600 MHz DDR3
グラフィックス intel HD Graphics 6000 1536 MB

ソフトウェア環境

項目 情報
homebrew 3.3.8
mysql Ver 8.0.27 for macos10.15 on x86_64
python 3.8.12
django 3.0.0
anaconda 4.10.1
pip 21.2.4

原因究明

コマンドは正しいか??

python manage.py testと公式ドキュメントの通りに打っているから問題なさそうだ。

ファイル名/関数名は正しいか??

テストを行うファイル名とテストケースの関数名の最初はtestから始まる必要がある。
そうしないとDjangoがそれをテストだと読み込んでくれない。

問題なさそう。

解決

参考にしていたこの記事にもちゃんと書いてあった。

空の__init__.pyを同ディレクトリに追加すること.

このコメントによると、

If you remove the init.py file, Python will no longer look for submodules inside that directory, so attempts to import the module will fail.

init.pyがディレクトリにないとモジュールのimportが失敗してしまい先ほどのようなエラーになるため、ディレクトリ作成時は__init__.pyを入れた方が良い。

.
├── __init__.py
├── admin.py
├── apps.py
├── migrations
├── models.py
├── serializer.py
├── tests
│   ├── __init__.py
│   └── test_models.py
├── urls.py
└── views.py

無事テストが実行された。

======================================================================
FAIL: test_is_empty (tinder.tests.test_models.JobModelTests)
初期状態では何も登録されていないことをチェック
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/Yuto/dev/api_practice/tinder_api/tinder/tests/test_models.py", line 13, in test_is_empty
    self.assertEqual(saved_jobs.count(), 1)
AssertionError: 0 != 1

----------------------------------------------------------------------
Ran 1 test in 0.014s

FAILED (failures=1)

0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?