You are here

function ServicesResourceUsertests::testUserLogin in Services 7.3

Same name and namespace in other branches
  1. 6.3 tests/functional/ServicesResourceUserTests.test \ServicesResourceUsertests::testUserLogin()

Test login method.

Create user. Login. Try to login with another user (to get error). Login with wrong credentials (to get error).

File

tests/functional/ServicesResourceUserTests.test, line 482
Call the endpoint tests when no authentication is being used.

Class

ServicesResourceUsertests
Run test cases for the endpoint with no authentication turned on.

Code

function testUserLogin() {
  $account = $this
    ->drupalCreateUser();

  // Logout first.
  $this
    ->drupalLogout();
  $response = $this
    ->servicesPost($this->endpoint->path . '/user/login', array(
    'username' => $account->name,
    'password' => $account->pass_raw,
  ));
  $response_data = $response['body'];
  $proper_answer = isset($response_data->sessid) && isset($response_data->user) && $response_data->user->name == $account->name;
  $this
    ->assertTrue($proper_answer, 'User successfully logged in.', 'UserResource: Login');

  // Make sure the session exists in the database.
  $result = db_query("SELECT * FROM {sessions} WHERE :uid=uid", array(
    ':uid' => $account->uid,
  ))
    ->fetchObject();
  $this
    ->assertTrue(!empty($result), 'Session found', 'UserResource: Login');

  // Save session details.
  $this->session_id = $response_data->sessid;
  $this->session_name = $response_data->session_name;
  $this->loggedInUser = $response_data->user;

  // Try to login with another user to get error.
  $account2 = $this
    ->drupalCreateUser();
  $response = $this
    ->servicesPost($this->endpoint->path . '/user/login', array(
    'username' => $account2->name,
    'password' => $account2->pass_raw,
  ));
  $this
    ->assertTrue(strpos($response['status'], 'Already logged in as ' . $account->name) !== FALSE, 'Session is properly opened for logged in user.', 'UserResource: Login');

  // Logout.
  $this
    ->drupalLogout();

  // Try to login with wrong credentials.
  $response = $this
    ->servicesPost($this->endpoint->path . '/user/login', array(
    'username' => $account->name,
    'password' => $this
      ->randomString(),
  ));
  $this
    ->assertTrue(strpos($response['status'], 'Wrong username or password') !== FALSE, 'User cannot login with wrong username / password.', 'UserResource: Login');
}