Skip to content

Static Data in Database is not kept/recreated for second FunctionalTest #377

Closed

Description

@sHorst

What are you trying to achieve?

Run more than one test requiring Static data in one TestClass Class

What do you get instead?

Error for missing data in static tables (in my case static_country)

How to reproduce the issue?

class PlatzTest extends FunctionalTestCase {
    
    [...]

    /**
     * @test
     */
    public function searchOverviewAction()
    {
        $response =  $this->executeFrontendSubRequest(
            (new InternalRequest())->withQueryParameters(
                [
                    'id' => self::PLATZ_CONTROLLER_PID,
                    self::PLUGIN_NAME . '[action]' => 'search',
                    self::PLUGIN_NAME . '[controller]' => 'Platz',
                ]
            )
        );

        $content = (string)$response->getBody();

        self::assertMatchesRegularExpression('#<a href=".*"> Bayern</a>#', $content);
        self::assertMatchesRegularExpression('#<a href=".*"> Nordrhein-Westfalen</a>#', $content);
    }

    /**
     * @test
     */
    public function searchBundeslandAction()
    {
        $respones = $this->executeFrontendSubRequest(
            (new InternalRequest())->withQueryParameters(
                [
                    'id' => self::PLATZ_CONTROLLER_PID,
                    self::PLUGIN_NAME . '[action]'  => 'search',
                    self::PLUGIN_NAME . '[controller]' => 'Platz',
                    self::PLUGIN_NAME . '[countryZone]' => '88',
                ]
            )
        );

        $content = (string)$respones->getBody();

        // Check if campsite 1 is listed
        self::assertMatchesRegularExpression('#Campsite 1564940472#', $content);
    }
}

Relevant code from the Tested Class:

  /**
     * @return array
     */
    private function _getAllCountryZones(): array
    {
        /** @var \SJBR\StaticInfoTables\Domain\Model\Country $de */
        $de = $this->countryRepository->findByUid($this->settings['germanyUid']??54);
        $countryZones = $this->countryZoneRepository->findByCountry($de)->toArray();

        // sort by name
        usort($countryZones, function (CountryZone $a, CountryZone $b) {
            return strnatcasecmp($a->getLocalName(), $b->getLocalName());
        });
        return $countryZones;
    }

Additional information you would like to provide?

The problem occures in the FunctionalTestCase line 303ff. Or more specific in Testbase.php::initializeTestDatabaseAndTruncateTables. It will truncate ALL tables. And does not insert the Static data back in as seen in Testbase::createDatabaseStructure().

Specify some data of the environment

  • TYPO3 testing framework version: 6.16.5 (current main has still the same issue)
  • TYPO3 version: 11.5
  • TYPO3 installation type:
  • PHP version: 7.4 and 8.0
  • Web server used + version: apache
  • Operating system: linux / docker
  • Selenium server version:
  • Browser driver (chromedriver/geckodriver...) version:
  • Browser used + version:

Activity

  1. lolli42 commented on Jul 13, 2022

    @lolli42
    Member

    Could you try if this solves your issue?

        protected function setUp(): void
        {
            parent::setUp();
            $this->withDatabaseSnapshot(function () {});
        }
    
    

    This triggers the db-snapshot functionality for second and further tests, so the imported rows of first test should survive.

    I think the problem with your patch approach is that it would collide with the snapshot logic: When static data is imported in first test, and a second tests imports it again with your patch, the snapshotter would try to add those rows a second time and would fail due to duplicate keys. So we can't combine both well, and the static import is a default thing and would always kick in with your approach.

    Maybe it's better to simply use the snapshotter in those (relatively rare?) cases, when you need static data combined with multiple tests? So, if the above solution works, I'd tend to keep it that way to avoid further trouble in this area?

  2. sHorst commented on Jul 13, 2022

    @sHorst
    Author

    i do have the snapshoter configured:

     protected function setUp(): void
        {
            // reset Headers
            self::$headers = [];
    
            // setup mbox file before the parent sets up the localconf.php
            $this->mboxPath = self::getInstancePath() . '/typo3temp/test.mbox';
            if (is_string($this->configurationToUseInTestInstance)) {
                $this->configurationToUseInTestInstance=[
                    'FE' => [
                        'lockIP' => 0,
                    ],
                    'MAIL' => [
                        'transport' => TestMboxTransport::class,
                        'transport_mbox_file' => '',
                    ],
                ];
            }
            $this->configurationToUseInTestInstance['MAIL']['transport_mbox_file'] = $this->mboxPath;
            parent::setUp();
    
            $this->withDatabaseSnapshot(/**
             * @throws Exception
             */ function () {
                $this->setupDatabase();
            });
        }

    the problem is in the setUp() of the FunctionalTestCase.php

             if (!$this->isFirstTest) {
                // Reusing an existing instance. This typically happens for the second, third, ... test
                // in a test case, so environment is set up only once per test case.
                GeneralUtility::purgeInstances();
                $this->container = $testbase->setUpBasicTypo3Bootstrap($this->instancePath);
                if ($this->initializeDatabase) {
                    $testbase->initializeTestDatabaseAndTruncateTables($dbPathSqlite, $dbPathSqliteEmpty);
                }
                $testbase->loadExtensionTables();
            } else {

    in case this is not the firstTest, it will call initializeTestDatabaseAndTruncateTables, which in turn will call truncateAllTablesForMysql which will truncate the table with this call $connection->truncate($tableName);. This will always truncate the Tables.

    It is possible, that i hold the tool wrong, but that is the code.

  3. sHorst commented on Jul 13, 2022

    @sHorst
    Author

    i see where you are heading, with the snapshot, i will check, why it does not work even though the snapshot is configured. (btw. i am on mysql)

  4. lolli42 commented on Jul 13, 2022

    @lolli42
    Member

    snapshotting as-such works: core uses it in cases where a lot of magic is done to set up db-content (for instance creating a lot of stuff via dataHandler before each test): to speed up things, snapshots are used for second and third tests. i'll also add a minor feature to the snapshot system soon.

  5. lolli42 commented on Jul 14, 2022

    @lolli42
    Member

    Talked with Stefan about this one:
    We will probably remove the auto-loading of static sql files in createDatabaseStructure(). Doing this collides with the snapshot feature, which expects an empty database when it's called (there is currently a hack to prevent issues, which should fall anyways).
    Instead, we'll establish a method that can be called to execute these imports manually, so tests that need this (relatively rare) feature can then call it manually. This will also solve the issue for subsequent tests in one test case.
    What do you think?

  6. lolli42 commented on Jul 14, 2022

    @lolli42
    Member

    Ok, yet another thought on this, aligned with Stefan:

    The fact that ext_tables_static+adt.sql files are auto-imported in the first place is unfortunate for various reasons:

    • This creates a dependency in your test to (potentially) a third party extension which can be a moving target.
    • It gives headaches with the snapshot feature which expects the DB to be empty.
    • We have solid solutions in TF to import fixture data base on CSV files. Those are designed to define DB state in detail and they bring DB state fully under control of the test setup.

    We will now go ahead in this area and deprecate the auto-import of ext_tables_static+adt.sql within createDatabaseStructure() in v6 and v7 altogether, and will remove it in main (for core >=v12).

    Extension's functional test setups that want to import these static data, then have two options:

    • (recommended): The test case provides a .csv file with the to-be-imported rows and loads it using importCSVDataSet()
    • The test case creates an own helper method that uses core SqlReader and SchemaMigrator importStaticData() similar to what is currently done in createDatabaseStructure(). The TF will not provide this as API.

    This gives the test case full control on these cases, and the "broken on subsequent test" issue is solved along the ways since TF does not import such rows by default anymore.

  7. lolli42 commented on Jul 14, 2022

    @lolli42
    Member

    Note: Many thanks for bringing this up, even if the solution is not "TF magically does it now".
    This issue and the related #359 helped a lot to review the current code and consider various possible solutions, and the resulting patches sharpen the TF responsibilities and simplify overall complexity a bit.
    I think when you adapt your test cases now, you'll see that it ends up with just a couple of straight code lines to achieve what you need in a reliable way.

  8. liayn commented on Aug 10, 2022

    @liayn
    Contributor

    This must ASAP be documented as "known issue".

    @lolli42 I understand all this and I agree with the long-term goal. It cost me 2 hours of debugging through all extbase stuff finally find this cause and create #397.

    But, I don't see a feasible way to work around this issue at the moment for v10 and v11.

    In our case we have a dependency on static_info_tables and the tables are populated for the first test. I have no problem with providing our own datasets, but how should we import those, it will fail on the first run of course, since the table is already populated, right?

  9. oliverklee commented on Aug 11, 2022

    @oliverklee
    Contributor

    @liayn I have approached this two different ways in my functional tests that use static records (e.g. countries):

    1. always create country records in the tests, but use UIDs higher than the highest real UID
    2. check if there is at least on record in the table, and if not, then import some fixture data that matches the real data
  10. liayn commented on Aug 11, 2022

    @liayn
    Contributor

    @oliverklee Thanks for the ideas. Will forward that internally.

  11. added 2 commits that reference this issue on Aug 12, 2022
  12. added a commit that references this issue on Feb 5, 2026
    fea6348
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions