Codeception icon indicating copy to clipboard operation
Codeception copied to clipboard

Injecting a symfony class into functional test fails to resolve dependency

Open geoff-maddock opened this issue 4 years ago • 3 comments

What are you trying to achieve?

Inject a symfony class into a functional test

What do you get instead?

Codeception fails to inject the class - fails to resolve the dependency

Provide console output if related. Use -vvv mode for more details.

cutups@EXP11280:~/PhpstormProjects/cadence$ ./local-test.sh functional Controller/NetworkJobControllerCest -vvv
geoff-smc-app-nginx-5b5fcc7457-x2xxk
Codeception PHP Testing Framework v4.1.4
Powered by PHPUnit 9.1.4 by Sebastian Bergmann and contributors.
Running with seed:


In Di.php line 119:

  [Codeception\Exception\InjectionException]
  Failed to inject dependencies in instance of 'App\Tests\functional\Controll
  er\NetworkJobControllerCest'. Failed to resolve dependency 'Symfony\Compone
  nt\Security\Core\Authentication\Token\Storage\TokenStorageInterface'.


Exception trace:
  at /srv/cadence/vendor/codeception/codeception/src/Codeception/Lib/Di.php:119
 Codeception\Lib\Di->injectDependencies() at /srv/cadence/vendor/codeception/codeception/src/Codeception/Test/Cest.php:48
 Codeception\Test\Cest->preload() at /srv/cadence/vendor/codeception/codeception/src/Codeception/SuiteManager.php:248
 Codeception\SuiteManager->configureTest() at /srv/cadence/vendor/codeception/codeception/src/Codeception/SuiteManager.php:112
 Codeception\SuiteManager->addToSuite() at /srv/cadence/vendor/codeception/codeception/src/Codeception/SuiteManager.php:105
 Codeception\SuiteManager->loadTests() at /srv/cadence/vendor/codeception/codeception/src/Codeception/Codecept.php:194
 Codeception\Codecept->runSuite() at /srv/cadence/vendor/codeception/codeception/src/Codeception/Codecept.php:163
 Codeception\Codecept->run() at /srv/cadence/vendor/codeception/codeception/src/Codeception/Command/Run.php:391
 Codeception\Command\Run->execute() at /srv/cadence/vendor/symfony/console/Command/Command.php:255
 Symfony\Component\Console\Command\Command->run() at /srv/cadence/vendor/symfony/console/Application.php:1001
 Symfony\Component\Console\Application->doRunCommand() at /srv/cadence/vendor/symfony/console/Application.php:271
 Symfony\Component\Console\Application->doRun() at /srv/cadence/vendor/symfony/console/Application.php:147
 Symfony\Component\Console\Application->run() at /srv/cadence/vendor/codeception/codeception/src/Codeception/Application.php:117
 Codeception\Application->run() at /srv/cadence/vendor/codeception/codeception/app.php:46
 {closure}() at /srv/cadence/vendor/codeception/codeception/app.php:47
 require() at /srv/cadence/vendor/codeception/codeception/codecept:7

run [-o|--override OVERRIDE] [-e|--ext EXT] [--report] [--html [HTML]] [--xml [XML]] [--phpunit-xml [PHPUNIT-XML]] [--tap [TAP]] [--json [JSON]] [--colors] [--no-colors] [--silent] [--steps] [-d|--debug] [--bootstrap [BOOTSTRAP]] [--no-redirect] [--coverage [COVERAGE]] [--coverage-html [COVERAGE-HTML]] [--coverage-xml [COVERAGE-XML]] [--coverage-text [COVERAGE-TEXT]] [--coverage-crap4j [COVERAGE-CRAP4J]] [--coverage-phpunit [COVERAGE-PHPUNIT]] [--no-exit] [-g|--group GROUP] [-s|--skip SKIP] [-x|--skip-group SKIP-GROUP] [--env ENV] [-f|--fail-fast] [--no-rebuild] [--seed SEED] [--no-artifacts] [--] [<suite> [<test>]]

command terminated with exit code 1

Provide test source code if related

class NetworkJobControllerCest
{

    protected TokenStorageInterface $token;

    protected function _inject(TokenStorageInterface $token)
    {
        $this->token = $token;
    }
...

Details

  • Codeception version: v4.1.4

  • PHP Version: PHP 7.4.6 (cli) (built: May 15 2020 01:43:37) ( NTS )

