Skip to content

Commit

Permalink
[TASK-11.5C] Fix - "Unit" Tests
Browse files Browse the repository at this point in the history
Notes:

* Replaces `GeneralUtility::isFirstPartOfStr()` with 
   PHP8(or Symfony Polyfills 8.0) `str_starts_with()`  

Fixes: TYPO3-Solr#3089
Relates: TYPO3-Solr#2976, TYPO3-Solr#2977
  • Loading branch information
dkd-kaehm committed Dec 2, 2021
1 parent d71ec45 commit 5e047c5
Show file tree
Hide file tree
Showing 22 changed files with 109 additions and 81 deletions.
14 changes: 7 additions & 7 deletions Build/Test/UnitTests.xml
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<phpunit
<?xml version="1.0"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd"
backupGlobals="false"
backupStaticAttributes="false"
colors="true"
Expand All @@ -11,15 +12,14 @@
stopOnIncomplete="false"
stopOnSkipped="false"
verbose="false">

<coverage processUncoveredFiles="false">
<include>
<directory suffix=".php">../../Classes/</directory>
</include>
</coverage>
<testsuites>
<testsuite name="ext-solr-unit-tests">
<directory>../../Tests/Unit/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="false">
<directory suffix=".php">../../Classes/</directory>
</whitelist>
</filter>
</phpunit>
8 changes: 4 additions & 4 deletions Build/Test/cibuild.sh
Original file line number Diff line number Diff line change
Expand Up @@ -61,28 +61,28 @@ fi
# Map the travis and shell variable names to the expected
# casing of the TYPO3 core.
#
if [ -n $TYPO3_DATABASE_NAME ]; then
if [[ -n $TYPO3_DATABASE_NAME ]]; then
export typo3DatabaseName=$TYPO3_DATABASE_NAME
else
echo "No environment variable TYPO3_DATABASE_NAME set. Please set it to run the integration tests."
exit 1
fi

if [ -n $TYPO3_DATABASE_HOST ]; then
if [[ -n $TYPO3_DATABASE_HOST ]]; then
export typo3DatabaseHost=$TYPO3_DATABASE_HOST
else
echo "No environment variable TYPO3_DATABASE_HOST set. Please set it to run the integration tests."
exit 1
fi

if [ -n $TYPO3_DATABASE_USERNAME ]; then
if [[ -n $TYPO3_DATABASE_USERNAME ]]; then
export typo3DatabaseUsername=$TYPO3_DATABASE_USERNAME
else
echo "No environment variable TYPO3_DATABASE_USERNAME set. Please set it to run the integration tests."
exit 1
fi

