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

PHP中文网
PHP中文网Original
2016-07-30 13:29:303731browse

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

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

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

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.

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

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>

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" />

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>

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>

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);
    }
}
?>

我们把 testFail()改成下面:

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

$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);
    }
}
?>

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:
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