This error is likely be repro'd out of tests only, but reporting as I see it.

Using toUrl within a Kernel test results in the following uncaught exception.

Drupal\Component\Plugin\Exception\ContextException: The 'entity:user' context is required and not present.

This is causing the tests for Linky project to fail. This may be caused by new code introduced this year in #2942907: Entity system does not provide an API for retrieving an entity variant that is safe for editing, specifically the changes introduced to \Drupal\Core\ParamConverter\EntityConverter::convert

Comments

dpi created an issue. See original summary.

dpi’s picture

StatusFileSize
new999 bytes

Tests for fail

dpi’s picture

StatusFileSize
new1.96 KB
dpi’s picture

Issue summary: View changes
dpi’s picture

StatusFileSize
new1021 bytes
new1.99 KB
m4olivei’s picture

Ran into this in our test suite today upgrading to 8.7.7 from 8.6. I found this was a suitable workaround, simply defining the anonymous user in the setUp method:

// Setup an anonymous user for our tests.
User::create([
  'name' => '',
  'uid' => 0,
])->save();</pre>
hchonov’s picture

Status: Active » Needs work
  1. +++ b/core/lib/Drupal/Core/ParamConverter/EntityConverter.php
    --- /dev/null
    +++ b/core/tests/Drupal/KernelTests/Core/Entity/BlahUrlKernelTest.php
    

    Let's rename it to something meaningful. EntityUrlTest maybe?

  2. +++ b/core/tests/Drupal/KernelTests/Core/Entity/BlahUrlKernelTest.php
    @@ -0,0 +1,36 @@
    +class BlahUrlKernelTest extends KernelTestBase {
    

    Let's make this an EntityKernelTest.

  3. +++ b/core/tests/Drupal/KernelTests/Core/Entity/BlahUrlKernelTest.php
    @@ -0,0 +1,36 @@
    +  use UserCreationTrait;
    ...
    +  public static $modules = [
    +    'entity_test',
    +    'user',
    +  ];
    

    The trait and the modules are included in EntityKernelTestBase.

  4. +++ b/core/tests/Drupal/KernelTests/Core/Entity/BlahUrlKernelTest.php
    @@ -0,0 +1,36 @@
    +    $url = \Drupal\Core\Url::fromUri('internal:/entity_test/' . $entityId);
    

    Let's assert something :)

berdir’s picture

+++ b/core/lib/Drupal/Core/ParamConverter/EntityConverter.php
@@ -142,9 +142,11 @@ class EntityConverter implements ParamConverterInterface {
     $context_id = '@user.current_user_context:current_user';
     if (isset($contexts[$context_id])) {
-      $account = $contexts[$context_id]->getContextValue();
-      unset($account->_skipProtectedUserFieldConstraint);
-      unset($contexts[$context_id]);
+      if ($contexts[$context_id]->hasContextValue()) {

we can combine the two if conditions into if (isset() && .. hasContextValue() IMHO, then it's a single-line change.

Version: 8.8.x-dev » 8.9.x-dev

Drupal 8.8.0-alpha1 will be released the week of October 14th, 2019, which means new developments and disruptive changes should now be targeted against the 8.9.x-dev branch. (Any changes to 8.9.x will also be committed to 9.0.x in preparation for Drupal 9’s release, but some changes like significant feature additions will be deferred to 9.1.x.). For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

subhojit777’s picture

Status: Needs work » Needs review
StatusFileSize
new1.85 KB
new2.52 KB

It was also failing for me in tests after 8.6 -> 8.7.8 upgrade and the patch in #5 fixed it. Here is another patch containing the changes suggested in #7 and #8

Status: Needs review » Needs work

The last submitted patch, 10: 3056234-10.patch, failed testing. View results

berdir’s picture

We're seeing this in our D9 tests, 300 or so behat tests in, this exceptions happens in a long backtrace as part of installing a module and after that, behat is completely messed up and the remaining 60 scenarios fail with an exception. I can't reproduce when just running that test.

Will see if this helps, but I kind of suspect that this indicates a problem elsewhere. My guess is that in my case, there is still a current user ID set, but the user was already deleted. In other cases, it could be that the entity for user 0 was deleted from the database.

No idea what D8/D9 change could cause this.

Version: 8.9.x-dev » 9.1.x-dev

Drupal 8.9.0-beta1 was released on March 20, 2020. 8.9.x is the final, long-term support (LTS) minor release of Drupal 8, which means new developments and disruptive changes should now be targeted against the 9.1.x-dev branch. For more information see the Drupal 8 and 9 minor version schedule and the Allowed changes during the Drupal 8 and 9 release cycles.

Version: 9.1.x-dev » 9.2.x-dev

Drupal 9.1.0-alpha1 will be released the week of October 19, 2020, which means new developments and disruptive changes should now be targeted for the 9.2.x-dev branch. For more information see the Drupal 9 minor version schedule and the Allowed changes during the Drupal 9 release cycle.

acbramley’s picture

Just hit this in a test that created (and subsequently deleted) an entity type that admin_toolbar_tools triggered a menu rebuild from. Here's the trace:

/code/web/core/lib/Drupal/Core/Plugin/Context/Context.php:73
/code/web/core/lib/Drupal/Core/ParamConverter/EntityConverter.php:145
/code/web/core/lib/Drupal/Core/ParamConverter/ParamConverterManager.php:100
/code/web/core/lib/Drupal/Core/Routing/Enhancer/ParamConversionEnhancer.php:45
/code/web/core/lib/Drupal/Core/Routing/Router.php:260
/code/web/core/lib/Drupal/Core/Routing/Router.php:131
/code/web/core/lib/Drupal/Core/Routing/Router.php:116
/code/web/core/lib/Drupal/Core/Path/PathValidator.php:163
/code/web/core/lib/Drupal/Core/Path/PathValidator.php:122
/code/web/core/lib/Drupal/Core/Path/PathValidator.php:89
/code/web/core/lib/Drupal/Core/Url.php:424
/code/web/core/lib/Drupal/Core/Url.php:316
/code/web/core/modules/link/src/Plugin/Field/FieldType/LinkItem.php:174
/code/web/core/modules/menu_link_content/src/Entity/MenuLinkContent.php:94
/code/web/core/modules/menu_link_content/src/Entity/MenuLinkContent.php:156
/code/web/core/modules/menu_link_content/src/Plugin/Deriver/MenuLinkContentDeriver.php:75
/code/web/core/lib/Drupal/Component/Plugin/Discovery/DerivativeDiscoveryDecorator.php:101
/code/web/core/lib/Drupal/Component/Plugin/Discovery/DerivativeDiscoveryDecorator.php:87
/code/web/core/lib/Drupal/Core/Menu/MenuLinkManager.php:164
/code/web/core/lib/Drupal/Core/Menu/MenuLinkManager.php:189
/code/web/modules/contrib/admin_toolbar/admin_toolbar_tools/admin_toolbar_tools.module:81
/code/web/core/lib/Drupal/Core/Extension/ModuleHandler.php:403
/code/web/core/lib/Drupal/Core/Config/Entity/ConfigEntityStorage.php:349
/code/web/core/lib/Drupal/Core/Entity/EntityStorageBase.php:434
/code/web/core/lib/Drupal/Core/Entity/EntityBase.php:403
/code/vendor/weitzman/drupal-test-traits/src/DrupalTrait.php:107

The patch fixed it, cheers!

Version: 9.2.x-dev » 9.3.x-dev

Drupal 9.2.0-alpha1 will be released the week of May 3, 2021, which means new developments and disruptive changes should now be targeted for the 9.3.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

rgpublic’s picture

Our whole log is inundated with this error happening every 15 seconds. Applying the patch (which perfectly works on Drupal 9.2.2) stops it. Still wonder why it happens. The website makes heavy use of Drupal's/Symfony's Session capabilities (Session-Manager service, currentUser()->setAccount). Still I have a hard time understanding what the origin of all this is.

codersrini’s picture

The patch given on #5 fixed the issue for me in Drupal 9.2.6. Thanks

Version: 9.3.x-dev » 9.4.x-dev

Drupal 9.3.0-rc1 was released on November 26, 2021, which means new developments and disruptive changes should now be targeted for the 9.4.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

arnaud-brugnon’s picture

Patch #10 works for me

dpi’s picture

Issue summary: View changes
acbramley’s picture

Started getting this post 9.3 upgrade. Creating the anonymous user didn't fix it, but the patch did :)

renguer0’s picture

Patch #10 works but we lost 'Anonymous user' group.

It just has no effect when selecting it on page view conditionals on content. There is a workaround for that? Cleaned all caches.

frank.dev’s picture

For me the patch only solves part of the problem.
The website is accessible again for anonymous visitors. But when calling the DB log, the error message remains with a white screen.

troybthompson’s picture

I'm running 9.3.9 and started getting site down errors after adding a link field that seemed to didn't fully get created. Restored a backup and would still crash whenever I cleared my cache, removed modules until it started working but then wouldn't work for anonymous users.

I used #10 and now it loads for anonymous but still not clear what the original cause was.

When viewing logs, I still get a white screen with:

The website encountered an unexpected error. Please try again later.
Error: Call to a member function getCacheMaxAge() on null in Drupal\views\Plugin\views\query\Sql->getCacheMaxAge() (line 1701 of core/modules/views/src/Plugin/views/query/Sql.php).
Drupal\views\Plugin\views\query\Sql->getCacheMaxAge() (Line: 263)
Drupal\views\Plugin\views\cache\CachePluginBase->getCacheMaxAge() (Line: 686)
Drupal\views\Plugin\views\style\StylePluginBase->renderFields() (Line: 584)
Drupal\views\Plugin\views\style\StylePluginBase->renderGrouping() (Line: 475)
Drupal\views\Plugin\views\style\StylePluginBase->render() (Line: 2170)
Drupal\views\Plugin\views\display\DisplayPluginBase->render() (Line: 1533)
Drupal\views\ViewExecutable->render() (Line: 199)
Drupal\views\Plugin\views\display\Page->execute() (Line: 1630)
Drupal\views\ViewExecutable->executeDisplay() (Line: 81)
Drupal\views\Element\View::preRenderViewElement()
call_user_func_array() (Line: 101)
Drupal\Core\Render\Renderer->doTrustedCallback() (Line: 772)
Drupal\Core\Render\Renderer->doCallback() (Line: 363)
Drupal\Core\Render\Renderer->doRender() (Line: 201)
Drupal\Core\Render\Renderer->render() (Line: 241)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 564)
Drupal\Core\Render\Renderer->executeInRenderContext() (Line: 242)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare() (Line: 132)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse() (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray()
call_user_func() (Line: 142)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch() (Line: 163)
Symfony\Component\HttpKernel\HttpKernel->handleRaw() (Line: 80)
Symfony\Component\HttpKernel\HttpKernel->handle() (Line: 58)
Drupal\Core\StackMiddleware\Session->handle() (Line: 48)
Drupal\Core\StackMiddleware\KernelPreHandle->handle() (Line: 106)
Drupal\page_cache\StackMiddleware\PageCache->pass() (Line: 85)
Drupal\page_cache\StackMiddleware\PageCache->handle() (Line: 48)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle() (Line: 51)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle() (Line: 23)
Stack\StackedHttpKernel->handle() (Line: 708)
Drupal\Core\DrupalKernel->handle() (Line: 19)
frank.dev’s picture

I was able to fix the problem described here:

The data record with the uid = "0" was missing in the "users" database table. However, the record was not simply deleted beforehand, instead the uid's seem to have simply "increased" by one place - uid "0" became "1", "1" became "2" and so on.

I solved the problem by resetting all existing uid's by 1 - 1 to 0, 2 to 1 and so on.

I was then able to take patch #10 back again, it's no longer needed.

frank.dev’s picture

Addendum:

The uid "0" stands for the anonymous user and is therefore urgently needed.

troybthompson’s picture

I just looked and my uids are 1, 7, 8, 9 with 9 being blank so I assume anonymous. So what would cause that?

There was a user 0 in my backup from December so I'm guessing a Drupal update since then? Possibly a module but I don't think I've added much.

frank.dev’s picture

I don't know exactly what caused the error either.

All I know is that for the last few months it has been observed whenever I import a full Drupal database backup into a new empty database. At this point, the uid 0 "disappeared" and even before I connected this new database to a Drupal installation.

If I then only import the "users" table into the database created in this way, uid 0 is retained.

troybthompson, has the problem been solved for you now?

rgpublic’s picture

@Frank.dev: Did you check your backup/restore method? If this is reproducible, perhaps it has sth. to do with type of export/import method that this line is lost. Perhaps it's a bug/configuration issue in PHPMyAdmin / mysqldump... Just a thought. In my case, the line was definitely there, so there might be different issues here that lead to the symptom.

frank.dev’s picture

rgpublic, thanks for the tip. However, I have been using the same tool to import the database for 5 years now:
https://www.ozerov.de/bigdump/
Also with the same PHP version.

The error does not actually occur with every database import, but for the first time in the last few months and quite often.

Addendum:
When importing the backup file, no line / data record was deleted. The modified "users" table contained the same number of records as the backup file and the original database.

dpi’s picture

If you are exporting/importing your database and you're finding you have missing anonymous user, you can try setting the SQL mode before your import with SET sql_mode =NO_AUTO_VALUE_ON_ZERO. Otherwise MySQL, etc, will instead treat the zero ID as autoincrementable and append it to the end of your users table with a new ID.

If you use Drush SQL export you already get this mode set, see \Drupal\Core\Command\DbDumpCommand::getTemplate. Im guessing you are not using Drush for these exports, perhaps they are done with the mysql/mysqldump CLI tool or some higher level tool.

frank.dev’s picture

@dpi, thanks for the tip. However, "SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";" is always set in my backup files,

troybthompson’s picture

That may be the problem in my case, it looks like the original backup when my site was broken had UID 0. The error initially was "Drupal\Component\Plugin\Exception\PluginNotFoundException: The "" entity type does not exist. in Drupal\Core\Entity\EntityTypeManager->getDefinition() (line 143 of core/lib/Drupal/Core/Entity/EntityTypeManager.php)." and then after backing up and restoring I got the error message in this issue.

I use Navicat for database work and haven't had an issue before but this backup was created by my hosting place for me. In their sql file, the only reference to auto value is:

/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;

which I assume means commented out?

Manually changing it back to 0 solved the problem, let me view the error log page again, and allowed me to remove patch #10. So thank you for the help even if this is unrelated to this issue.

But now that means I still have the cause of my original issue to figure out. =^)

Version: 9.4.x-dev » 9.5.x-dev

Drupal 9.4.0-alpha1 was released on May 6, 2022, which means new developments and disruptive changes should now be targeted for the 9.5.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

Version: 9.5.x-dev » 10.1.x-dev

Drupal 9.5.0-beta2 and Drupal 10.0.0-beta2 were released on September 29, 2022, which means new developments and disruptive changes should now be targeted for the 10.1.x-dev branch. For more information see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

anybody’s picture

veder’s picture

I was experiencing the same error in my Drupal site, core ver. 9.1.0 after importing a database from one of my team member's localhost. That was occurring because of the same problem as is described in #28. However my fix was different. I opened the database file-I had received from my colleague and imported into my localhost-and observed that an insert statement for the anonymous user (uid, 0) was present in the SQL script. For some reason the uid of that row got changed to 186 in my site's database in my localhost; I found this out by executing a select query with a where condition for the uuid column with the value copied and pasted from the database script. I just changed 186 to 0.

Version: 10.1.x-dev » 11.x-dev

Drupal core is moving towards using a “main” branch. As an interim step, a new 11.x branch has been opened, as Drupal.org infrastructure cannot currently fully support a branch named main. New developments and disruptive changes should now be targeted for the 11.x branch, which currently accepts only minor-version allowed changes. For more information, see the Drupal core minor version schedule and the Allowed changes during the Drupal core release cycle.

dpi’s picture

dave reid’s picture

I just experienced this in a kernel test in some custom code as well. I believe when we had code running Url::fromUri('internal:/taxonomy/term/1').

herved’s picture

Cross-posting #3357354-16: The 'entity:user' context is required and not present here.
The patch solves my issue on 2 projects caused by image styles as explained there. Few, what an absolute horror to debug. Thank you so much!

@Berdir from #12: Could the introduction of image lazy loading in core be directly related to the emergence of this issue?

Edit: I will reroll the patch for 10.1.x

herved’s picture

StatusFileSize
new1.86 KB
new545 bytes
herved’s picture

StatusFileSize
new1.95 KB
new642 bytes

Ok the assert is wrong there it seems.
Not exactly sure what to assert tbh, we mainly need to ensure that there are no exceptions thrown even though the current user context is NULL (because the anonymous user is used).

We could also do this but it's not really what we are trying to test:

$context_repository = $this->container->get('context.repository');
$contexts = $context_repository->getAvailableContexts();
$this->assertArrayHasKey('@user.current_user_context:current_user', $contexts);
$this->assertFalse($contexts['@user.current_user_context:current_user']->hasContextValue());

PS: Very interesting to see that such a simple URL causes the issue as anonymous. My case in #42 was hitting the same issue but from \Drupal\Core\Routing\AccessAwareRouter::match

berdir’s picture

FWIW, #3158130: Many calls to ContextRepository::getAvailableContexts() due to entity upcasting removes that whole chunk completely, I'd expect that fixes the issue as well.

herved’s picture

Indeed it does, and I see no side effects. I'll use that instead then. Thanks for pointing it out.
I guess we could close this one then?
Cheers

berdir’s picture

I'm not sure, maybe wait until it's actually resolved. I'd love to get it done, but no idea how feasible it is to get it done soon. Hard to move it forward as it's related to several other language upcasting issues.

gabesullice’s picture

For those looking for a simple workaround to fix their kernel tests, the following additions to my kernel test class suppressed the exception.

I imported Drupal\Tests\user\Traits\UserCreationTrait and added that trait to my kernel test class with use UserCreationTest. Then I added $this->setUpCurrentUser() in my class's setUp method. In my case, I didn't need to call that method any optional arguments.

yurg’s picture

There are a lot of

Drupal\Component\Plugin\Exception\ContextException: The 'entity:user' context is required and not present. in Drupal\Core\Plugin \Context\Context->getContextValue()

mentions across the versions. For me the #44 is a life-saver. Thanks.

joachim’s picture

If you don't want to make a user current, this workaround creates the anon user in a kernel test:

use UserCreationTest

    $values = [
      'uid' => 0,
      'status' => 0,
      'name' => '',
    ];
    $this->createUser(values: $values);

Note that AFAICT the next call to createUser() will create user 1, so call it again if you don't want you actual test users to be that.

mstrelan’s picture

Status: Needs work » Postponed (maintainer needs more info)
Related issues: +#3158130: Many calls to ContextRepository::getAvailableContexts() due to entity upcasting

As per #45 this is probably no longer needed as per #3158130: Many calls to ContextRepository::getAvailableContexts() due to entity upcasting which has landed. Marking PMNMI for someone to verify if there is anything left to do here.

smustgrave’s picture

Status: Postponed (maintainer needs more info) » Closed (outdated)
Issue tags: +Bug Smash Initiative

Since there's been no follow up to #51 going to close out, if still a bug in D11 please re-open.