CircleCIでPHPUnit

Aug 23, 2020 PHP GitHub PHPUnit Composer CircleCI

#Introduction This article aims to automate CI with PHPUnit using CircleCI, and the following figure is a memorandum through one sequence. ![Screenshot 2020-08-08 17.21.37.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/377612/a44f6bc3-b0f9-301d-76f3-(7e7a0c424d6d.png)

GitHub repository is here [https://github.com/sakamotoyuya/circleci-phpunit)

#Environment macOS Catalina:10.15.5 (19F101) php 7.4.9 composer 1.10.10 PHPUnit 9.3.7

table of contents

Assumptions

The procedure in this article is based on the assumption that GitHub registration work has been completed in advance. Also, as shown in the figure above, knowledge of the following technologies is required.

Register CircleCI

Create a repository for CI integration on GitHub

Get # composer To get composer, you need to install php on mac and cut the path in advance. By the way, mac includes php from the beginning, but when the version of macOS is raised, the php settings may change as backup, so in my environment [xampp](https://www.apachefriends.org/(jp/index.html) is downloaded and put in “xamppfies/bin” of xampp not through path so that php command can be used from terminal. In this state, composer can be downloaded by the following procedure.

First, move to the directory where you want to download composer.

cd project folder

Then download composer referring to the following.

Excerpt from composer homepage

php -r "copy('https://getcomposer.org/installer','composer-setup.php');"
php -r "if (hash_file('sha384','composer-setup.php') ==='e5325b19b381bfd88ce90a5ddb7823406b2a38cff6bb704b0acc289a09c8128d4a8ce2bbafcd1fcbdc38666422fe2806') (echo'installer'er echo'installer verify'installer verified' php');} echo PHP_EOL;"
php composer-setup.php
php -r "unlink('composer-setup.php');"

After downloading composer.phar, make sure the composer you downloaded works excluding the extension. *Although it can be operated as phar, the extension is omitted to shorten the command.

sakamotoyuya:circleci-phpunit sakamotoyuya$ mv composer.phar composer
sakamotoyuya:circleci-phpunit sakamotoyuya$ ./composer -v
   ______
  / ____/___ ____ ___ ____ ____ ________ _____
 / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__) __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 1.10.10 2020-08-03 11:35:19

Usage:
  command [options] [arguments]

Options:
...

Install PHPUnit with composer

{
    "autoload": {
        "classmap": [
            "src/"
        ]
    },
    "require-dev": {
        "phpunit/phpunit": "^9"
    }
}

There are psr-4, psr-0, classmap, and files in the autoload method, but this time we will target the classmap that reads all the specified directories. ..

See the following for details on autoloading. composer documentation-autoload

The destination of autoload is set to src/, and the following modules are automatically loaded in this folder.

require-dev is called a package link. See the following for details of the package link. composer documentation-package links

There are two package links, require (for production) and require-dev (for development). For details on how to use this, refer to the following for easy understanding. [Laravel] Development of composer require-dev, separation in production

$ composer install --no-dev

Since the development package is not required in the production environment, execute the composer command with the –no-dev option. Then the libraries listed in the require-dev option will not be installed in vendorIn short, whether to install the package is decided by switching the compile option. Since PHPUnit is not used for production, by putting it in require-dev and adding the –no-dev compile option, the operation will not be introduced.

Root directory
|-.git: hidden folder
|- src folder
|- composer file
|- composer.json file
|- README.md file
$ ./composer install

To execute the composer command, you need the executable file composer and the configuration file composer.json read by the executable file. You need to move to the place where the file is stored and execute it. This procedure creates the vendor folder. Packages are installed in the vendor folder below, but this folder is often large or variable, so create a .gitignore file and exclude it from git management.

vendor
Root directory
|-.git: hidden folder
|-.gitignore file...⭐️
|- src folder...
|- vendor: Folder installed by ⭐️ composer
| |-bin
│ | | |- phpunit・・・⭐️ phpunit executable
| ~
|- composer file
|- composer.json file
|- README.md file

Create a test file to execute manually with PHPUnit

<?php
class Human{
    public function helloString(){
        return "Hello";
    }
    public function goodnightString(){
        return "Good night";
    }
}
Root directory
|-.git: hidden folder
|- src folder...
│ |- Human.php ・・・⭐️ Evaluation target module
|
|-tests folder...⭐️
|- vendor: folder installed by composer
| |- bin
| | |- phpunit... phpunit executable file
| ~
|- composer file
|- composer.json file
|- README.md file

<?php
use PHPUnit\Framework\TestCase;
final class SakamotoTest extends TestCase{
    public function testA(){
        $obj = new Human();
        $this->assertSame("hello", $obj->helloString());
    }
    public function testB(){
        $obj = new Human();
        // $this->assertSame("Oh Ma Iyuga!", $obj->goodnightString());
        $this->assertSame("Good night", $obj->goodnightString());
    }

    public function testD(){
        $obj = new Human();
        $this->assertSame("Good night", $obj->goodnightString());
    }
}