  • Operating System: linux

  • Installation type: Composer

  • List of installed packages (composer show) /srv/cadence # composer show beberlei/doctrineextensions v1.2.6 A set of extensions to Doctrine 2 that add support for additional que... behat/gherkin v4.6.2 Gherkin DSL parser for PHP 5.3 behat/transliterator v1.3.0 String transliterator codeception/c3 2.4.1 CodeCoverage collector for Codeception codeception/codeception 4.1.4 BDD-style testing framework codeception/lib-asserts 1.12.0 Assertion methods used by Codeception core and Asserts module codeception/lib-innerbrowser 1.3.1 Parent library for all Codeception framework modules and PhpBrowser codeception/module-asserts 1.2.1 Codeception module containing various assertions codeception/module-doctrine2 1.0.1 Doctrine2 module for Codeception codeception/module-phpbrowser 1.0.0 Codeception module for testing web application over HTTP codeception/module-symfony 1.1.0 Codeception module for Symfony framework codeception/phpunit-wrapper 9.0.2 PHPUnit classes used by Codeception codeception/stub 3.6.1 Flexible Stub wrapper for PHPUnit's Mock Builder composer/ca-bundle 1.2.7 Lets you find a path to the system CA bundle, and includes a fallback... composer/semver 1.5.1 Semver library that offers utilities, version constraint parsing and ... composer/xdebug-handler 1.4.1 Restarts a process without Xdebug. doctrine/annotations 1.10.2 Docblock Annotations Parser doctrine/cache 1.10.0 PHP Doctrine Cache library is a popular cache implementation that sup... doctrine/collections 1.6.4 PHP Doctrine Collections library that adds additional functionality o... doctrine/common 2.12.0 PHP Doctrine Common project is a library that provides additional fun... doctrine/dbal 2.10.2 Powerful PHP database abstraction layer (DBAL) with many features for... doctrine/doctrine-bundle 2.0.8 Symfony DoctrineBundle doctrine/doctrine-migrations-bundle 2.1.2 Symfony DoctrineMigrationsBundle doctrine/event-manager 1.1.0 The Doctrine Event Manager is a simple PHP event system that was buil... doctrine/inflector 1.3.1 Common String Manipulations with regard to casing and singular/plural... doctrine/instantiator 1.3.0 A small, lightweight utility to instantiate objects in PHP without in... doctrine/lexer 1.2.0 PHP Doctrine Lexer parser library that can be used in Top-Down, Recur... doctrine/migrations 2.2.1 PHP Doctrine Migrations project offer additional functionality on top... doctrine/orm v2.7.2 Object-Relational-Mapper for PHP doctrine/persistence 1.3.7 The Doctrine Persistence project is a set of shared interfaces and fu... doctrine/reflection 1.2.1 The Doctrine Reflection project is a simple library used by the vario... egulias/email-validator 2.1.17 A library for validating emails against several RFCs expedient/ansible-tower-client 1.0.5 No description provided (generated by Openapi Generator https://githu... friendsofphp/php-cs-fixer v2.16.3 A tool to automatically fix PHP code style friendsofsymfony/jsrouting-bundle 2.5.4 A pretty nice way to expose your Symfony2 routing to client applicati... gedmo/doctrine-extensions v2.4.39 Doctrine2 behavioral extensions guzzlehttp/guzzle 6.5.3 Guzzle is a PHP HTTP client library guzzlehttp/promises v1.3.1 Guzzle promises library guzzlehttp/psr7 1.6.1 PSR-7 message implementation that also provides common utility methods jdorn/sql-formatter v1.2.17 a PHP SQL highlighting library jms/metadata 2.1.0 Class/method/property metadata management in PHP knplabs/knp-components v1.3.10 Knplabs component library knplabs/knp-paginator-bundle v3.0.0 Paginator bundle for Symfony to automate pagination and simplify sort... laminas/laminas-code 3.4.1 Extensions to the PHP Reflection API, static code scanning, and code ... laminas/laminas-eventmanager 3.2.1 Trigger and listen to events within a PHP application laminas/laminas-zendframework-bridge 1.0.3 Alias legacy ZF class names to Laminas Project equivalents. markbaker/complex 1.4.8 PHP Class for working with complex numbers markbaker/matrix 1.2.0 PHP Class for working with matrices mcorrigan/salesforce-rest-api-php-wrapper 1.0.3 SalesForce REST API PHP Wrapper monolog/monolog 2.0.2 Sends your logs to files, sockets, inboxes, databases and various web... myclabs/deep-copy 1.9.5 Create deep copies (clones) of your objects nesbot/carbon 2.33.0 An API extension for DateTime that supports 281 different languages. nikic/php-parser v4.4.0 A PHP parser written in PHP ocramius/package-versions 1.8.0 Composer plugin that provides efficient querying for installed packag... ocramius/proxy-manager 2.8.0 A library providing utilities to generate, instantiate and generally ... pdepend/pdepend 2.7.1 Official version of pdepend to be handled with Composer phar-io/manifest 1.0.3 Component for reading phar.io manifest information from a PHP Archive... phar-io/version 2.0.1 Library for handling version information and constraints php-cs-fixer/diff v1.3.0 sebastian/diff v2 backport support for PHP5.6 phpdocumentor/reflection-common 2.1.0 Common reflection classes used by phpdocumentor to reflect the code s... phpdocumentor/reflection-docblock 5.1.0 With this component, a library can provide support for annotations vi... phpdocumentor/type-resolver 1.1.0 A PSR-5 based resolver of Class names, Types and Structural Element N... phpmd/phpmd 2.8.2 PHPMD is a spin-off project of PHP Depend and aims to be a PHP equiva... phpoffice/phpspreadsheet 1.12.0 PHPSpreadsheet - Read, Create and Write Spreadsheet documents in PHP ... phpspec/prophecy v1.10.3 Highly opinionated mocking framework for PHP 5.3+ phpstan/phpstan 0.12.23 PHPStan - PHP Static Analysis Tool phpunit/php-code-coverage 8.0.1 Library that provides collection, processing, and rendering functiona... phpunit/php-file-iterator 3.0.1 FilterIterator implementation that filters files based on a list of s... phpunit/php-invoker 3.0.0 Invoke callables with a timeout phpunit/php-text-template 2.0.0 Simple template engine. phpunit/php-timer 3.1.4 Utility class for timing phpunit/php-token-stream 4.0.1 Wrapper around PHP's tokenizer extension. phpunit/phpunit 9.1.4 The PHP Unit Testing framework. predis/predis v1.1.1 Flexible and feature-complete Redis client for PHP and HHVM psr/cache 1.0.1 Common interface for caching libraries psr/container 1.0.0 Common Container Interface (PHP FIG PSR-11) psr/http-message 1.0.1 Common interface for HTTP messages psr/log 1.1.3 Common interface for logging libraries psr/simple-cache 1.0.1 Common interfaces for simple caching ralouphie/getallheaders 3.0.3 A polyfill for getallheaders. sebastian/code-unit 1.0.2 Collection of value objects that represent the PHP code units sebastian/code-unit-reverse-lookup 2.0.0 Looks up which function or method a line of code belongs to sebastian/comparator 4.0.0 Provides the functionality to compare PHP values for equality sebastian/diff 4.0.0 Diff implementation sebastian/environment 5.1.0 Provides functionality to handle HHVM/PHP environments sebastian/exporter 4.0.0 Provides the functionality to export PHP variables for visualization sebastian/global-state 4.0.0 Snapshotting of global state sebastian/object-enumerator 4.0.0 Traverses array structures and object graphs to enumerate all referen... sebastian/object-reflector 2.0.0 Allows reflection of object attributes, including inherited and non-p... sebastian/recursion-context 4.0.0 Provides functionality to recursively process PHP variables sebastian/resource-operations 3.0.0 Provides a list of PHP built-in functions that operate on resources sebastian/type 2.0.0 Collection of value objects that represent the types of the PHP type ... sebastian/version 3.0.0 Library that helps with managing the version number of Git-hosted PHP... sensio/framework-extra-bundle v5.5.5 This bundle provides a way to configure your controllers with annotat... sensiolabs/ansi-to-html v1.1.3 A library to convert a text with ANSI codes to HTML sensiolabs/security-checker v5.0.3 A security checker for your composer.lock snc/redis-bundle 3.2.2 A Redis bundle for Symfony solarium/solarium 4.2.0 PHP Solr client stof/doctrine-extensions-bundle dev-master 578ae5d Integration of the gedmo/doctrine-extensions with Symfony2 swiftmailer/swiftmailer v6.2.3 Swiftmailer, free feature-rich PHP mailer symfony/asset v4.4.8 Symfony Asset Component symfony/browser-kit v4.4.8 Symfony BrowserKit Component symfony/cache v5.0.8 Symfony Cache component with PSR-6, PSR-16, and tags symfony/cache-contracts v2.0.1 Generic abstractions related to caching symfony/config v5.0.8 Symfony Config Component symfony/console v4.4.8 Symfony Console Component symfony/css-selector v5.0.8 Symfony CssSelector Component symfony/debug v4.4.13 Symfony Debug Component symfony/debug-bundle v4.4.8 Symfony DebugBundle symfony/debug-pack v1.0.8 A debug pack for Symfony projects symfony/dependency-injection v5.0.8 Symfony DependencyInjection Component symfony/deprecation-contracts v2.1.3 A generic function and convention to trigger deprecation notices symfony/doctrine-bridge v4.4.8 Symfony Doctrine Bridge symfony/dom-crawler v5.0.8 Symfony DomCrawler Component symfony/dotenv v4.4.8 Registers environment variables from a .env file symfony/error-handler v4.4.13 Symfony ErrorHandler Component symfony/event-dispatcher v4.4.13 Symfony EventDispatcher Component symfony/event-dispatcher-contracts v1.1.9 Generic abstractions related to dispatching event symfony/expression-language v4.4.8 Symfony ExpressionLanguage Component symfony/filesystem v5.0.8 Symfony Filesystem Component symfony/finder v5.0.8 Symfony Finder Component symfony/flex v1.6.2 Composer plugin for Symfony symfony/form v4.4.8 Symfony Form Component symfony/framework-bundle v4.4.8 Symfony FrameworkBundle symfony/http-foundation v5.1.5 Symfony HttpFoundation Component symfony/http-kernel v4.4.13 Symfony HttpKernel Component symfony/inflector v5.0.8 Symfony Inflector Component symfony/intl v5.0.8 A PHP replacement layer for the C intl extension that includes additi... symfony/ldap v4.4.8 An abstraction in front of PHP's LDAP functions, compatible with PHP ... symfony/maker-bundle v1.16.0 Symfony Maker helps you create empty commands, controllers, form clas... symfony/mime v4.4.13 A library to manipulate MIME messages symfony/monolog-bridge v5.0.8 Symfony Monolog Bridge symfony/monolog-bundle v3.5.0 Symfony MonologBundle symfony/options-resolver v5.0.8 Symfony OptionsResolver Component symfony/orm-pack v1.0.8 A pack for the Doctrine ORM symfony/phpunit-bridge v4.4.8 Symfony PHPUnit Bridge symfony/polyfill-ctype v1.18.1 Symfony polyfill for ctype functions symfony/polyfill-intl-grapheme v1.15.0 Symfony polyfill for intl's grapheme_* functions symfony/polyfill-intl-icu v1.15.0 Symfony polyfill for intl's ICU-related data and classes symfony/polyfill-intl-idn v1.18.1 Symfony polyfill for intl's idn_to_ascii and idn_to_utf8 functions symfony/polyfill-intl-normalizer v1.15.0 Symfony polyfill for intl's Normalizer class and related functions symfony/polyfill-mbstring v1.18.1 Symfony polyfill for the Mbstring extension symfony/polyfill-php72 v1.18.1 Symfony polyfill backporting some PHP 7.2+ features to lower PHP vers... symfony/polyfill-php73 v1.18.1 Symfony polyfill backporting some PHP 7.3+ features to lower PHP vers... symfony/polyfill-php80 v1.18.1 Symfony polyfill backporting some PHP 8.0+ features to lower PHP vers... symfony/process v5.0.8 Symfony Process Component symfony/profiler-pack v1.0.4 A pack for the Symfony web profiler symfony/property-access v5.0.8 Symfony PropertyAccess Component symfony/property-info v5.0.8 Symfony Property Info Component symfony/proxy-manager-bridge v4.4.8 Symfony ProxyManager Bridge symfony/routing v5.0.8 Symfony Routing Component symfony/security-bundle v4.4.8 Symfony SecurityBundle symfony/security-core v4.4.8 Symfony Security Component - Core Library symfony/security-csrf v5.0.8 Symfony Security Component - CSRF Library symfony/security-guard v4.4.8 Symfony Security Component - Guard symfony/security-http v4.4.8 Symfony Security Component - HTTP Integration symfony/serializer v5.0.8 Symfony Serializer Component symfony/serializer-pack v1.0.3 A pack for the Symfony serializer symfony/service-contracts v2.0.1 Generic abstractions related to writing services symfony/stopwatch v5.0.8 Symfony Stopwatch Component symfony/string v5.0.8 Symfony String component symfony/swiftmailer-bundle v3.4.0 Symfony SwiftmailerBundle symfony/translation v4.4.8 Symfony Translation Component symfony/translation-contracts v2.0.1 Generic abstractions related to translation symfony/twig-bridge v4.4.8 Symfony Twig Bridge symfony/twig-bundle v4.4.8 Symfony TwigBundle symfony/validator v4.4.8 Symfony Validator Component symfony/var-dumper v4.4.8 Symfony mechanism for exploring and dumping PHP variables symfony/var-exporter v5.0.8 A blend of var_export() + serialize() to turn any serializable data s... symfony/web-profiler-bundle v5.0.8 Symfony WebProfilerBundle symfony/web-server-bundle v4.4.8 Symfony WebServerBundle symfony/webpack-encore-bundle v1.7.3 Integration with your Symfony app & Webpack Encore! symfony/workflow v4.4.8 Symfony Workflow Component symfony/yaml v4.4.8 Symfony Yaml Component theseer/tokenizer 1.1.3 A small library for converting tokenized PHP source code into XML and... twig/twig v2.12.5 Twig, the flexible, fast, and secure template language for PHP twilio/sdk 5.42.2 A PHP wrapper for Twilio's API vanilla/htmlawed v2.2.5 A composer wrapper for the htmLawed library to purify & filter HTML. ... vich/uploader-bundle 1.13.2 Ease file uploads attached to entities webimpress/safe-writer 2.0.1 Tool to write files safely, to avoid race conditions webmozart/assert 1.8.0 Assertions to validate method input/output with nice error messages. willdurand/jsonp-callback-validator v1.1.0 JSONP callback validator.

