Home Backend Development PHP Tutorial Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

Jul 30, 2016 pm 01:29 PM

Based on building a continuous integration environment based on Jenkins, we will continue to introduce Jenkins combined with PHP projects to achieve automated testing and automatic deployment. No more nonsense, just get to work.

The server used by Zhainiao is Ubuntu

To implement automated testing of PHP in Jenkins, you first need to install the PHP testing framework on the Jenkins server. There are many PHP testing frameworks. Here we choose PHPUnit Framework.

PHPUnit The installation is very simple:

sudo apt-get install phpunit
Copy after login

If the following error occurs:

PHP Warning: require_once(PHP/CodeCoverage/Filter.php): failed to open stream: No such file or directory 
in /usr/bin/phpunit on line 39
PHP Fatal error: require_once(): Failed opening required 'PHP/CodeCoverage/Filter.php' 
(include_path='.:/usr/share/php:/usr/share/pear') in /usr/bin/phpunit on line 39
Copy after login

You can install it through the following method:

sudo pear channel-discover pear.phpunit.de
sudo pear channel-discover pear.symfony-project.com
sudo pear channel-discover components.ez.no
sudo pear channel-discover pear.symfony.com
sudo pear update-channels
sudo pear upgrade-all
sudo pear install pear.symfony.com/Yaml
sudo pear install --alldeps phpunit/PHPUnit
sudo pear install --force --alldeps phpunit/PHPUnit
Copy after login

After installation, execute phpunit --version to return the version information. Indicates successful installation.

root@dop-kvm-2:# phpunit --version
PHPUnit 3.7.28 by Sebastian Bergmann.
Copy after login

Now let’s start giving Jenkins some plug-ins:

Subversion/Git: Used to integrate project version control software, select as needed (already installed and used in the previous blog post)

Phing/Ant: Use Phing or Apache Ant for PHP Automated project construction

CheckStyle: A tool for code style checking using PHP CodeSniffer. A PEAR package used to check whether PHP code violates a set of preset coding standards. It has built-in ZEND and PEAR coding style rules

Clover PHP: a tool for unit testing using phpunit, which can be used by the xdebug extension to generate Code coverage report, and can be integrated with phing for automated testing, and can also be integrated with Selenium to complete large-scale automated integration testing

DRY: Use PHPCPD (php copy paste detector) to find duplicate code in the project

HTML Publisher: Use To publish the phpunit code coverage report

JDepend: Use PHP Depend to analyze the static code in php to check the code size and complexity in the project

Plot: Use phploc to count the size of the php project, which can count php The number of lines of project code

PMD: Use phpmd (php mess dector) to analyze the results based on pdepend. Once the project exceeds the specific indicators in pdepend, a warning message will be issued.

Violations: According to the serious code defects Centrally display the results of pwd static code analysis

xUnit: Use JUnit format to output phpunit log files


Note that these plug-ins are some plug-ins provided by Jenkins for PHP projects, but they are not necessary, so stay home Niao only explains to you how to automate testing, packaging and publishing that deserves your most attention.

First give the directory structure of the project:

root@dop-kvm-2:/home/jenkins/api# tree
.
├── aa.php
├── build.xml
├── create.php
└── test
    ├── DemoTest.php
    └── FunctionTest.php
1 directory, 5 files
Copy after login

Note:

aa.php and create.php are the program files of the project

DemoTest.php and FunxtionTest.php in the test directory are the test files of the project

build .xml is the calling file for Jenkins continuous integration test packaging and deployment


First give the build.xml file required by the project:

