programing

Python 유닛 테스트는 어디로 진행됩니까?

itsource 2022. 9. 28. 23:31
반응형

Python 유닛 테스트는 어디로 진행됩니까?

라이브러리 또는 앱을 작성하는 경우 유닛 테스트 파일은 어디로 이동합니까?

메인 앱 코드에서 테스트 파일을 분리하는 것은 좋지만, 테스트하는 모듈을 Import하는 것이 어려워지기 때문에 앱 루트 디렉토리 내의 "tests" 서브 디렉토리에 넣는 것은 곤란합니다.

여기 베스트 프랙티스가 있나요?

파일의 경우module.py유닛 테스트는 통상적으로 호출해야 합니다.test_module.py피토닉 명명 규칙을 따릅니다.

일반적으로 수용되는 몇 가지 장소가 있습니다.test_module.py:

  1. 와 같은 디렉토리에 있습니다.module.py.
  2. 에서../tests/test_module.py(코드 디렉토리와 같은 레벨).
  3. 에서tests/test_module.py(코드 디렉토리의 한 레벨).

1번으로 간단하게 검사해서 수입하는 것이 좋습니다.사용하고 있는 빌드 시스템에 관계없이, 간단하게 파일을 실행할 수 있습니다.test_실제로 테스트 검출에 사용되는 기본 패턴은 입니다.

1개의 테스트 파일만

테스트 파일이 1개밖에 없는 경우 최상위 디렉토리에 저장하는 것이 좋습니다.

module/
    lib/
        __init__.py
        module.py
    test.py

CLI에서 테스트 실행

python test.py

많은 테스트 파일

에 많은 테스트 파일이 있는 경우,tests폴더:

module/
    lib/
        __init__.py
        module.py
    tests/
        test_module.py
        test_module_function.py
# test_module.py

import unittest
from lib import module

class TestModule(unittest.TestCase):
    def test_module(self):
        pass

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

CLI에서 테스트 실행

# In top-level /module/ folder
python -m tests.test_module
python -m tests.test_module_function

사용

unittest discovery패키지 폴더에서 모든 테스트를 찾습니다.

작성하다__init__.py에서tests/폴더

module/
    lib/
        __init__.py
        module.py
    tests/
        __init__.py
        test_module.py
        test_module_function.py

CLI에서 테스트 실행

# In top-level /module/ folder

# -s, --start-directory (default current directory)
# -p, --pattern (default test*.py)

python -m unittest discover

언급

유닛 테스트 프레임워크

일반적인 방법은 테스트 디렉토리를 모듈/패키지와 같은 부모 디렉토리에 두는 것입니다.따라서 모듈의 이름이 foo.py인 경우 디렉토리 레이아웃은 다음과 같습니다.

parent_dir/
  foo.py
  tests/

물론 그것을 하는 한가지 방법은 없다.테스트 서브 디렉토리를 만들고 absolute import를 사용하여 모듈을 Import할 수도 있습니다.

어디서 검사를 하든지 로 검사하는 것을 추천합니다.Nose는 테스트를 위해 디렉토리를 검색합니다.이렇게 하면 조직적으로 가장 적합한 위치에 테스트를 배치할 수 있습니다.

Python 프로그램의 유닛 테스트를 생성하는 Pythonoscope(https://pypi.org/project/pythoscope/),)를 작성할 때도 같은 질문을 받았습니다.우리는 디렉토리를 선택하기 전에 python 리스트에서 테스트에 대해 사람들을 대상으로 여론조사를 실시했는데, 여러 가지 의견이 있었습니다.결국 소스 코드와 같은 디렉토리에 "tests" 디렉토리를 넣기로 했습니다.이 디렉토리에서는 부모 디렉토리의 각 모듈에 대한 테스트파일을 생성합니다.

위의 Jeremy Cantrell이 언급했듯이, 나는 또한 내 유닛 테스트를 파일 자체에 넣는 경향이 있다, 비록 나는 테스트 기능을 본체에 넣는 것이 아니라, 오히려 모든 것을 파일 안에 넣는 경향이 있다.

if __name__ == '__main__':
   do tests...

block. 테스트 중인 python 파일을 사용하는 방법에 대한 '예제 코드'로서 문서를 파일에 추가합니다.

덧붙이자면, 저는 매우 엄격한 모듈/클래스를 작성하는 경향이 있습니다.모듈이 매우 많은 수의 테스트를 필요로 하는 경우 다른 모듈에 추가할 수 있지만, 그래도 다음과 같이 덧붙입니다.

if __name__ == '__main__':
   import tests.thisModule
   tests.thisModule.runtests

이를 통해 소스 코드를 읽는 모든 사용자가 테스트 코드를 찾는 위치를 알 수 있습니다.

때때로 나는 시험 배치에 대한 주제를 체크하고, 대부분의 사람들이 도서관 코드 외에 별도의 폴더 구조를 추천하지만, 매번 주장이 같고 설득력이 없다는 것을 알게 된다.테스트 모듈을 코어 모듈 옆에 두게 됩니다.

이렇게 하는 주된 이유는 리팩터링입니다.

물건을 이동할 때 테스트 모듈을 코드와 함께 이동시키고 싶다.다른 트리에 있으면 테스트에 실패하기 쉽다.솔직히 말하자면, 조만간 당신은 장고, 플라스크, 그리고 다른 많은 것들과 같은 완전히 다른 폴더 구조를 갖게 될 것이다.신경 안 쓴다면 괜찮아

자신에게 물어봐야 할 주요 질문은 다음과 같습니다.

내가 쓰고 있나?

  • a) 재사용 가능한 라이브러리 또는
  • b) 프로젝트 구축은 반분리된 모듈 몇 개를 묶는 것이 아니라?

