pytest-dev / pytest-django

A Django plugin for pytest.
https://pytest-django.readthedocs.io/
Other
1.37k stars 344 forks source link

Jenkins fails to create test mysql database when running pytest Unit testing as a step #1029

Open ShervinAbd92 opened 2 years ago

ShervinAbd92 commented 2 years ago

Hi, I have created some unit testing functions with pytest-django for my application models and successfully ran them on my local machine. However, when integrated them into Jenkinsfile as a step before building my docker image, i started getting errors. for simplicity i am going to show one test example. Here is how i have implemented my tests followed by the error i get from jenkins.

factories.py

import factory
import logging
from faker import Faker
from my_app import models

logger = logging.getLogger('faker')
logger.setLevel(logging.INFO)
fake = Faker()
class ChannelFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = models.Channel
    name = 'test'
    description = fake.text()

conftest.py

import pytest
from pytest_factoryboy import register
from factories import ChannelFactory
register(ChannelFactory)
@pytest.fixture
def test_channel(db, channel_factory):
    channel = channel_factory.create()
    return channel

test_unit.py

import pytest
@pytest.mark.django_db
def test_channel_str(test_channel):
    assert  test_channel.__str__() == 'test'

after committing this to my master, jenkins picks it up and runs the following as a step

        stage("Pytest Unit Testing") {
            steps {
                script {
                    withPythonEnv('python3.9') {
                        sh 'pip install -r requirements.txt'
                        def statusCode = sh(script: "pytest test_unit.py", returnStatus:true)
                        if (statusCode != 0) {
                            error 'unit test failed, exiting ....'
                        }}}}}

the errors i get from jenkins console, is due to not being able to create mysql database.

django.db.utils.OperationalError: (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)")
.pyenv-python3.9/lib/python3.9/site-packages/pymysql/connections.py:664: OperationalError

i am not sure when pytest is attempting to create the test database, do i need to have a mysql server running on the build node? or how i can configure pytest for the db credentials. Any suggestions would be greatly appreciated.