<?xml version="1.0" encoding="UTF-8"?>
<project name="api" default="build">
        <target name="build" depends="make_runtime,phpcs-ci,phploc,pdepend,phpcb,phpunit,phpdox,phpcpd"/>
        <property name="version-m"  value="1.1" />
        <property name="version"    value="1.1.0" />
        <property name="stability"  value="stable" />
        <property name="releasenotes" value="" />
        <property name="tarfile"     value="${phing.project.name}.${buildnumber}.${buildid}.tar.gz" />
        <property name="pkgfile"     value="${phing.project.name}.${version}.tgz" />
        <property name="distfile"    value="dist/${tarfile}" />
        <property name="tests.dir" value="test" />
        <fileset id="api.tar.gz" dir=".">
            <include name="test/**"/>
            <include name="*.php"/>
            <include name="*.xml"/>
        </fileset>
        <target name="make_runtime">
                <mkdir dir="${project.basedir}/Runtime" />
                <mkdir dir="${project.basedir}/build/logs" />
                <mkdir dir="${project.basedir}/build/pdepend" />
                <mkdir dir="${project.basedir}/build/code-browser" />
        </target>
        <target name="phpcs" description="Find coding standard violations using PHP_CodeSniffer">
                <exec executable="phpcs">
                        <arg value="--standard=${project.basedir}/build/phpcs.xml" />
                        <arg value="--ignore=autoload.php" />
                        <arg path="${project.basedir}/" />
                </exec>
        </target>
        <target name="phpcs-ci" description="Find coding standard violations using PHP_CodeSniffer">
                <exec executable="phpcs" output="${project.basedir}/build/build.log">
                        <arg value="--report=checkstyle" />
                        <arg value="--report-file=${project.basedir}/build/logs/checkstyle.xml" />
                        <arg value="--standard=${project.basedir}/build/phpcs.xml" />
                        <arg value="--ignore=" />
                        <arg path="${project.basedir}/" />
                </exec>
        </target>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
        <target name="phploc" description="Measure project size using PHPLOC">
                <exec executable="phploc">
                        <arg value="--log-csv" />
                        <arg value="${project.basedir}/build/logs/phploc.csv"/>
                        <arg path="${project.basedir}/"/>
                </exec>
        </target>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
        <target name="pdepend" description="Calculate software metrics using PHP_Depend">
                <exec executable="pdepend">
                        <arg value="--jdepend-xml=${project.basedir}/build/logs/jdepend.xml"/>
                        <arg value="--jdepend-chart=${project.basedir}/build/pdepend/dependencies.svg"/>
                        <arg value="--overview-pyramid=${project.basedir}/build/pdepend/overview-pyramid.svg"/>
                        <arg path="${project.basedir}/"/>
                </exec>
        </target>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
        <target name="phpmd" description="Perform project mess detection using PHPMD">
                <exec executable="phpmd">
                        <arg path="${project.basedir}/"/>
                        <arg value="text"/>
                        <arg value="${project.basedir}/build/phpmd.xml"/>
                </exec>
        </target>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
        <target name="phpmd-ci" description="Perform project mess detection using PHPMD">
                <exec executable="phpmd">
                        <arg path="${project.basedir}/"/>
                        <arg value="xml"/>
                        <arg value="${project.basedir}/build/phpmd.xml"/>
                        <arg value="--reportfile"/>
                        <arg value="${project.basedir}/build/logs/pmd.xml"/>
                </exec>
        </target>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
        <target name="phpcpd" description="Find duplicate code using PHPCPD">
                <exec executable="phpcpd">
                        <arg value="--log-pmd"/>
                        <arg value="${project.basedir}/build/logs/pmd-cpd.xml"/>
                        <arg path="${project.basedir}/"/>
                </exec>
        </target>
        <target name="phpdox" description="Generate API documentation using phpDox">
                <exec executable="phpdox"/>
        </target>
        <target name="phpunit" description="Run unit tests with PHPUnit">
                <exec executable="phpunit" />
        </target>
        <target name="test" description="Run PHPUnit tests">
            <phpunit haltonerror="true" haltonfailure="true" printsummary="true">
            <batchtest>
            <fileset dir="${tests.dir}">
                <include name="**/*Test.php" />
            </fileset>
            </batchtest>
            </phpunit>
        </target>
        <target name="phpcb" description="Aggregate tool output with PHP_CodeBrowser">
                <exec executable="phpcb">
                        <arg value="--log"/>
                        <arg path="${project.basedir}/build/logs"/>
                        <arg value="--source"/>
                        <arg path="${project.basedir}/"/>
                        <arg value="--output"/>
                        <arg path="${project.basedir}/build/code-browser"/>
                </exec>
        </target>
        <target name="check" description="Check variables" >
            <fail unless="version" message="Version not defined!" />
            <fail unless="buildnumber" message="buildnumber not defined!" />
            <fail unless="buildid" message="buildid not defined!" />
            <delete dir="dist" failonerror="false" />
            <mkdir dir="dist" />
        </target>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
        <target name="tar" depends="check" description="Create tar file for release">
            <echo msg="Creating distribution tar for ${phing.project.name} ${version}"/>
            <delete file="${distfile}" failonerror="false"/>
            <tar destfile="${distfile}" compression="gzip">
                <fileset refid="api.tar.gz"/>
            </tar>
        </target>
</project>
Copy after login

After reading the build.xml, you can understand the content:


Project name , version, package name after printing:

<project name="api" default="build">
        <target name="build" depends="make_runtime,phpcs-ci,phploc,pdepend,phpcb,phpunit,phpdox,phpcpd"/>
        <property name="version-m"  value="1.1" />
        <property name="version"    value="1.1.0" />
        <property name="stability"  value="stable" />
        <property name="releasenotes" value="" />
        <property name="tarfile"     value="${phing.project.name}.${buildnumber}.${buildid}.tar.gz" />
        <property name="pkgfile"     value="${phing.project.name}.${version}.tgz" />
        <property name="distfile"    value="dist/${tarfile}" />
        <property name="tests.dir" value="test" />
Copy after login

Files and folders included when packaging: You can also use exclude to exclude files and folders:

<fileset id="api.tar.gz" dir=".">
           <include name="test/**"/>
           <include name="*.php"/>
           <include name="*.xml"/>
       </fileset>
Copy after login

The address of the test file:

<target name="phpunit" description="Run unit tests with PHPUnit">
                <exec executable="phpunit" />
        </target>
        <target name="test" description="Run PHPUnit tests">
            <phpunit haltonerror="true" haltonfailure="true" printsummary="true">
            <batchtest>
            <fileset dir="${tests.dir}">
                <include name="**/*Test.php" />
            </fileset>
            </batchtest>
            </phpunit>
        </target>
Copy after login

After understanding these, we started to Create a new autoTestTarAndPublish project in Jenkins, select: Build a free-style software project:

and specify the code base: as shown in the picture

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

Then add the build step ->Invoke Phing targets:

Add two target: test, tar respectively correspond to the test and tar names in build. Add a host under Publish over SSH: (Here Zhainiao settings use ssh password-free login) It needs to be set to password-less login from jenkins to the web server to be published

As shown in the figure:Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

Add settings here The host name is: 134

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

Next we can set up the deployment work:


Select in the table below to add the build step: Send files or execute commands over SSh. If this option does not appear, it needs to be in the plug-in management Install the plug-in: Publish Over SSH and then restart jenkins.


Then select the host to be published in the SSH Publishers that appears:

and fill in the package file address, publish to the remote server address information, and in the Exec command Fill in the text box with shell scripts such as decompression:

See the picture for details:

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

After this setting is completed, you can publish the php project to the 134 server:

Archiving of the final file release package:

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

Add post-build steps:


填写dist/*.tar.gz

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

至此配置完毕后,点击 保存 按钮.我们就可以发布程序到指定服务器134上了.


来看一下发布结果:

回到项目左侧点击:立即构建:可以看到构建进度条,结束后可以在控制台看到输出结果:

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

我们来到134上看:

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

至此发布完毕.


此时我们查看一下test/DemoTest.php文件内容:

<?php
class DemoTest extends PHPUnit_Framework_TestCase {
  public function testPass() {
      $this->assertTrue(true);
    }
  public function testFail() {
      $this->assertFalse(false);
    }
}
?>
Copy after login
Copy after login

我们把 testFail()改成下面:

<?php
class DemoTest extends PHPUnit_Framework_TestCase {
  public function testPass() {
      $this->assertTrue(true);
    }
  public function testFail() {
     $this->assertTrue(false);
    }
}
?>
Copy after login

$this->assertTrue(false);

这个是错误的断定:

提交文件后再次构建:

我们可以看到本次构建失败,查看输出结果如下:

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

当把测试用例修改回正确后,执行构建,发布正确。

<?php
class DemoTest extends PHPUnit_Framework_TestCase {
  public function testPass() {
      $this->assertTrue(true);
    }
  public function testFail() {
      $this->assertFalse(false);
    }
}
?>
Copy after login
Copy after login

Implement automated testing, automatic packaging and automatic deployment of PHP projects based on Jenkins

ok,到此介绍结束.

总结一下:

jenkins根据项目根目录下的build.xml文件,并根据jenkins中targets的配置,首先自动执行test,当测试通过后,开始执行tar,打包完成后,开始链接远程webserver把程序包上传到远程webserver指定目录下,然后再根据jenkins下的command 执行解压操作,然后就可以根据自己的业务通过shell脚本进行自动处理自动发布的各项操作.


如果在执行test过程中,出现发现测试用例不通过,则就发出错误报告,终止本次构建。


以上就是基于Jenkins 实现php项目的自动化测试、自动打包和自动部署的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Python scripts to implement automated testing in Linux environment How to use Python scripts to implement automated testing in Linux environment Oct 05, 2023 am 11:51 AM

How to use Python scripts to implement automated testing in the Linux environment. With the rapid development of software development, automated testing plays a vital role in ensuring software quality and improving development efficiency. As a simple and easy-to-use programming language, Python has strong portability and development efficiency, and is widely used in automated testing. This article will introduce how to use Python to write automated test scripts in a Linux environment and provide specific code examples. Environment Preparation for Automation in Linux Environment

Write automated test samples using Go language Write automated test samples using Go language Jun 03, 2023 pm 07:31 PM

With the rapid development of software development, automated testing plays an increasingly important role in the development process. Compared with manual testing, automated testing can improve the efficiency and accuracy of testing and reduce delivery time and costs. Therefore, mastering automated testing becomes very necessary. Go language is a modern and efficient programming language. Due to its unique concurrency model, memory management and garbage collection mechanism, it has been widely used in web applications, network programming, large-scale concurrency, distributed systems and other fields. In terms of automated testing,

How to handle automated testing and deployment of services in a microservices architecture? How to handle automated testing and deployment of services in a microservices architecture? May 17, 2023 am 08:10 AM

With the rapid development of Internet technology, microservice architecture is becoming more and more widely used. Using a microservice architecture can effectively avoid the complexity and code coupling of a single application, and improve the scalability and maintainability of the application. However, unlike monolithic applications, in a microservice architecture, there are a huge number of services, and each service requires automated testing and deployment to ensure the quality and reliability of the service. This article will discuss how to handle automated testing and deployment of services in a microservices architecture. 1. Automated testing in microservice architecture Automated testing is the guarantee

Java and Linux Scripting: How to Automate Testing Java and Linux Scripting: How to Automate Testing Oct 05, 2023 am 08:50 AM

Java and Linux Script Operations: Methods and Examples for Implementing Automated Testing Introduction: In the software development process, automated testing can greatly improve testing efficiency and quality. By using Java language and Linux scripts, we can write powerful automated test scripts to automatically execute test cases, generate test reports and other functions. This article will introduce how to use Java and Linux scripts to implement automated testing and provide some specific code examples. 1. Java automated testing: Java is a

Integration testing of go-zero: realizing automated non-destructive testing of API services Integration testing of go-zero: realizing automated non-destructive testing of API services Jun 22, 2023 pm 02:06 PM

As Internet companies continue to grow, software development becomes more and more complex, and testing becomes more and more important. In order to ensure the correctness and stability of the program, various types of tests must be performed. Among them, automated testing is a very important way. It can improve the efficiency of testing work, reduce error rates, and allow repeated execution of test cases to detect problems early. However, in the actual operation process, we will also encounter various problems, such as Issues such as selection of testing tools, writing of test cases, and setting up of test environment. go-zero

Detailed explanation of API documentation and automated testing in the Gin framework Detailed explanation of API documentation and automated testing in the Gin framework Jun 22, 2023 pm 09:43 PM

Gin is a web framework written in Golang. It has the advantages of efficiency, lightweight, flexibility, relatively high performance, and easy to use. In Gin framework development, API documentation and automated testing are very important. This article will take an in-depth look at API documentation and automated testing in the Gin framework. 1. API documentation API documentation is used to record the detailed information of all API interfaces to facilitate the use and understanding of other developers. The Gin framework provides a variety of API documentation tools, including Swagger, GoSwa

The significance of Go language return value type inference for automated testing The significance of Go language return value type inference for automated testing Apr 29, 2024 pm 04:45 PM

Go language return type inference simplifies automated testing: it allows the compiler to infer the return type based on the function implementation, eliminating the need for explicit declarations. Improve the simplicity and readability of test functions and simplify function output verification. Practical cases show how to use type inference to write automated tests to verify that function output meets expectations.

Future-oriented AI automated testing tools Future-oriented AI automated testing tools Apr 08, 2023 pm 05:01 PM

Translator | Reviewed by Chen Jun | Sun Shujuan In recent years, automated testing has undergone major iterations. It assists the QA team in reducing the possibility of human errors to a great extent. Although there are many tools that can be used for automated testing, the right tool has always been the key to the success or failure of automated testing. At the same time, with the widespread use of artificial intelligence, machine learning and neural networks in various fields, automated testing for artificial intelligence also requires appropriate tools to undertake repetitive work, so as to save valuable time of the project team and perform more precise tasks. Complex and critical tasks. Below, I will discuss with you in depth the future-oriented AI automated testing tools. What is artificial intelligence (AI) automated testing? AI automated testing means existing software

See all articles