sebastianbergmann / phpunit

The PHP Unit Testing framework.
https://phpunit.de/
BSD 3-Clause "New" or "Revised" License
19.71k stars 2.2k forks source link

DB::Rollback() does not rollback Transaction when called in tearDownAfterClass() #4880

Closed pildit closed 2 years ago

pildit commented 2 years ago
Q A
PHPUnit version 8.5.21
PHP version 7.2.34
Installation Method Composer

Summary

When using DB:rollback() in static function tearDownAfterClass nothing happens. In the DB i see the inserts which means that the transaction has been committed.

In order for it to work, i used a hack found elsewhere (else there was an error about the DB facade not being resolved)

Current behavior

The values are stored in the DB even if i intend to rollback the transaction after all tests are run.

How to reproduce

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;
    private $faker;

    protected static $db_inited = false;

    public function setUp(): void
    {
        parent::setUp();

        if (! self::$db_inited) {
            DB::connection('mysql')->beginTransaction();
            self::$db_inited = true;
        }
    }

    public static function tearDownAfterClass(): void
    {
        (new self())->setUp();
        DB::connection('mysql')->rollBack();
    }
}

Expected behavior

The results of the queries (INSERT in my case) should not be seen in the DB ( the transaction should rollback at the end of the tests).

Output of "composer info | sort"

