Skip to content

how to properly escape a string for use in --filter #5706

Open
@staabm

Description

Q A
PHPUnit version 9.5.23
PHP version 8.2.16
Installation Method Composer / PHAR

Summary

we try to feed phpunit --filter with test-case names which we determine via --list-tests-xml.
we are wondering, how to properly escape our input strings we want to pass to phpunit via --filter option.

Current behavior

the docs mention the filter is interpreted as a regex, therefore I went with preg_quote(), but this didn't work when we use a "full qualified test-case name" which contains a #.

How to reproduce

a test-class like

<?php
namespace TestNamespace;

use PHPUnit\Framework\TestCase;

class mytest extends TestCase
{
	/**
	 * @dataProvider provider
	 */
	public function testMethod($data)
	{
		$this->assertTrue($data);
	}

	public function provider()
	{
		return [
			'my name(d data' => [true],
			'my $dat)a'       => [true]
		];
	}
}

requires a escaped filter

➜  phpstan-src git:(1.11.x) ✗ vendor/bin/phpunit mytest.php --filter 'my $dat\)a'
PHPUnit 9.5.23 #StandWithUkraine

Warning:       No code coverage driver available

No tests executed!
➜  phpstan-src git:(1.11.x) ✗ vendor/bin/phpunit mytest.php --filter 'my \$dat\)a'
PHPUnit 9.5.23 #StandWithUkraine

Warning:       No code coverage driver available

.                                                                   1 / 1 (100%)

Time: 00:00.011, Memory: 32.00 MB

OK (1 test, 1 assertion)

the escaping required looks like preg_quote and it works for the case above


the following example doesn't work with preg_quote:

<?php
namespace TestNamespace;

use PHPUnit\Framework\TestCase;

class mytest extends TestCase
{
	/**
	 * @dataProvider provider
	 */
	public function testMethod($data)
	{
		$this->assertTrue($data);
	}

	public function provider()
	{
		return [
			[true],
			[true]
		];
	}
}
➜  phpstan-src git:(quote) ✗ vendor/bin/phpunit mytest.php --filter 'mytest\#1'
PHPUnit 9.5.23 #StandWithUkraine

Warning:       No code coverage driver available

No tests executed!

Expected behavior

I wonder how to properly escape the value for the --filter option.
this would be especially important as when using the wrong filter no tests would be executed.

can we make phpunit return with a non-zero exit code, when a filter is used which does not execute any tests?

edit: I just found #4314 - which described how it should be done.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type/bugSomething is broken

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions