Kernel::System::UnitTest::Helper

NAME

Kernel::System::UnitTest::Helper – Unit test helper functions

new()

construct a helper object.

    use Kernel::System::ObjectManager;
    local $Kernel::OM = Kernel::System::ObjectManager->new(
        'Kernel::System::UnitTest::Helper' => {
            RestoreDatabase => 1,        # Runs the test in a transaction, and roll it back in the destructor.
                                         #
                                         # NOTE: Rollback does not work for changes in the database layout. If you
                                         # want to do this in your tests, you cannot use this option and must handle the rollback
                                         # yourself.
            RedeploySystemConfiguration => 1,    # (default 0), performs a forced sysconfig deployment at the end.
            UseTmpArticleDir => 1,       # (default 0), create & use a temporary article directory and clean it up afterwards.
            ProvideTestDocumentSearchIndices => 1,  # (default 0) - create and use temporary document search indices and clean them up afterwards.
            ProvideTestPGPEnvironment   => 1,  # (default 0) - configure PGP to use a temporary directory for its keyring that is cleaned up afterwards.
            ProvideTestSMIMEEnvironment => 1,  # (default 0) - configure SMIME to use a temporary directory for its certificates that is cleaned up afterwards.
            DisableAsyncCacheCleanup    => 1,  # (default 0) - always delete cache directory immediately, rather than moving it to "trash/", to avoid data piling up.
            DisableAsyncCalls           => 1,  # (default 0) - silently discard any async calls.
            StartDaemon      => 0,       # (default 0) - 0 causes the daemon to be stopped to not interfere with tests (default behaviour).
                                         #  1 will cause the daemon to be started with an empty set of tasks.
        },
    );
    my $Helper = $Kernel::OM->Get('Kernel::System::UnitTest::Helper');

GetRandomID()

creates a random ID that can be used in tests as a unique identifier.

It is guaranteed that within a test this function will never return a duplicate.

Please note that these numbers are not really random and should only be used to create test data.

GetRandomNumber()

creates a random Number that can be used in tests as a unique identifier.

It is guaranteed that within a test this function will never return a duplicate.

Please note that these numbers are not really random and should only be used to create test data.

TestUserCreate()

creates a test user that can be used in tests. It will be set to invalid automatically during "DESTROY()". Returns the login name of the new user, the password is the same.

    my $TestUserLogin = $Helper->TestUserCreate(
        Groups               => ['admin', 'users'], # optional, list of groups to add this user to (rw rights)
        Language             => 'de'                # optional, defaults to 'en' if not set
        UserLogin            => 'UserLogin',        # optional, if not provided it will be generated
        SetUserLastLogin     => 1,                  # optional, defaults to 1 if not set
        ExceptTwoFactorSetup => 1,                  # optional, defaults to 1 if not set
        Groups        => ['admin', 'users'],           # optional, list of groups to add this user to (rw rights)
        Language      => 'de'                          # optional, defaults to 'en' if not set
    );

    or

    my ( $TestUserLogin, $TestUserID ) = $Helper->TestUserCreate(
        Groups        => ['admin', 'users'],           # optional, list of groups to add this user to (rw rights)
        Language      => 'de'                          # optional, defaults to 'en' if not set
        UserLogin     => 'UserLogin',                  # optional, if not provided it will be generated
    );

TestCustomerUserCreate()

creates a test customer user that can be used in tests. It will be set to invalid automatically during "DESTROY()". Returns the login name of the new customer user, the password is the same.

    my $TestUserLogin = $Helper->TestCustomerUserCreate(
        Language             => 'de',   # optional, defaults to 'en' if not set
        SetUserLastLogin     => 1,      # optional, defaults to 1 if not set
        ExceptTwoFactorSetup => 1,      # optional, defaults to 1 if not set
    );

BeginWork()

    $Helper->BeginWork()

Starts a database transaction (in order to isolate the test from the static database).

Rollback()

    $Helper->Rollback()

Rolls back the current database transaction.

GetTestHTTPHostname()

returns a host name for HTTP based tests, possibly including the port.

FixedTimeSet()

makes it possible to override the system time as long as this object lives. You can pass an optional time parameter that should be used, if not, the current system time will be used.

All calls to methods of Kernel::System::Time and Kernel::System::DateTime will use the given time afterwards.

    $HelperObject->FixedTimeSet(366475757);         # with Timestamp
    $HelperObject->FixedTimeSet($DateTimeObject);   # with previously created DateTime object
    $HelperObject->FixedTimeSet();                  # set to current date and time

Returns: Timestamp

FixedTimeUnset()

restores the regular system time behavior.

FixedTimeAddSeconds()

adds a number of seconds to the fixed system time which was previously set by FixedTimeSet(). You can pass a negative value to go back in time.

DESTROY()

performs various clean-ups.

ConfigSettingChange()

temporarily change a configuration setting system wide to another value, both in the current ConfigObject and also in the system configuration on disk.

This will be reset when the Helper object is destroyed.

Please note that this will not work correctly in clustered environments.

    $Helper->ConfigSettingChange(
        Valid => 1,            # (optional) enable or disable setting
        Key   => 'MySetting',  # setting name
        Value => { ... } ,     # setting value
    );

CustomCodeActivate()

Temporarily include custom code in the system. For example, you may use this to redefine a subroutine from another class. This change will persist for remainder of the test.

All code will be removed when the Helper object is destroyed.