a:

별도의 폴더와 구조를 유지하기 위한 추가 노력이 더 적합할 수 있습니다.당신의 테스트가 실전에 도입되는 것에 대해 불평하는 사람은 아무도 없을 것입니다.

그러나 코어 폴더와 혼재되어 있는 테스트도 배포 대상에서 제외하는 것이 간단합니다.설정에 추가합니다.py:

find_packages("src", exclude=["*.tests", "*.tests.*", "tests.*", "tests"]) 

b:

우리 모두가 그렇듯이 재사용 가능한 라이브러리를 작성하기를 원할 수도 있지만, 대부분의 경우 라이브러리의 생명은 프로젝트의 라이프와 관련되어 있습니다.프로젝트를 쉽게 유지관리할 수 있는 능력이 우선시되어야 합니다.

그 후 모듈을 다른 프로젝트에 적합하게 사용할 수 있다면 모듈이 새로운 프로젝트로 복사될 수 있습니다(포크되거나 별도의 라이브러리로 만들어지지 않음).또한 테스트 폴더와 같은 폴더 구조 내의 테스트를 이동하는 것은 다른 테스트 폴더가 엉망진창으로 되어 있는 테스트보다 간단합니다.(애초에 엉망진창이 되어서는 안 된다고 주장할 수도 있지만, 여기서 현실화합시다.)

So the choice is still yours, but I would argue that with mixed up tests you achieve all the same things as with a separate folder, but with less effort on keeping things tidy.

I use a tests/ directory, and then import the main application modules using relative imports. So in MyApp/tests/foo.py, there might be:

from .. import foo

to import the MyApp.foo module.

I don't believe there is an established "best practice".

I put my tests in another directory outside of the app code. I then add the main app directory to sys.path (allowing you to import the modules from anywhere) in my test runner script (which does some other stuff as well) before running all the tests. This way I never have to remove the tests directory from the main code when I release it, saving me time and effort, if an ever so tiny amount.

From my experience in developing Testing frameworks in Python, I would suggest to put python unit tests in a separate directory. Maintain a symmetric directory structure. This would be helpful in packaging just the core libraries and not package the unit tests. Below is implemented through a schematic diagram.

                              <Main Package>
                               /          \
                              /            \
                            lib           tests
                            /                \
             [module1.py, module2.py,  [ut_module1.py, ut_module2.py,
              module3.py  module4.py,   ut_module3.py, ut_module.py]
              __init__.py]

In this way when you package these libraries using an rpm, you can just package the main library modules (only). This helps maintainability particularly in agile environment.

I recommend you check some main Python projects on GitHub and get some ideas.

When your code gets larger and you add more libraries it's better to create a test folder in the same directory you have setup.py and mirror your project directory structure for each test type (unittest, integration, ...)

For example if you have a directory structure like:

myPackage/
    myapp/
       moduleA/
          __init__.py
          module_A.py
       moduleB/
          __init__.py
          module_B.py
setup.py

After adding test folder you will have a directory structure like:

myPackage/
    myapp/
       moduleA/
          __init__.py
          module_A.py
       moduleB/
          __init__.py
          module_B.py
test/
   unit/
      myapp/
         moduleA/
            module_A_test.py
         moduleB/
            module_B_test.py
   integration/
          myapp/
             moduleA/
                module_A_test.py
             moduleB/
                module_B_test.py
setup.py

Many properly written Python packages uses the same structure. A very good example is the Boto package. Check https://github.com/boto/boto

How I do it...

Folder structure:

project/
    src/
        code.py
    tests/
    setup.py

Setup.py points to src/ as the location containing my projects modules, then i run:

setup.py develop

Which adds my project into site-packages, pointing to my working copy. To run my tests i use:

setup.py tests

내가 구성한 테스트 러너를 사용해.

최상위 테스트 디렉토리를 선호합니다.이것은 수입이 조금 더 어려워진다는 것을 의미한다.이를 위해 두 가지 솔루션이 있습니다.

  1. setuptools를 사용합니다.그럼 통과해test_suite='tests.runalltests.suite'안으로setup()테스트를 간단하게 실행할 수 있습니다.python setup.py test
  2. 테스트를 실행할 때 PYTONPATH를 설정합니다.PYTHONPATH=. python tests/runalltests.py

M2Crypto의 코드로 지원되는 방법은 다음과 같습니다.

만약 당신이 nosetests로 테스트를 실행하는 것을 선호한다면, 당신은 조금 다른 것을 해야 할 수도 있습니다.

테스트 대상 코드(CUT)와 같은 디렉토리에 테스트를 저장합니다.플러그인으로 pytest를 조정할 수 있는 프로젝트에서foo.py사용하고 있다foo.pt특정 모듈 및 해당 모듈을 쉽게 편집할 수 있는 테스트의 경우:vi foo.*.

할 수 없는 경우에는foo_ut.py또는 이와 유사합니다.아직 사용할 수 있습니다.vi foo*그것도 잡히겠지만foobar.py그리고.foobar_ut.py그게 존재한다면요.

어느 경우든 테스트 디스커버리 프로세스를 조정하여 이러한 항목을 찾습니다.

이것에 의해, 테스트가 디렉토리 리스트내의 코드의 바로 옆에 있어, 테스트가 존재하는 것을 알 수 있습니다.또, 테스트가 다른 파일에 있는 경우는, 가능한 한 간단하게 오픈할 수 있습니다(위의 커맨드 라인으로부터 개시한 에디터의 경우, GUI 시스템의 경우, 코드 파일과 인접한(또는 매우 가까운) 테스트를 클릭합니다).일레

다른 사람들이 지적했듯이, 이것은 또한 필요할 때 다른 곳에서 사용하기 위해 코드를 추출하는 것을 더 쉽게 만든다.

전혀 다른 디렉토리 트리에 테스트를 넣는 것은 정말 싫습니다. CUT로 파일을 열 때 개발자가 테스트를 여는 것이 필요 이상으로 어려워지는 이유는 무엇입니까?대부분의 개발자가 테스트 작성이나 수정에 열심이어서 그 장벽을 핑계로 삼지 않고 무시하지는 않는다.(제 경험상으로는 정반대입니다.최대한 간단하게 해도 테스트 작성은 귀찮은 개발자를 많이 알고 있습니다.)

사용하고 있습니다

app/src/code.py
app/testing/code_test.py 
app/docs/..

각 테스트 파일에 삽입하는../src/에서sys.path가장 좋은 솔루션은 아니지만 효과가 있습니다.어떤 프로젝트에 종사하든 상관 없이 기능하는 표준 규약을 제공하는 Java maven과 같은 기능을 가진 사람이 있으면 좋을 것 같습니다.

If the tests are simple, simply put them in the docstring -- most of the test frameworks for Python will be able to use that:

>>> import module
>>> module.method('test')
'testresult'

For other more involved tests, I'd put them either in ../tests/test_module.py or in tests/test_module.py.

In C#, I've generally separated the tests into a separate assembly.

In Python -- so far -- I've tended to either write doctests, where the test is in the docstring of a function, or put them in the if __name__ == "__main__" block at the bottom of the module.

When writing a package called "foo", I will put unit tests into a separate package "foo_test". Modules and subpackages will then have the same name as the SUT package module. E.g. tests for a module foo.x.y are found in foo_test.x.y. The __init__.py files of each testing package then contain an AllTests suite that includes all test suites of the package. setuptools provides a convenient way to specify the main testing package, so that after "python setup.py develop" you can just use "python setup.py test" or "python setup.py test -s foo_test.x.SomeTestSuite" to the just a specific suite.

I've recently started to program in Python, so I've not really had chance to find out best practice yet. But, I've written a module that goes and finds all the tests and runs them.

So, I have:

app/
 appfile.py
test/
 appfileTest.py

I'll have to see how it goes as I progress to larger projects.

ReferenceURL : https://stackoverflow.com/questions/61151/where-do-the-python-unit-tests-go

반응형