Importing a module does not run the code inside it when running a few unittest files using pytest

半世苍凉 提交于 2019-12-24 07:58:23

问题


I have a few files with tests and an imported file:

# test1.py
print("running test1.py")

import unittest
import imported

class MyTest1(unittest.TestCase):
    def test_method1(self):
        assert "love" == "".join(["lo", "ve"])

    def test_fail1(self):
        assert True, "I failed!"

and

# test2.py
print("running test2.py")

import unittest
import imported

class MyTest2(unittest.TestCase):
    def test_ok2(self):
        self.assertEqual(True, 2==2, "I will not appear!")

    def test_fail2(self):
        self.assertFalse(False, "Doh!")

and

# imported.py
import sys

# Here I am accessing the module that has imported this file
importing = sys.modules[sys._getframe(6).f_globals['__name__']]
print(importing.__name__ + " imported this file")

When I run pytest -s test1.py test2.py, I get this result:

=============================== test session starts ================================
platform darwin -- Python 3.6.0, pytest-3.7.1, py-1.5.4, pluggy-0.7.1
rootdir: /Users/ibodi/MyDocs/progs/Python/unittest_test, inifile:
collecting 0 items                                                                 running test1.py
test1 imported this file
collecting 2 items                                                                 running test2.py
collected 4 items                                                                  

test1.py ..                                                                        
test2.py ..

============================= 4 passed in 0.08 seconds =============================

importing variable in imported.py corresponds to the module that has imported the imported.py module.

And the problem is that the line import imported in test2.py doesn't cause test2 imported this file to appear in the logs. Why is that?

来源:https://stackoverflow.com/questions/51861110/importing-a-module-does-not-run-the-code-inside-it-when-running-a-few-unittest-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!