在Laravel PHP单元测试中,Regex的Range值失败

问题描述 投票:0回答:2

我尝试使用以下条件制作正则表达式:

-90 < latitude < 90

-180 < longitude < 180

Should have 6 decimal points.

我的正则表达式如下:

Latitude : /^-?(0|[0-9]|[1-8][0-9]|90)\.{1}\d{6}$/

Longitude : /^-?(0|[0-9]|[1-9][0-9]|1[0-7][0-9]|180)\.{1}\d{6}$/

最大的测试通过了这个。但是当我在Php Unit中尝试这个时

Latitude : 10.000000 , Longitude: 10.000000 // Got Failed

Latitude : 0.000001 , Longitude: 0.000001 // Got Failed

Latitude : 0.000000 , Longitude: 0.000000 // Got Failed

我想也包括这3个选项。我在laravel 5.6(PHP)中使用这个正则表达式。

此外,当我这样做时,它开始在单元测试中工作。

Latitude : "10.000000" , Longitude: "10.000000" // Got Succeed

Latitude : "0.000001" , Longitude: "0.000001" // Got Succeed

Latitude : "0.000000" , Longitude: "0.000000" // Got Succeed

如果我正在试图通过Postman,那么它适用于两种情况。但是在Laravel进行PHP单元测试时却无法正常工作。

我的验证规则是:

public static $fieldValidations = [
        'serial'    => 'required|unique:panels|size:16|alpha_num',
        'latitude'  => array('required','numeric','between:-90,90','regex:/^-?(0|[0-9]|[1-8][0-9]|90)\.{1}\d{6}$/'),
        'longitude'  => array('required','numeric','between:-180,180','regex:/^-?(0|[0-9]|[1-9][0-9]|1[0-7][0-9]|180)\.{1}\d{6}$/'),
    ];

我的Php单元测试代码是

public function testStoreFailureLatitudeLongitudeAllZeroDecimalCase()
    {
        $response = $this->json('POST', '/api/panels', [
            'serial'    => 'AAAABBBBCCCC1234',
            'longitude' => 10.000000,
            'latitude'  => -20.000000
        ]);

        $response->assertStatus(201);
    }

    public function testStoreFailurePrecisionFloatDecimalValueCase()
    {
        $response = $this->json('POST', '/api/panels', [
            'serial'    => 'AAAABBBBCCCC1234',
            'longitude' => 0.000001,
            'latitude'  => 0.000001
        ]);

        $response->assertStatus(201);
    }

    public function testStoreFailurePrecisionFloatDecimalValuewithZeroCase()
    {
        $response = $this->json('POST', '/api/panels', [
            'serial'    => 'AAAABBBBCCCC1234',
            'longitude' => 0.000000,
            'latitude'  => 0.000000
        ]);

        $response->assertStatus(201);
    }

这些是失败的3个案例,并且通过邮递员可以使用相同的值。

有帮助吗?

php laravel phpunit
2个回答
0
投票
function validateLatitude($lat) {
  return preg_match('/^(\+|-)?(?:90(?:(?:\.0{1,6})?)|(?:[0-9]|[1-8][0-9])(?:(?:\.[0-9]{1,6})?))$/', $lat);
}

function validateLongitude($long) {
  return preg_match('/^(\+|-)?(?:180(?:(?:\.0{1,6})?)|(?:[0-9]|[1-9][0-9]|1[0-7][0-9])(?:(?:\.[0-9]{1,6})?))$/', $long);
}

它失败了0.0001,0.00001,0.000001


0
投票

也许对于Latitude你可以使用:

^-?(?:[1-8][0-9]|[0-9]|90)\.\d{6}$

对于经度,您可以使用:

^-?(?:1[0-7][0-9]|[1-9][0-9]|[0-9]|180)\.\d{6}$

请注意,您可以省略{1},对于0|[0-9],您可以仅使用[0-9],如果您不是指捕获的组,则可以使用非捕获组(?:进行更改。

© www.soinside.com 2019 - 2024. All rights reserved.