参考了这个:Test Files Creating a Temporal Directory in Python Unittests | Simple IT 🤘 Rocks
并使用pathlib做了优化:
- import tempfile
- import unittest
- from pathlib import Path
-
-
- class TestExample(unittest.TestCase):
- def test_example(self):
- with tempfile.TemporaryDirectory() as tmpdirname:
- print("created temporary directory", tmpdirname)
- assert isinstance(tmpdirname, str)
- tmp_path = Path(tmpdirname)
- tmp_file = tmp_path / "output.txt"
- tmp_file.write_text("hehe")
- assert tmp_file.exists()
- assert tmp_file.read_text() == "hehe"
-
-
- if __name__ == "__main__":
- unittest.main()
================
注:pytest的话,自带了tmp_path,直接用即可,例如
- # test_a.py
- from pathlib import Path
- def test_xxx(tmp_path):
- assert isinstance(tmp_path, Path)
- assert tmp_path.is_dir()
- p = tmp_path / 'a.txt'
- p.write_text('haha')
- assert p.read_text() == 'haha'
pytest test_a.py