Relative imports with unittest in Python

前端 未结 3 1527
忘了有多久
忘了有多久 2020-12-30 19:32

I am trying to use Python unittest and relative imports, and I can\'t seem to figure it out. I know there are a lot of related questions, but none of them have helped so fa

相关标签:
3条回答
  • 2020-12-30 19:48

    In my experience it is easiest if your project root is not a package, like so:

    project/
      test.py
      run.py
      package/
        __init__.py
        main_program.py
        lib/
          __init__.py
          lib_a
          lib_b
        tests/
          __init__.py
          test_a
          test_b
    

    However, as of python 3.2 , the unittest module provides the -t option, which lets you set the top level directory, so you could do (from package/):

    python -m unittest discover -t ..
    

    More details at the unittest docs.

    0 讨论(0)
  • 2020-12-30 19:57

    I run with the same problem and kai's answer solved it. I just want to complement his answer with the content of test.py (as @gsanta asked). I've only tested it on Python 2.7:

    from packages.tests import test_a, test_b
    import unittest
    
    # for test_a
    unittest.main(test_a, exit=False)
    
    # for test_b
    unittest.main(test_b)
    

    then you can just

    ../project $ python test.py
    
    0 讨论(0)
  • 2020-12-30 20:05

    In a layout where tests and package are at sibling level:

    /project
       /tests
       /package
    

    One way is to start within the package dir, use -s to discover only in tests, and use -t to set the top level:

    ../package $ python3 -m unittest discover -s ../tests -t ..
    
    
    0 讨论(0)
提交回复
热议问题