PhpUnit interface API unit test

Keywords: PHP curl network

1, Install PhpUnit

1. Download phpunit: Click to enter

2. Configure phpunit:

1) Add environment variable

Right click my computer and select properties. Click Advanced system settings on the left. At this time, system properties will pop up, select Advanced tab, and click environment variable in the lower right corner. In the user variable, double-click PATH, and add D:\repository\CourseManagement\mobile_api_test after the value of the variable (note the semicolon at the front, and the PATH to store phpunit.phar). This is configured to use PHPUnit at any location. If not, PHPUnit can only be used in the PATH of phpunit.phar.

2) Configuration:

Enter the path where phpunit.phar is stored and run in the command window

echo @php "%~dp0phpunit.phar" %* > phpunit.cmd

2, Project catalog file

1.API request class

Directory:. / lib/CurlClient.php

<?php
/**
 * http client operation class encapsulating curl
 */
class CurlClient {
    /**
     * Execute get request
     *
     * @access public
     * @param string $url Remote address
     * @param string $cookie cookie
     * @param array $options curl To configure
     * @param integer $time_out Read data timeout
     * @param integer $con_timeout Connection timeout
     * @return array
     */
    public function get($url,$cookie="", array $options=array(), $time_out=30, $con_timeout=20) {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $con_timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $time_out);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);

        foreach ($options as $key => $val) {
            curl_setopt($ch, $key, $val);
        }
        unset($val);

        // Execute the remote request and clear the bom output of utf8
        $content = $this -> remove_utf8_bom(curl_exec($ch));
        // Status code can only be obtained after execution
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if($httpcode != 200){
            die("network error");
        }

        return $content;
    }

    /**
     * Execute post request
     *
     * @access public
     * @param string $url Remote address
     * @param mixed $data Data set
     * @param string $cookie cookie
     * @param array $options curl To configure
     * @param integer $timeout Read data timeout
     * @param integer $con_timeout Connection timeout
     * @return string
     */
    public function post($url, $data=null,$cookie="",$is_show_header=0, array $options=array(), $timeout=30, $con_timeout=20) {

        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_HEADER, $is_show_header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $con_timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_COOKIE, $cookie);

        !empty($data) and curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        foreach ($options as $key => $val) {
            curl_setopt($ch, $key, $val);
        }
        unset($val);

        // Execute the remote request and clear the bom output of utf8
        $ch_res = curl_exec($ch);
        if($is_show_header){
            $content  = $this -> get_cookie($ch_res);
        }else{
            $content  = $this -> remove_utf8_bom($ch_res);
        }
        //Status code can only be obtained after execution
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if($httpcode != 200){
            die("network error");
        }
        curl_close($ch);

        return $content;
    }

    /**
     * Clear the bom head of utf-8
     *
     * @access public
     * @param string $text Character string
     * @return string
     */
    private function remove_utf8_bom($text) {
        $bom = pack('H*', 'EFBBBF');
        $text = preg_replace("/^{$bom}+?/", '', $text);

        return $text;
    }
    private function get_cookie($text){
        list($header, $body) = explode("\r\n\r\n", $text);
        preg_match("/set\-cookie:([^\r\n]*)/i", $header, $matches);
        $cookie = explode(';', $matches[1])[0];
        return $cookie;
    }
}

/* End of this file */

2. Basic configuration class: configuration domain name, reference request class

Directory:. / project/config.php

<?php
require_once(dirname(__FILE__)."/../lib/CurlClient.php");
define("PREFIX", "http://localhost.insure.qy.com");

3.API unit test class:

Directory:. / project/TestAPI.php

<?php
require_once(dirname(__FILE__) . '/config.php');
use PHPUnit\Framework\TestCase;

class TestAPI extends TestCase
{
    /** Test login and keep cookie s */
    public function testLogin()
    {
        $param = array(
            "ajax_act"=>"login",
            'data' => '{"acct":"admin","password":"adminpass","code":"","cache_acct":1}'
        );
        $url = '/index.php?m=login';
        $cookie = $this->get_post_cookie($url, $param);
        file_put_contents("./cookie.txt",$cookie);
        $this->assertEquals(1, 1);

    }
    /** 100 Save form */
    public function testForm100()
    {
        $param = array(
            'data' => '{"title_item":"input157846865167924"}'
        );
        $url = '/index.php?model=form&m=ajax&cmd=100';
        $this->call_post($url, $param);
    }
    /** 101 Get form list */
    public function testForm101()
    {
        $param = array();
        $url = '/index.php?model=form&m=ajax&cmd=101';
        $this->call_post($url, $param);
    }

    private function call_get($path, $param, $expect = '0')
    {
        $curl = new CurlClient();
        $url = PREFIX . "$path?" . http_build_query($param);
        $buf = $curl->get($url);
        $obj = json_decode($buf, True);
        $this->assertEquals($obj['errcode'], $expect);
        return $obj;
    }

    private function call_post($path, $param, $expect = '0')
    {
        $curl = new CurlClient();
        $url = PREFIX . $path ;
        $cookie = file_get_contents("./cookie.txt");
        $buf = $curl->post($url,$param,$cookie);
        $obj = json_decode($buf, True);
        if($obj['errcode'] != 0) {
            print_r([
                "url"=>$url,
                "obj"=>$obj
            ]);
            die;
        }
        $this->assertEquals($obj['errcode'], $expect);
        return [$obj,$cookie];
    }
    private function get_post_cookie($path, $param)
    {
        $curl = new CurlClient();
        $url = PREFIX . $path ;
        $cookie = $curl->post($url,$param,"",1);
        return $cookie;
    }
}

3, Test run

phpunit TestFormApi.php

4, Normal results

Published 20 original articles, won praise 2, visited 10000+
Private letter follow

Posted by neroag on Thu, 16 Jan 2020 10:42:29 -0800