Skip to content

Commit

Permalink
ADD_PYTHON_UNIT_TEST: allow multiple paths in argn (#240)
Browse files Browse the repository at this point in the history
Multiple paths can be set in PYTHONPATH, but they have to be joined by
`os.pathsep`(":" on unix, ";" on windows)
https://docs.python.org/3/using/cmdline.html#envvar-PYTHONPATH

This commit fix the concatenation with any pre-existing environment
variables, and allows to set several folders (relative to the project
build tree) inside this PYTHONPATH.

eg. if you build a module in src/ and a test module in tests/, you can
import them both in a test with:
ADD_PYTHON_UNIT_TEST("test-python" "tests/main.py" "src" "tests")
  • Loading branch information
nim65s authored and jcarpent committed Oct 1, 2019
1 parent c81a371 commit 429af97
Showing 1 changed file with 15 additions and 8 deletions.
23 changes: 15 additions & 8 deletions test.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,10 @@ MACRO(ADD_UNIT_TEST NAME SOURCE)
ENDMACRO(ADD_UNIT_TEST NAME SOURCE)

#.rst:
# .. command:: ADD_PYTHON_UNIT_TEST (NAME SOURCE [MODULE_PATH])
# .. command:: ADD_PYTHON_UNIT_TEST (NAME SOURCE [MODULES...])
#
# Add a test called `NAME` that runs an equivalent of ``python ${SOURCE}``,
# optionnaly with a `PYTHONPATH` set to `CMAKE_BINARY_DIR/MODULE_PATH` if `MODULE_PATH` is set.
# optionnaly with a `PYTHONPATH` set to `CMAKE_BINARY_DIR/MODULE_PATH` for each MODULES
# `SOURCE` is relative to `PROJECT_SOURCE_DIR`
#
# .. note:: :command:`FINDPYTHON` should have been called first.
Expand All @@ -98,16 +98,23 @@ MACRO(ADD_PYTHON_UNIT_TEST NAME SOURCE)
ADD_TEST(NAME ${NAME} COMMAND ${PYTHON_EXECUTABLE} "${PROJECT_SOURCE_DIR}/${SOURCE}")
SET(PYTHONPATH)

SET(MODULE_PATH "${ARGN}") # ARGN is not a variable
IF(MODULE_PATH)
SET(MODULES "${ARGN}") # ARGN is not a variable
FOREACH(MODULE_PATH IN LISTS MODULES)
LIST(APPEND PYTHONPATH "${CMAKE_BINARY_DIR}/${MODULE_PATH}")
ENDIF(MODULE_PATH)
ENDFOREACH(MODULE_PATH IN LISTS MODULES)

IF(DEFINED ENV{PYTHONPATH})
SET(PYTHONPATH "${PYTHONPATH}:$ENV{PYTHONPATH}")
LIST(APPEND PYTHONPATH "$ENV{PYTHONPATH}")
ENDIF(DEFINED ENV{PYTHONPATH})

SET(ENV_VARIABLES "PYTHONPATH=${PYTHONPATH}")
# get path separator to join those paths
EXECUTE_PROCESS(COMMAND
"${PYTHON_EXECUTABLE}" "-c" "import os; print(os.pathsep)"
OUTPUT_VARIABLE PATHSEP
OUTPUT_STRIP_TRAILING_WHITESPACE)

STRING(REPLACE ";" ${PATHSEP} PYTHONPATH_STR "${PYTHONPATH}")
SET(ENV_VARIABLES "PYTHONPATH=${PYTHONPATH_STR}")
IF(APPLE)
LIST(APPEND ENV_VARIABLES "LD_LIBRARY_PATH=$ENV{LD_LIBRARY_PATH}")
LIST(APPEND ENV_VARIABLES "DYLD_LIBRARY_PATH=$ENV{DYLD_LIBRARY_PATH}")
Expand Down

0 comments on commit 429af97

Please sign in to comment.