Make WordPress Core

Opened 11 years ago

Closed 11 years ago

Last modified 11 years ago

#29712 closed enhancement (fixed)

Restore $current_user between unit tests

Reported by: mnelson4's profile mnelson4 Owned by: boonebgorges's profile boonebgorges
Milestone: 4.1 Priority: normal
Severity: normal Version: 4.1
Component: Build/Test Tools Keywords:
Focuses: Cc:

Description

If the $current_user global is changed during a unit test, that change is persisted to all subsequent unit tests, making the tests dependent on order. (eg, meaning that if I change the $current_user to be an admin during a test, they're forevermore an admin. So a later test that assumes the $current_user is the default blank user will probably fail, even though that other unit test could pass when ran in isolation.)
The solution I have is to just clone the $current_user on the first unit test and save it somewhere; and then after each unit test, restore the $current_user to be a clone of the saved original

Attachments (1)

0001-clone-the-current_user-before-the-first-unit-test-an.patch (2.3 KB) - added by mnelson4 11 years ago.
git patch

Download all attachments as: .zip

Change History (6)

#1 @nacin
11 years ago

For the most part, creating your own user is going to be preferred.

If you do need to set the current user for some reason, you should do wp_set_current_user(), then call wp_set_current_user(0) in your tearDown. We could do that in our own class's tearDown, we just haven't.

#2 @mnelson4
11 years ago

  • Component changed from General to Build/Test Tools

#3 @boonebgorges
11 years ago

  • Milestone changed from Awaiting Review to 4.1

If the $current_user global is changed during a unit test, that change is persisted to all subsequent unit tests, making the tests dependent on order.

Yup, good find.

If you do need to set the current user for some reason, you should do wp_set_current_user(), then call wp_set_current_user(0) in your tearDown. We could do that in our own class's tearDown, we just haven't.

We should, and we shall :) mnelson4, I see the motivation behind your original patch (seems like the safe thing to do) but it only uncovers other issues: $userdata can get muddled between tests, as well as a bunch of other ugly little globals. (See setup_userdata().) Safer not to touch the globals at all if we can help it. Core tests expect the current user to be 0 for each test, so wp_set_current_user( 0 ) is a safe bet.

#4 @boonebgorges
11 years ago

  • Owner set to boonebgorges
  • Resolution set to fixed
  • Status changed from new to closed

In 30001:

Set current user to 0 after each unit test.

This prevents $current_user, $userdata, and other user-related globals from
being polluted if a previous test does not properly reset the current user.

Props nacin, mnelson4.
Fixes #29712.

#5 @mnelson4
11 years ago

yeah sounds good thanks!

Note: See TracTickets for help on using tickets.