Project: Automated Code Testing with Jenkins and Git Webhooks

Objective

To automate unit testing using Jenkins, where every code push to a Git repository triggers a pipeline that runs unit tests (e.g., JUnit for Java or PyTest for Python). This ensures code quality before deployment.

Project Components

Implementation Steps

1. Set Up Jenkins

2. Configure Git Webhook

3. Create a Jenkins Pipeline

Pipeline Structure

Example Jenkinsfile

For Java (JUnit with Maven)
pipeline {
    agent any
    stages {
        stage('Checkout Code') {
            steps {
                git branch: 'main', url: 'https://github.com/your-repo.git'
            }
        }
        stage('Build Project') {
            steps {
                sh 'mvn clean install'
            }
        }
        stage('Run Unit Tests') {
            steps {
                sh 'mvn test'
            }
            post {
                always {
                    junit '**/target/surefire-reports/*.xml'
                }
            }
        }
    }
    post {
        success {
            echo "Tests passed!"
        }
        failure {
            echo "Tests failed!"
        }
    }
}
    
For Python (PyTest with Virtualenv)
pipeline {
    agent any
    stages {
        stage('Checkout Code') {
            steps {
                git branch: 'main', url: 'https://github.com/your-repo.git'
            }
        }
        stage('Setup Environment') {
            steps {
                sh 'python3 -m venv venv && source venv/bin/activate'
                sh 'pip install -r requirements.txt'
            }
        }
        stage('Run Unit Tests') {
            steps {
                sh 'pytest --junitxml=pytest_results.xml'
            }
            post {
                always {
                    junit '**/pytest_results.xml'
                }
            }
        }
    }
    post {
        success {
            echo "Tests passed!"
        }
        failure {
            echo "Tests failed!"
        }
    }
}
    

4. Configure Notifications

Slack Notification (Optional)

post {
    success {
        slackSend channel: '#ci-cd', message: "Build Passed: ${env.BUILD_URL}"
    }
    failure {
        slackSend channel: '#ci-cd', message: "Build Failed: ${env.BUILD_URL}"
    }
}
    

5. Run and Validate

Expected Outcome

Next Steps

This setup ensures a robust CI/CD pipeline with automated testing, improving software quality and development speed.