My module has some special functionality based on the user agent of the request. I want to write tests for this functionality based on D8's BrowserTestBase, but it doesn't seem possible to change the user agent string.

The prepareRequest method of BrowserTestBase sets the user agent to the value of drupal_generate_test_ua($this->databasePrefix).

For a test, I tried changing this value to something else, and it breaks the tests.

Now I realize that there appears to be some functionality built into core based on this value that drupal_generate_test_ua returns and there's checks all over core to detect if Drupal is running within a test or not.

Is there a workaround or any hope for writing tests with a custom user agent?


No, you can't.

BrowserTestBase, just like other other tests that support web requests uses the user agent to identify which test environment you're in (there could be multiple, parallel ones). Changing the user agent would result in your request being sent against the main site.

The only workaround that I see is to send another header (if that's actually possible through the API, not sure). In your could you would then look at that header instead. It's not perfect and it requires you to write special code for tests, but I can't really see another way if you really rely on the user agent.

  • Thought so, thanks. I added this issue for core which would allow modules to at least add on their own user agent to the end of the simpletest one: drupal.org/node/2820515 – Brian Oct 23 '16 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.