if [ -n $TYPO3_DATABASE_PASSWORD ]; then
if [[ -n $TYPO3_DATABASE_PASSWORD ]]; then
export typo3DatabasePassword=$TYPO3_DATABASE_PASSWORD
else
echo "No environment variable TYPO3_DATABASE_PASSWORD set. Please set it to run the integration tests."
Expand Down
2 changes: 1 addition & 1 deletion Classes/Domain/Search/Query/ParameterBuilder/Filters.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public function removeByFieldName($filterFieldName)
public function removeByPrefix($filterFieldName)
{
foreach ($this->filters as $key => $filterString) {
if (GeneralUtility::isFirstPartOfStr($filterString, $filterFieldName)) {
if (\str_starts_with($filterString, $filterFieldName)) {
unset($this->filters[$key]);
}
}
Expand Down
3 changes: 2 additions & 1 deletion Classes/IndexQueue/PageIndexer.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use ApacheSolrForTypo3\Solr\Domain\Index\PageIndexer\Helper\UriBuilder\AbstractUriStrategy;
use ApacheSolrForTypo3\Solr\Domain\Index\PageIndexer\Helper\UriStrategyFactory;
use ApacheSolrForTypo3\Solr\System\Logging\SolrLogManager;
use TYPO3\CMS\Core\Type\Bitmask\PageTranslationVisibility;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
Expand Down Expand Up @@ -119,7 +120,7 @@ protected function getSolrConnectionsByItem(Item $item)
unset($solrConnections[0]);
}

if (GeneralUtility::hideIfNotTranslated($page['l18n_cfg'])) {
if ((new PageTranslationVisibility((int)$page['l18n_cfg'] ?? 0))->shouldHideTranslationIfNoTranslatedRecordExists()) {
$accessibleSolrConnections = [];
if (isset($solrConnections[0])) {
$accessibleSolrConnections[0] = $solrConnections[0];
Expand Down
5 changes: 3 additions & 2 deletions Classes/System/UserFunctions/FlexFormUserFunctions.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use ApacheSolrForTypo3\Solr\System\Configuration\ExtensionConfiguration;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Utility\LocalizationUtility;
use function str_starts_with;

/**
* This class contains all user functions for flexforms.
Expand Down Expand Up @@ -82,9 +83,9 @@ protected function getParsedSolrFieldsFromSchema($configuredFacets, $pageRecord)
$configuredFacet = array_values($configuredFacets);
$label = $configuredFacet[0]['label'];
// try to translate LLL: label or leave it unchanged
if (GeneralUtility::isFirstPartOfStr($label, 'LLL:') && $this->getTranslation($label) != '') {
if (str_starts_with($label, 'LLL:') && $this->getTranslation($label) != '') {
$label = $this->getTranslation($label);
} elseif (!GeneralUtility::isFirstPartOfStr($label, 'LLL:') && $configuredFacet[0]['label.']) {
} elseif (!str_starts_with($label, 'LLL:') && $configuredFacet[0]['label.']) {
$label = sprintf('cObject[...faceting.facets.%slabel]', array_keys($configuredFacets)[0]);
}
$label = sprintf('%s (Facet Label: "%s")', $value, $label);
Expand Down
2 changes: 1 addition & 1 deletion Tests/Unit/ContentObject/ClassificationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ protected function setUp(): void
$GLOBALS['TSFE'] = $this->getDumbMock(TypoScriptFrontendController::class);

$this->contentObject = $this->getMockBuilder(ContentObjectRenderer::class)
->setMethods(['getResourceFactory', 'getEnvironmentVariable'])
->onlyMethods(['getResourceFactory', 'getEnvironmentVariable', 'getRequest'])
->setConstructorArgs([$GLOBALS['TSFE']])->getMock();
}

Expand Down
2 changes: 1 addition & 1 deletion Tests/Unit/ContentObject/MultivalueTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ protected function setUp(): void
$GLOBALS['TSFE'] = $this->getDumbMock(TypoScriptFrontendController::class);

$this->contentObject = $this->getMockBuilder(ContentObjectRenderer::class)
->setMethods(['getResourceFactory', 'getEnvironmentVariable'])
->setMethods(['getResourceFactory', 'getEnvironmentVariable', 'getRequest'])
->setConstructorArgs([$GLOBALS['TSFE']])->getMock();
}

Expand Down
27 changes: 17 additions & 10 deletions Tests/Unit/Domain/Search/ApacheSolrDocument/RepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,14 @@
use ApacheSolrForTypo3\Solr\Domain\Search\ApacheSolrDocument\Repository;
use ApacheSolrForTypo3\Solr\Domain\Search\Query\QueryBuilder;
use ApacheSolrForTypo3\Solr\Domain\Search\Query\Query;
use ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\Result\Parser\DocumentEscapeService;
use ApacheSolrForTypo3\Solr\NoSolrConnectionFoundException;
use ApacheSolrForTypo3\Solr\Search;
use ApacheSolrForTypo3\Solr\Domain\Site\Site;
use ApacheSolrForTypo3\Solr\SolrService;
use ApacheSolrForTypo3\Solr\System\Solr\Service\AbstractSolrService;
use ApacheSolrForTypo3\Solr\System\Solr\Document\Document;
use ApacheSolrForTypo3\Solr\System\Solr\ResponseAdapter;
use ApacheSolrForTypo3\Solr\Tests\Unit\UnitTest;
use InvalidArgumentException;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
Expand Down Expand Up @@ -66,31 +66,35 @@ public function findOneByPageIdAndByLanguageIdReturnsFirstFoundDocument()
{
$apacheSolrDocumentCollection = [new Document(), new Document()];
$apacheSolrDocumentRepository = $this->getAccessibleMock(Repository::class, ['findByPageIdAndByLanguageId']);
$apacheSolrDocumentRepository->expects($this->at(0))->method('findByPageIdAndByLanguageId')->will($this->returnValue($apacheSolrDocumentCollection));
$apacheSolrDocumentRepository
->expects($this->exactly(1))
->method('findByPageIdAndByLanguageId')
->will($this->returnValue($apacheSolrDocumentCollection));

/* @var $apacheSolrDocumentRepository Repository */
$this->assertSame($apacheSolrDocumentCollection[0], $apacheSolrDocumentRepository->findOneByPageIdAndByLanguageId(0, 0));
}

/**
* @test
* @expectedException \InvalidArgumentException
* @expectedExceptionCode 1487332926
*/
public function findByPageIdAndByLanguageIdThrowsInvalidArgumentExceptionIfPageIdIsNotSet()
{

$this->expectException(InvalidArgumentException::class);
$this->expectExceptionCode(1487332926);
/* @var $apacheSolrDocumentRepository Repository */
$apacheSolrDocumentRepository = GeneralUtility::makeInstance(Repository::class);
$apacheSolrDocumentRepository->findByPageIdAndByLanguageId(null, 3);
}

/**
* @test
* @expectedException \InvalidArgumentException
* @expectedExceptionCode 1487335178
*/
public function findByPageIdAndByLanguageIdThrowsInvalidArgumentExceptionIfLanguageIdIsNotInteger()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionCode(1487335178);
/* @var $apacheSolrDocumentRepository Repository */
$apacheSolrDocumentRepository = GeneralUtility::makeInstance(Repository::class);
$apacheSolrDocumentRepository->findByPageIdAndByLanguageId(1, 'Abc');
Expand All @@ -103,7 +107,10 @@ public function findByPageIdAndByLanguageIdReturnsEmptyCollectionIfConnectionToS
{
/* @var $apacheSolrDocumentRepository Repository */
$apacheSolrDocumentRepository = $this->getAccessibleMock(Repository::class, ['initializeSearch']);
$apacheSolrDocumentRepository->expects($this->at(0))->method('initializeSearch')->will($this->throwException(new NoSolrConnectionFoundException()));
$apacheSolrDocumentRepository
->expects($this->exactly(1))
->method('initializeSearch')
->will($this->throwException(new NoSolrConnectionFoundException()));

$apacheSolrDocumentCollection = $apacheSolrDocumentRepository->findByPageIdAndByLanguageId(777, 0);
$this->assertEmpty($apacheSolrDocumentCollection);
Expand All @@ -116,9 +123,9 @@ public function findByPageIdAndByLanguageIdReturnsEmptyCollectionIfConnectionToS
public function findByPageIdAndByLanguageIdReturnsResultFromSearch()
{

$solrServiceMock = $this->getDumbMock(SolrService::class);
$AbstractSolrServiceMock = $this->getDumbMock(AbstractSolrService::class);
$solrConnectionManager = $this->getAccessibleMock(ConnectionManager::class, ['getConnectionByPageId'], [], '', false);
$solrConnectionManager->expects($this->any())->method('getConnectionByPageId')->will($this->returnValue($solrServiceMock));
$solrConnectionManager->expects($this->any())->method('getConnectionByPageId')->will($this->returnValue($AbstractSolrServiceMock));
$mockedSingletons = [ConnectionManager::class => $solrConnectionManager];

$search = $this->getAccessibleMock(Search::class, ['search', 'getResultDocumentsEscaped'], [], '', false);
Expand Down
10 changes: 5 additions & 5 deletions Tests/Unit/Domain/Search/Query/QueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
use ApacheSolrForTypo3\Solr\Domain\Search\Query\ParameterBuilder\Elevation;
use ApacheSolrForTypo3\Solr\Domain\Search\Query\ParameterBuilder\Faceting;
use ApacheSolrForTypo3\Solr\Domain\Search\Query\ParameterBuilder\FieldCollapsing;
use ApacheSolrForTypo3\Solr\Domain\Search\Query\ParameterBuilder\Filters;
use ApacheSolrForTypo3\Solr\Domain\Search\Query\ParameterBuilder\Grouping;
use ApacheSolrForTypo3\Solr\Domain\Search\Query\ParameterBuilder\Highlighting;
use ApacheSolrForTypo3\Solr\Domain\Search\Query\ParameterBuilder\Operator;
Expand All @@ -47,6 +46,7 @@
use ApacheSolrForTypo3\Solr\Tests\Unit\UnitTest;
use Solarium\QueryType\Select\RequestBuilder;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use function str_starts_with;

/**
* @author Timo Hund <timo.hund@dkd.de>
Expand Down Expand Up @@ -456,7 +456,7 @@ public function groupingIsNotActiveAfterInitialization()
$queryParameters = $query->getQueryParameters();
foreach ($queryParameters as $queryParameter => $value) {
$this->assertTrue(
!GeneralUtility::isFirstPartOfStr($queryParameter, 'group'),
!str_starts_with($queryParameter, 'group'),
'Query already contains grouping parameter "' . $queryParameter . '"'
);
}
Expand Down Expand Up @@ -496,7 +496,7 @@ public function settingGroupingFalseDeactivatesGrouping(SearchQuery $query)
$queryParameters = $this->getAllQueryParameters($query);
foreach ($queryParameters as $queryParameter => $value) {
$this->assertTrue(
!GeneralUtility::isFirstPartOfStr($queryParameter, 'group'),
!str_starts_with($queryParameter, 'group'),
'Query contains grouping parameter "' . $queryParameter . '"'
);
}
Expand Down Expand Up @@ -1201,7 +1201,7 @@ public function canSetQueryElevation()

$this->assertNull($queryParameters['enableElevation']);
$this->assertNull($queryParameters['forceElevation']);
$this->assertNotContains('isElevated:[elevated]', $queryParameters['fl']);
$this->assertStringNotContainsString('isElevated:[elevated]', $queryParameters['fl']);

// do we get the expected default values, when calling setQueryElevantion with no arguments?
Expand All @@ -1210,7 +1210,7 @@ public function canSetQueryElevation()
$queryParameters = $this->getAllQueryParameters($query);
$this->assertSame('true', $queryParameters['enableElevation'], 'enabledElevation was not set after enabling elevation');
$this->assertSame('true', $queryParameters['forceElevation'], 'forceElevation was not set after enabling elevation');
$this->assertContains('isElevated:[elevated]', $queryParameters['fl'], 'isElevated should be in the list of return fields');
$this->assertStringContainsString('isElevated:[elevated]', $queryParameters['fl'], 'isElevated should be in the list of return fields');

// can we reset the elevantion?
$elevation->setIsEnabled(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public function testWhenKeepAllOptionsOnSelectionIsNotConfiguredNoExcludeTagIsAd
$defaultQueryBuilder = new DefaultFacetQueryBuilder();
$result = $defaultQueryBuilder->build('color', $fakeConfiguration);

$this->assertNotContains('{!ex', $result['facet.field'][0]);
$this->assertStringNotContainsString('{!ex', $result['facet.field'][0]);
}

}
}
18 changes: 10 additions & 8 deletions Tests/Unit/Domain/Search/ResultSet/Facets/FacetRegistryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
use ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\Facets\FacetRegistry;
use ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\Facets\OptionBased\Options\OptionsPackage;
use ApacheSolrForTypo3\Solr\Tests\Unit\Domain\Search\ResultSet\Facets\TestPackage\TestPackage;
use InvalidArgumentException;
use PHPUnit\Framework\MockObject\MockObject;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;

Expand Down Expand Up @@ -45,14 +47,14 @@ public function setUp(): void {
/**
* Initialize a RendererRegistry and mock createRendererInstance()
*
* @param array $createsParserInstances
* @return \PHPUnit_Framework_MockObject_MockObject|FacetRegistry
* @param array $createsPackageInstances
* @return MockObject|FacetRegistry
*/
protected function getTestFacetPackageRegistry(array $createsPackageInstances = [])
{
/** @var $facetRegistry FacetRegistry */
/** @var $facetRegistry MockObject|FacetRegistry */
$facetRegistry = $this->getMockBuilder(FacetRegistry::class)
->setMethods(['createInstance'])
->onlyMethods(['createInstance'])
->getMock();

// @extensionScannerIgnoreLine
Expand Down Expand Up @@ -84,22 +86,22 @@ public function registeredPackageClassCanBeRetrievedByType()

/**
* @test
* @expectedException \InvalidArgumentException
* @expectedExceptionCode 1462883324
*/
public function registerParserClassThrowsExceptionIfClassDoesNotExist()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionCode(1462883324);
$facetParserRegistry = $this->getTestFacetPackageRegistry();
$facetParserRegistry->registerPackage($this->getUniqueId(), 'unknown');
}

/**
* @test
* @expectedException \InvalidArgumentException
* @expectedExceptionCode 1462883325
*/
public function registerParserClassThrowsExceptionIfClassDoesNotImplementFacetPackageInterface()
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionCode(1462883325);
$className = __CLASS__;
$facetParserRegistry = $this->getTestFacetPackageRegistry();
$facetParserRegistry->registerPackage($className, 'unknown');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@

use ApacheSolrForTypo3\Solr\Domain\Search\ResultSet\Facets\RangeBased\NumericRange\NumericRangeUrlDecoder;
use ApacheSolrForTypo3\Solr\Tests\Unit\UnitTest;
use InvalidArgumentException;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
Expand Down Expand Up @@ -56,7 +57,7 @@ public function setUp(): void
*
* @return array
*/
public function rangeQueryParsingDataProvider()
public function rangeQueryParsingDataProvider(): array
{
return [
['firstValue' => '50', 'secondValue' => '100', 'expected' => '[50 TO 100]'],
Expand All @@ -76,7 +77,7 @@ public function rangeQueryParsingDataProvider()
* @param string $expectedResult
* @return void
*/
public function canParseRangeQuery($firstValue, $secondValue, $expectedResult)
public function canParseRangeQuery(string $firstValue, string $secondValue, string $expectedResult)
{
$actual = $this->rangeParser->decode($firstValue . '-' . $secondValue);
$this->assertEquals($expectedResult, $actual);
Expand All @@ -86,11 +87,12 @@ public function canParseRangeQuery($firstValue, $secondValue, $expectedResult)
* Test the handling of invalid parameters
*
* @test
* @expectedException \InvalidArgumentException
*
* @return void
*/
public function canHandleInvalidParameters()
{
$this->expectException(InvalidArgumentException::class);
$this->rangeParser->decode('invalid-value');
}
}
12 changes: 10 additions & 2 deletions Tests/Unit/Domain/Search/ResultSet/SearchResultSetTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,8 +206,16 @@ public function canRegisterSearchResultSetProcessor()
$fakeRequest = new SearchRequest(['tx_solr' => ['q' => 'my 4. search']]);
$fakeRequest->setResultsPerPage(10);

$this->objectManagerMock->expects($this->at(0))->method('get')->with(SearchResultSet::class)->willReturn(new SearchResultSet());
$this->objectManagerMock->expects($this->at(1))->method('get')->with($testProcessor)->willReturn(new TestSearchResultSetProcessor());
$this->objectManagerMock
->expects($this->exactly(2))
->method('get')
->withConsecutive(
[SearchResultSet::class],
[$testProcessor]
)->will($this->onConsecutiveCalls(
new SearchResultSet(),
new TestSearchResultSetProcessor()
));

$resultSet = $this->searchResultSetService->search($fakeRequest);

Expand Down
Loading

0 comments on commit 5e047c5

Please sign in to comment.