  • Suite configuration:

# Codeception Test Suite Configuration
#
# Suite for functional tests
# Emulate web requests and make application process them
# Include one of framework modules (Symfony2, Yii2, Laravel5) to use it
# Remove this suite if you don't use frameworks

actor: FunctionalTester
modules:
    enabled:
        - Asserts
        - PhpBrowser:
            # module configuration
            url: '%INTERNAL_URL%'
        - Symfony:
            app_path: 'src'
            environment: 'test'
            em_service: 'doctrine.orm.entity_manager'
            rebootable_client: true
        - Doctrine2:
            depends: Symfony
            cleanup: false
        # add a framework module here
        - \Helper\Functional
    config:
        WebDriver:
            url: '%INTERNAL_URL%'
            browser: 'firefox'

geoff-maddock avatar Sep 23 '20 17:09 geoff-maddock

Your expectation was that Symfony autowiring will work for Codeception tests, but Codeception DI class does not collaborate with Symfony Service Container, the most it can do is to call new $className with default parameters and its typehinted dependencies instantiated recursively in the same way.

In theory, DI class can use fallback container if it is passed to constructor, but this functionality is not used anywhere.

The instantiation of DI which is used for running tests happens in SuiteManager.

@TavoNiievez Have you got any ideas how to integration Codeception DI to Symfony Service Container?

Naktibalda avatar Jan 02 '21 11:01 Naktibalda

@Naktibalda It seems that you already have the solution.

Adding:

    if ($this->moduleContainer->hasModule('Symfony')) {
        /** @var Symfony $symfonyModule */
        $symfonyModule = $this->moduleContainer->getModule('Symfony');
        $symfonyModule->_initialize();
        $symfonyContainer = $symfonyModule->_getContainer();
        $this->di = new Di($symfonyContainer);
    }

after this line (SuiteManager.php L72):

    $this->moduleContainer->validateConflicts();

makes autowiring work fine with _inject.

TavoNiievez avatar Jan 02 '21 19:01 TavoNiievez

I think that it would be nicer to declare interface for that:

foreach ($modules as $moduleName) {
    $module = $this->moduleContainer->create($moduleName);

    if ($module instanceof DependencyInjectionContainerProvider) {
      $this->di->addFallbackContainer($module->getDependencyInjectionContainer());
    }
}

Naktibalda avatar Jul 31 '22 09:07 Naktibalda