Please note that this will not work correctly in clustered environments.

    $Helper->CustomCodeActivate(
        Identifier => 'AdminPackageManager' . $RandomID,   # (optional) Code identifier to include in file name
        Code => q^
sub Kernel::Config::Files::ZZZZUnitTestAdminPackageManager${RandomID}::Load {} # no-op, avoid warning logs

use Kernel::System::MojoUserAgent; package Kernel::System::MojoUserAgent; use Mojo::Transaction::HTTP;

use strict; use warnings; { no warnings 'redefine'; sub post { my \$Transaction = Mojo::Transaction::HTTP->new(); \$Transaction->res()->code(200)->body('{"Success":1,"Results":{"PackageManagement":[{"Operation":"PackageVerify","Data":{"Test":"not_verified","TestIncompatible":"not_verified"},"Success":"1"}]},"ErrorMessage":""}'); return \$Transaction; }; } 1; ^, );

CustomFileCleanup()

Remove all custom files from ConfigSettingChange() and CustomCodeActivate().

PushEventCleanup()

Remove all push event related database entries.

UseTmpArticleDir()

switch the article storage directory to a temporary one to prevent collisions;

DisableAsyncCalls()

Disable scheduling of asynchronous tasks using AsynchronousExecutor component of OTRS daemon.

ProvideTestDatabase()

Provide temporary database for the test. Please first define test database settings in Config.pm, i.e:

    $Self->{TestDatabase} = {
        DatabaseDSN  => 'DBI:mysql:database=otrs_test;host=127.0.0.1;',
        DatabaseUser => 'otrs_test',
        DatabasePw   => 'otrs_test',
    };

The method call will override global database configuration for duration of the test, i.e. temporary database will receive all calls sent over system DBObject.

All database contents will be automatically dropped when the Helper object is destroyed.

    $Helper->ProvideTestDatabase(
        DatabaseXMLString => $XML,      # (optional) OTRS database XML schema to execute
                                        # or
        DatabaseXMLFiles => [           # (optional) List of XML files to load and execute
            '/opt/otrs/scripts/database/otrs-schema.xml',
            '/opt/otrs/scripts/database/otrs-initial_insert.xml',
        ],
    );

This method returns 'undef' in case the test database is not configured. If it is configured, but the supplied XML cannot be read or executed, this method will die() to interrupt the test with an error.

GetDatabaseStructure()

returns a hash representation of the current database structure. This can be used if certain transformations in the database lead to identical / expected results.

Please note that the hash structure varies based on the used DB driver type.

    my $DatabaseStructureHashBefore = $Helper->GetDatabaseStructure();

    ...     # perform some changes

    my $DatabaseStructureHashAfter  = $Helper->GetDatabaseStructure();

    ...     # compare the hashes

TestDatabaseCleanup()

Clears temporary database used in the test. Always call ProvideTestDatabase() called first, in order to set it up.

Please note that all database contents will be dropped, USE WITH CARE!

    $Helper->TestDatabaseCleanup();

DatabaseXMLExecute()

Execute supplied XML against current database. Content of supplied XML or XMLFilename parameter must be valid OTRS database XML schema.

    $Helper->DatabaseXMLExecute(
        XML => $XML,     # OTRS database XML schema to execute
    );

Alternatively, it can also load an XML file to execute:

    $Helper->DatabaseXMLExecute(
        XMLFile => '/path/to/file',  # OTRS database XML file to execute
    );

IsDaemonRunning()

Checks if the OTRS daemon is currently running

    $Helper->IsDaemonRunning();

Returns 1 if the daemon is running, 0 if not.

StartDaemon()

Tries to start the OTRS daemon.

    $Helper->StartDaemon();

Returns 1, if the daemon was started successfully, 0 if not.

StopDaemon()

Tries to stop the OTRS daemon.

    $Helper->StopDaemon();

Returns 1, if the daemon was stopped successfully, 0 if not.

ProvideTestDocumentSearchIndices()

Updates the configuration with a random prefix for all elastic search indexes and creates a new set of all of them.

This is normally only executed in the constructor of the helper object by adding ProvideTestDocumentSearchIndices parameter.

    $Helper->ProvideTestDocumentSearchIndices();

RemoveTestDocumentSearchIndices()

Removes custom created indices by gathering the prefix in the configuration.

This is normally only executed in the constructor of the helper object by adding ProvideTestDocumentSearchIndices parameter.

    $Helper->RemoveTestDocumentSearchIndices();

DocumentAdd()

Add documents to their corresponding elastic search index and refresh index so the documents will be immediately available for search.

    $Helper->DocumentAdd(
        Documents => {
            Ticket => [ 1, 2, 3, ],         # each document type needs its own key and the value is an
                                            #   array reference of the IDs of the documents to be indexed.
            ArticleMime => [ 4, 5, 6,],
        },
    );

DocumentDelete()

Removes documents from corresponding elastic search index.

    $Helper->DocumentDelete(
        Documents => {
            Ticket => [ 1, 2, 3, ],         # each document type needs its own key and the value is an
                                            #   array reference of the IDs of the documents to be indexed.
            ArticleMime => [ 4, 5, 6,],
        },
    );

ProvideTestSMIMEEnvironment()

creates an empty, temporary certificate store that is cleaned up after the test and configures it to be used.

ProvideTestPGPEnvironment()

creates an empty, temporary key ring that is cleaned up after the test and configures it to be used.

BuildWebApp()

Builds web apps using the webpack toolchain.

    $SeleniumObject->BuildWebApp(
        Apps => [           # (optional) Specific web apps to build. If unspecified, builds all default apps.
            'External',
            'Chat',
            ...
        ],
    );

StartS3Service()

Tries to start https://min.io S3 service.

    $Helper->StartS3Service();

Returns 1, if the service was started successfully, 0 if not.

StopS3Service()

Tries to stop the https://min.io S3 service.

    $Helper->StopS3Service();

_UnitTestSettingsSet()

Sets needed settings for unit testing.

    $Self->_UnitTestSettingsSet();
Scroll to Top