Test if code is executed from within a py.test session

前端 未结 6 1413
被撕碎了的回忆
被撕碎了的回忆 2020-12-08 18:19

I\'d like to connect to a different database if my code is running under py.test. Is there a function to call or an environment variable that I can test that will tell me i

6条回答
  •  余生分开走
    2020-12-08 18:48

    This could be done by setting an environment variable inside the testing code. For example, given a project

    conftest.py
    mypkg/
        __init__.py
        app.py
    tests/
        test_app.py
    

    In test_app.py you can add

    import os
    os.environ['PYTEST_RUNNING'] = 'true'
    

    And then you can check inside app.py:

    import os
    if os.environ.get('PYTEST_RUNNING', '') == 'true':
        print('pytest is running')
    

提交回复
热议问题