LoginSignup
3
2

More than 5 years have passed since last update.

Python unittestのsetUpでテスト用ファイルを用意する

Last updated at Posted at 2018-07-27

問題

unittestで、setUp内でテストデータを作成しようとするとファイルが作成されない。
(あまり調べてないが、原因はよくわからない。。。)

解決策

setUp内で、tempfileモジュールを使用して、テストディレクトリを作り、その下でファイルを作成すればよい。
なお、tearDownでファイルを削除することを忘れずに。

自動作成したテストファイルでunittest
import os
import shutil
import tempfile
import unittest

class TestExample(unittest.TestCase):
    def setUp(self):
        self.test_dir = tempfile.mkdtemp()
        self.test_file = os.path.join(self.test_dir, 'test_file.txt')
        test_content = """
        test file content
        """

        with open(self.test_file, 'w') as fp:
            fp.write(test_content)

    def tearDown(self):
        shutil.rmtree(self.test_dir)

    def test_hoge(self):
        result = hoge(self.test_file)
        expect = "hoge's result"
        self.assertEqual(result, expect)

if __name__ == '__main__':
    unittest.main()

コードに誤りがあったのを修正しました(7/27)

参考

3
2
2

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
3
2