When I used Python for the first time, I had a hard time before using unittest, so this article is for smooth use. Moreover, it is difficult to start using it unless you understand the basics of Python, so I summarized it.
The directory structure that can be executed successfully is as follows.
.
├─sample.py
└─tests
├─__init__.py
└─test_sample.py
sample.py
def add(x, y):
return x + y
test_sample.py
import unittest
import sample
class TestSample(unittest.TestCase):
def test_add(self):
self.assertEqual(sample.add(1, 2), 3)
if __name__ == "__main__":
unittest.main()
python -m unittest tests.test_sample And unittest scripts
I can run the test well with the above method, but I learned the following points.
__init__.What is py? I thought, but the directory where this file is located seems to be treated as a python package. Therefore sample.With the execute command from the directory where py is, "tests.test_"tests" of "sample".It seems that you can specify the package and execute it.
* Python 2.7 does not recognize it as a package without ``` __ init__.py```, so it is necessary, but it is not necessary because it is recognized as a package even if it is not Python 3.5.
Also, I am importing with test_sample.py. There are various import search paths, but the execution path is one of them. It seems that you can import with "import sample" by executing from the directory where sample.py is located.
## Experiment
We are conducting the following experiments to realize what we have learned.
python tests\test_sample.py
Try running it with.
``` error
Traceback (most recent call last):
File "tests\test_sample.py", line 2, in <module>
import sample
ImportError: No module named sample
Error that sample module cannot be found. The execution path seems to be the tests directory, and it seems that the sample in the next higher hierarchy cannot be found.
However, put test_sample.py in the same hierarchy as the sample.py directory, python test_sample.py Will work correctly. python -m unittest test_sample It works correctly here as well.
Restore the directory structure and then delete the `` `__ init__.py``` file python -m unittest tests.test_sample When you run ImportError: No module named tests Error. It doesn't seem to be recognized as a package.
Finally, go to the tests directory and python test_sample.py When you run ImportError: No module named sample Error. python -m unittest test_sample But the same error. In other words, it cannot be imported because there is no sample in the execution directory.
Even though I just tried to use unittest in python, I learned a lot about how to specify packages and how to think of directories that can be imported. I learned a lot because I couldn't do it easily. With this, I feel that future python programming can go smoothly.
How to execute tests collectively with Python unit test
Recommended Posts