alexpechkarev/geometry-library          1.0.1        PHP Geometry library provides utility functions for the computation of geometric data on the surface of the Earth.
alexpechkarev/google-maps               7.0.0        Collection of Google Maps API Web Services for Laravel
asm89/stack-cors                        v2.1.1       Cross-origin resource sharing library and stack middleware
aws/aws-crt-php                         v1.0.2       AWS Common Runtime for PHP
aws/aws-sdk-php                         3.208.4      AWS SDK for PHP - Use Amazon Web Services in your PHP project
barryvdh/laravel-debugbar               v3.6.6       PHP Debugbar integration for Laravel
barryvdh/laravel-dompdf                 v0.8.7       A DOMPDF Wrapper for Laravel
barryvdh/laravel-ide-helper             v2.8.2       Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.
barryvdh/reflection-docblock            v2.0.6      
brick/math                              0.9.3        Arbitrary-precision arithmetic library
composer/ca-bundle                      1.3.1        Lets you find a path to the system CA bundle, and includes a fallback to the Mozilla CA bundle.
composer/composer                       2.1.14       Composer helps you declare, manage and install dependencies of PHP projects. It ensures you have the right stack everywhere.
composer/metadata-minifier              1.0.0        Small utility library that handles metadata minification and expansion.
composer/pcre                           1.0.0        PCRE wrapping library that offers type-safe preg_* replacements.
composer/semver                         3.2.6        Semver library that offers utilities, version constraint parsing and validation.
composer/spdx-licenses                  1.5.6        SPDX licenses list and validation library.
composer/xdebug-handler                 2.0.3        Restarts a process without Xdebug.
doctrine/annotations                    1.13.2       Docblock Annotations Parser
doctrine/cache                          2.1.1        PHP Doctrine Cache library is a popular cache implementation that supports many different drivers such as redis, memcache, apc, mongodb and others.
doctrine/dbal                           2.13.6       Powerful PHP database abstraction layer (DBAL) with many features for database schema introspection and management.
doctrine/deprecations                   v0.5.3       A small layer on top of trigger_error(E_USER_DEPRECATED) or PSR-3 logging with options to disable all deprecations or selectively for packages.
doctrine/event-manager                  1.1.1        The Doctrine Event Manager is a simple PHP event system that was built to be used with the various Doctrine projects.
doctrine/inflector                      2.0.4        PHP Doctrine Inflector is a small library that can perform string manipulations with regard to upper/lowercase and singular/plural forms of words.
doctrine/instantiator                   1.4.0        A small, lightweight utility to instantiate objects in PHP without invoking their constructors
doctrine/lexer                          1.2.1        PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.
dompdf/dompdf                           v0.8.6       DOMPDF is a CSS 2.1 compliant HTML to PDF converter
dragonmantank/cron-expression           v2.3.1       CRON for PHP: Calculate the next or previous run date and determine if a CRON expression is due
egulias/email-validator                 2.1.25       A library for validating emails against several RFCs
facade/flare-client-php                 1.9.1        Send PHP errors to Flare
facade/ignition                         2.4.2        A beautiful error page for Laravel applications.
facade/ignition-contracts               1.0.1        Solution contracts for Ignition
fideloper/proxy                         4.4.1        Set trusted proxies for Laravel
filp/whoops                             2.14.4       php error handling for cool kids
friendsofphp/php-cs-fixer               v2.19.3      A tool to automatically fix PHP code style
fruitcake/laravel-cors                  v2.0.5       Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
fzaninotto/faker                        v1.9.2       Faker is a PHP library that generates fake data for you.
guzzlehttp/guzzle                       7.4.1        Guzzle is a PHP HTTP client library
guzzlehttp/promises                     1.5.1        Guzzle promises library
guzzlehttp/psr7                         1.8.3        PSR-7 message implementation that also provides common utility methods
hamcrest/hamcrest-php                   v2.0.1       This is the PHP port of Hamcrest Matchers
hubspot/api-client                      3.1.0        Hubspot API client
intervention/image                      2.7.0        Image handling and manipulation library with support for Laravel integration
jaybizzle/crawler-detect                v1.2.110     CrawlerDetect is a PHP class for detecting bots/crawlers/spiders via the user agent
jbroadway/urlify                        1.2.2-stable PHP port of URLify.js from the Django project. Transliterates non-ascii characters for use in URLs.
jenssegers/agent                        v2.6.4       Desktop/mobile user agent parser with support for Laravel, based on Mobiledetect
justinrainbow/json-schema               5.2.11       A library to validate a json schema.
laravel/framework                       v7.30.6      The Laravel Framework.
laravel/helpers                         v1.4.1       Provides backwards compatibility for helpers in the latest Laravel release.
laravel/tinker                          v2.6.3       Powerful REPL for the Laravel framework.
laravel/ui                              v2.5.0       Laravel UI utilities and presets.
laravelcollective/html                  v6.2.1       HTML and Form Builders for the Laravel Framework
lcobucci/jwt                            3.3.3        A simple library to work with JSON Web Token and JSON Web Signature
league/commonmark                       1.6.6        Highly-extensible PHP Markdown parser which fully supports the CommonMark spec and Github-Flavored Markdown (GFM)
league/flysystem                        1.1.9        Filesystem abstraction: Many filesystems, one API.
league/flysystem-aws-s3-v3              1.0.29       Flysystem adapter for the AWS S3 SDK v3.x
league/mime-type-detection              1.9.0        Mime-type detection for Flysystem
martinlindhe/laravel-vue-i18n-generator 0.1.46       Generates a vue-i18n compatible include file from your Laravel translations.
maximebf/debugbar                       v1.17.3      Debug bar in the browser for php application
mobiledetect/mobiledetectlib            2.8.37       Mobile_Detect is a lightweight PHP class for detecting mobile devices. It uses the User-Agent string combined with specific HTTP headers to detect the mobile environment.
mockery/mockery                         1.3.5        Mockery is a simple yet flexible PHP mock object framework
monolog/monolog                         2.3.5        Sends your logs to files, sockets, inboxes, databases and various web services
mtdowling/jmespath.php                  2.6.1        Declaratively specify how to extract elements from a JSON document
myclabs/deep-copy                       1.10.2       Create deep copies (clones) of your objects
namshi/jose                             7.2.3        JSON Object Signing and Encryption library for PHP.
nesbot/carbon                           2.55.2       An API extension for DateTime that supports 281 different languages.
nikic/php-parser                        v4.13.2      A PHP parser written in PHP
nunomaduro/collision                    v4.3.0       Cli error handling for console/command-line PHP applications.
opis/closure                            3.6.2        A library that can be used to serialize closures (anonymous functions) and arbitrary objects.
paragonie/random_compat                 v9.99.100    PHP 5.x polyfill for random_bytes() and random_int() from PHP 7
paragonie/sodium_compat                 v1.17.0      Pure PHP implementation of libsodium; uses the PHP extension if it exists
phar-io/manifest                        2.0.3        Component for reading phar.io manifest information from a PHP Archive (PHAR)
phar-io/version                         3.1.0        Library for handling version information and constraints
phenx/php-font-lib                      0.5.2        A library to read, parse, export and make subsets of different types of font files.
phenx/php-svg-lib                       v0.3.3       A library to read, parse and export to PDF SVG files.
php-cs-fixer/diff                       v1.3.1       sebastian/diff v2 backport support for PHP5.6
phpdocumentor/reflection-common         2.2.0        Common reflection classes used by phpdocumentor to reflect the code structure
phpdocumentor/reflection-docblock       5.3.0        With this component, a library can provide support for annotations via DocBlocks or otherwise retrieve information that is embedded in a DocBlock.
phpdocumentor/type-resolver             1.5.1        A PSR-5 based resolver of Class names, Types and Structural Element Names
phpoption/phpoption                     1.8.1        Option Type for PHP
phpspec/prophecy                        v1.15.0      Highly opinionated mocking framework for PHP 5.3+
phpunit/php-code-coverage               7.0.15       Library that provides collection, processing, and rendering functionality for PHP code coverage information.
phpunit/php-file-iterator               2.0.5        FilterIterator implementation that filters files based on a list of suffixes.
phpunit/php-text-template               1.2.1        Simple template engine.
phpunit/php-timer                       2.1.3        Utility class for timing
phpunit/php-token-stream                3.1.3        Wrapper around PHP's tokenizer extension.
phpunit/phpunit                         8.5.21       The PHP Unit Testing framework.
psr/cache                               1.0.1        Common interface for caching libraries
psr/container                           1.1.1        Common Container Interface (PHP FIG PSR-11)
psr/event-dispatcher                    1.0.0        Standard interfaces for event handling.
psr/http-client                         1.0.1        Common interface for HTTP clients
psr/http-message                        1.0.1        Common interface for HTTP messages
psr/log                                 1.1.4        Common interface for logging libraries
psr/simple-cache                        1.0.1        Common interfaces for simple caching
psy/psysh                               v0.10.12     An interactive shell for modern PHP.
pusher/pusher-php-server                v3.4.1       Library for interacting with the Pusher REST API
ralouphie/getallheaders                 3.0.3        A polyfill for getallheaders.
ramsey/collection                       1.1.4        A PHP 7.2+ library for representing and manipulating collections.
ramsey/uuid                             4.2.3        A PHP library for generating and working with universally unique identifiers (UUIDs).
react/promise                           v2.8.0       A lightweight implementation of CommonJS Promises/A for PHP
sabberworm/php-css-parser               8.4.0        Parser for CSS Files written in PHP
scrivo/highlight.php                    v9.18.1.8    Server side syntax highlighter that supports 185 languages. It's a PHP port of highlight.js
sebastian/code-unit-reverse-lookup      1.0.2        Looks up which function or method a line of code belongs to
sebastian/comparator                    3.0.3        Provides the functionality to compare PHP values for equality
sebastian/diff                          3.0.3        Diff implementation
sebastian/environment                   4.2.4        Provides functionality to handle HHVM/PHP environments
sebastian/exporter                      3.1.4        Provides the functionality to export PHP variables for visualization
sebastian/global-state                  3.0.1        Snapshotting of global state
sebastian/object-enumerator             3.0.4        Traverses array structures and object graphs to enumerate all referenced objects
sebastian/object-reflector              1.1.2        Allows reflection of object attributes, including inherited and non-public ones
sebastian/recursion-context             3.0.1        Provides functionality to recursively process PHP variables
sebastian/resource-operations           2.0.2        Provides a list of PHP built-in functions that operate on resources
sebastian/type                          1.1.4        Collection of value objects that represent the types of the PHP type system
sebastian/version                       2.0.1        Library that helps with managing the version number of Git-hosted PHP projects
seld/jsonlint                           1.8.3        JSON Linter
seld/phar-utils                         1.2.0        PHAR file format utilities, for when PHP phars you up
swiftmailer/swiftmailer                 v6.3.0       Swiftmailer, free feature-rich PHP mailer
symfony/console                         v5.4.1       Eases the creation of beautiful and testable command line interfaces
symfony/css-selector                    v3.1.10      Symfony CssSelector Component
symfony/debug                           v4.4.37      Provides tools to ease debugging PHP code
symfony/deprecation-contracts           v2.5.0       A generic function and convention to trigger deprecation notices
symfony/dom-crawler                     v3.1.10      Symfony DomCrawler Component
symfony/error-handler                   v5.4.1       Provides tools to manage errors and ease debugging PHP code
symfony/event-dispatcher                v5.4.0       Provides tools that allow your application components to communicate with each other by dispatching events and listening to them
symfony/event-dispatcher-contracts      v2.5.0       Generic abstractions related to dispatching event
symfony/filesystem                      v5.4.0       Provides basic utilities for the filesystem
symfony/finder                          v5.4.0       Finds files and directories via an intuitive fluent interface
symfony/http-foundation                 v5.4.1       Defines an object-oriented layer for the HTTP specification
symfony/http-kernel                     v5.4.1       Provides a structured process for converting a Request into a Response
symfony/mime                            v5.4.0       Allows manipulating MIME messages
symfony/options-resolver                v5.4.0       Provides an improved replacement for the array_replace PHP function
symfony/polyfill-ctype                  v1.23.0      Symfony polyfill for ctype functions
symfony/polyfill-iconv                  v1.23.0      Symfony polyfill for the Iconv extension
symfony/polyfill-intl-grapheme          v1.23.1      Symfony polyfill for intl's grapheme_* functions
symfony/polyfill-intl-idn               v1.23.0      Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions
symfony/polyfill-intl-normalizer        v1.23.0      Symfony polyfill for intl's Normalizer class and related functions
symfony/polyfill-mbstring               v1.23.1      Symfony polyfill for the Mbstring extension
symfony/polyfill-php56                  v1.20.0      Symfony polyfill backporting some PHP 5.6+ features to lower PHP versions
symfony/polyfill-php70                  v1.20.0      Symfony polyfill backporting some PHP 7.0+ features to lower PHP versions
symfony/polyfill-php72                  v1.23.0      Symfony polyfill backporting some PHP 7.2+ features to lower PHP versions
symfony/polyfill-php73                  v1.23.0      Symfony polyfill backporting some PHP 7.3+ features to lower PHP versions
symfony/polyfill-php80                  v1.23.1      Symfony polyfill backporting some PHP 8.0+ features to lower PHP versions
symfony/process                         v5.4.0       Executes commands in sub-processes
symfony/routing                         v5.4.0       Maps an HTTP request to a set of configuration variables
symfony/service-contracts               v2.5.0       Generic abstractions related to writing services
symfony/stopwatch                       v5.4.0       Provides a way to profile code
symfony/string                          v5.4.0       Provides an object-oriented API to strings and deals with bytes, UTF-8 code points and grapheme clusters in a unified way
symfony/translation                     v5.4.1       Provides tools to internationalize your application
symfony/translation-contracts           v2.5.0       Generic abstractions related to translation
symfony/var-dumper                      v5.4.1       Provides mechanisms for walking through any arbitrary PHP variable
theseer/tokenizer                       1.2.1        A small library for converting tokenized PHP source code into XML and potentially other formats
tijsverkoyen/css-to-inline-styles       2.2.4        CssToInlineStyles is a class that enables you to convert HTML-pages/files into HTML-pages/files with inline styles. This is very useful when you're sending emails.
torann/geoip                            1.2.1        Support for multiple GeoIP services.
tymon/jwt-auth                          1.0.2        JSON Web Token Authentication for Laravel and Lumen
vlucas/phpdotenv                        v4.2.2       Loads environment variables from `.env` to `getenv()`, `$_ENV` and `$_SERVER` automagically.
voku/portable-ascii                     1.5.6        Portable ASCII library - performance optimized (ascii) string functions for php.
voku/stop-words                         2.0.1        Stop-Words via PHP
webmozart/assert                        1.10.0       Assertions to validate method input/output with nice error messages.
sebastianbergmann commented 2 years ago

Please report this issue to the vendor of DB:rollback().