There is a rule for the file name of the test code, and it is necessary to use something like "file name of the module you want to test + Test.php". Since we want to test Human.php this time, the file name is HumanTest.php. Also, it seems that the class name in the contents of HumanTest.php can be operated even if it is different from the file name. The test could be executed even with the SakamotoTest class as a trial. There is no point in doing so, so it is better to read the class name as HumanTest according to the file name. This time it is a trial code as above, but let’s use the HumanTest class when actually creating it.

Root directory
|-.git: hidden folder
|- src folder...
| |- Human.php ・・・ Module to be evaluated
|
|- tests ・・・ folder
| |-- HumanTest.php・・・⭐️Test file
|
|- vendor: folder installed by composer
| |- bin
| | |- phpunit... phpunit executable file
| ~
|- composer file
|- composer.json file
|- README.md file

Run PHPUnit manually

$ ./composer dump-autoload

You need to run this command if you have updated the files in your project. If you do not do this, it will start in the state before the change.

$ ./vender/bin/phpunit tests

Specify the folder that contains the test code. This time, specify the tests folder. If there is no problem, the result will be as follows.

sakamotoyuya:circleci-phpunit sakamotoyuya$ ./vendor/bin/phpunit tests
PHPUnit 9.3.7 by Sebastian Bergmann and contributors.


Warning: Test case class not matching filename is deprecated
               in /Users/sakamotoyuya/Documents/GitHub/circleci-phpunit/tests/HumanTest.php
               Class name was'SakamotoTest', expected'HumanTest'

... 3/3 (100%)

Time: 00:00.016, Memory: 4.00 MB

OK (3 tests, 3 assertions)
... 3/3 (100%)

Time: 29 ms, Memory: 4.00 MB

OK (3 tests, 3 assertions)

If the result is OK like this, the test is OK. Since the sample code HumanTest.php only compares the character strings, you can check it even if it is NG by replacing the commented out parts. Up to here for manual confirmation. From now on, this flow will be automated using CircleCI.

git add.
git commit -m "create test environment with phpunit"
git push

Here’s what GitHub looks like after the push. ![Screenshot 2020-08-23 8.20.57.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/377612/b7abd4f7-83d6-6a19-bed6-(fe7da7027046.png)

Link CI Circle and repository created on GitHub

Did you add the config.yml file?
If you have already added .circleci/config.yml then you can start building your project.
If not, download the config.yml file before starting the build and
Add to a new folder named .circleci at the root of the repository.

The configuration file of .circleci/config.yml is required directly under the root directory, so create the configuration file according to this.- .circleci/config.ymlを以下の内容で作成する。

version: 2.1
jobs:
  build:
    environment:
      TZ: "Asia/Tokyo"
      DEBIAN_FRONTEND: noninteractive
    docker: 
      - image: ubuntu:latest # the primary container, where your job's commands are run
        environment:
          TZ: "Asia/Tokyo"
          DEBIAN_FRONTEND: noninteractive
    steps:
      - checkout # check out the code in the project directory
      - run: apt-get update && apt-get install -y tzdata
      - run: apt-get install -y wget sudo gnupg
      - run: sudo apt-get update
      - run: sudo apt-get upgrade -y
      - run: sudo apt install -y php
      - run: sudo apt-get install -y php-mbstring
      - run: sudo apt-get install -y php-xml
      - run: sudo apt-get install -y zip
      - run: sudo apt-get install -y unzip
      - run: echo "Set disable_coredump false" >> /etc/sudo.conf
      - run: php ./composer install && ./vendor/bin/phpunit tests

設定ファイルの詳細は後で記載する。

ルートディレクトリ
|- .git       ・・・隠しフォルダ
|- .circleci
|  |- config.yml ・・・⭐️circleciの設定ファイル
|
|- src       ・・・フォルダ
|  |- Human.php   ・・・評価対象モジュール
|
|- tests      ・・・フォルダ
|  |- HumanTest.php・・・Testファイル
|
|- vendor     ・・・composerによりインストールされたフォルダ
|  |- bin
|  |   |- phpunit・・・phpunitの実行ファイル
|  ~
|- composer    ・・・ファイル
|- composer.json ・・・ファイル
|- README.md    ・・・ファイル
git add .
git commit -m "CircleCIの設定ファイル(config.yml)を作成"
git push

※GitHubの画面は省略する。

このようになるのでcircleci-phpunit #2Actionsの一番左のアイコンをクリックする。 スクリーンショット 2020-08-23 10.20.42.png

セットアップできているか確認できるのでSUCCESSとなっていれば問題ありませんね。 CircleCIとGitHubリポジトリとの連携は完了です。 これでローカルのソースコードを修正してGitHubにプッシュした際にCircleCIが自動的にデバッグphpunitを実行してくれる環境を作成することができました。 実際にプッシュして試す。

CircleCIでPHPUnitを動作させるためにGitHubにTestコードを修正してプッシュしてみる

# circleci-phpunit
テスト

コマンドで以下を実行する。

git add .
git commit -m "README.mdの修正"
git push

おまけ・・・config.yml作成時につまづいた点について