1

I have a file structure like this:

Main/
|----unit_tests
|    |---test_main.py
|    |---__init__.py
|--main.py
|--__init__.py
|--requirements.txt

test_main.py:

import unittest.mock
from main import MainFunction
from nose.tools import assert_is_not_none, assert_is_none, assert_equal

class TestMainLogic(unittest.case):
~~~ code here ~~~~

When running my unit tests in test_main.py from Pycharm, all is well. However when I try to run it in a Jenkins setup, I get:

+ python3 unit_tests/test_main.py
Traceback (most recent call last):
  File "unit_tests/test_main.py", line 4, in <module>
    from main import MainFunction
ModuleNotFoundError: No module named 'main'

Here's my Jenkinsfile:

pipeline 
{
    environment 
    {
        PATH = "/home/jenkins/.local/bin:$PATH"
    }
    stages 
    {
        stage('build') 
        {
            steps
            {
                sh 'python3 --version'
                sh 'wget https://bootstrap.pypa.io/get-pip.py'
                sh 'python3 get-pip.py'  
                sh 'pip3 install -r requirements.txt'
                echo 'build phase has finished'
            }
        }
        stage('Lint')
        {
            steps
            {
                sh 'pylint unit_tests/test_main.py'
            }
        }
        stage('test')
        {
            steps
            {
                sh 'python3 unit_tests/test_main.py'
            }
            post
            {
                always
                {
                    cleanWs()
                }
            }
        }
    }
}

I've followed several posts and I'm just not getting an answer that works. I tried:Python module import failure in Jenkins and its linked answers. I do not have access to ssh into the Jenkins server and find the path so I need a way to set it at execution.

itinneed
  • 153
  • 2
  • 14
  • You probably need to configure the build agent to support this. – Matthew Schuchard Mar 26 '21 at 15:35
  • How? And again, I do not have access to the node to reconfigure python. I just get to run my code from github against it. – itinneed Mar 26 '21 at 15:53
  • It's always a good practice to use python venv for python applications and specially with this kind of scenario because in Jenkins you might build several other python related app and there might be high chances to override python package version with each other. so I will suggest create a venv and make use of that for your build – Samit Kumar Patel Mar 26 '21 at 15:57
  • @Samit Kumar Patel, a what? Googling venv comes up with a lot that I don't related to Jenkins. – itinneed Mar 26 '21 at 16:03

1 Answers1

1

you need to use absolute import instead of relative in your test_main.py file.

in test_main.py

replace:

from main import MainFunction
# SOME CODE

with:

from Main.main import MainFunction
# SOME CODE
Tam Nguyen
  • 88
  • 1
  • 8