[Python] Importing some symbol from a Python script into its test script

Discussão em 'Python' iniciado por Stack, Julho 31, 2025.

  1. Stack

    Stack Membro Participativo

    I've got the following project tree:

    SomeDir
    |- script.py
    |- TestDir
    | |- test.py


    script.py is designed to be called in CLI and contains several classes: notably one that does the actual job and one that is a class exit_codes(Enum) that defines exit codes.

    test.py is to be used by pytest and typical tests consist of calling script.py with arguments that are used to initialize a working class object. This object then does some processing and calls sys.exit(<some enumerator>.value), using the exit codes in the Enum class.

    In the test I'm giving the command line to subprocess.run and assert its returncode against the desired exit code.

    Thus test.py and script.py should use the same code and I'd like to do something like

    from script import exit_codes


    but without additional actions script cannot be found.

    What is the proper way to do that?

    The typical workaround is sys.path.append using .. from __file__ (Importing files from different folder).

    Honestly I didn't try as I fear undesired side-effects (if there are other modules in this directory, there might be collisions with modules having the same name, in other directories).

    Continue reading...

Compartilhe esta Página