# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import logging
import os
import unittest

from telemetry import benchmark
from telemetry.core import util
from telemetry.internal.browser import browser_finder
from telemetry.testing import options_for_unittests
from telemetry.testing import simple_mock

_ = simple_mock.DONT_CARE


def _GetCredentialsPath():
  # TODO: This shouldn't depend on tools/perf.
  credentials_path = os.path.join(util.GetChromiumSrcDir(),
      'tools', 'perf', 'data', 'credentials.json')
  if not os.path.exists(credentials_path):
    return None
  return credentials_path


class FormBasedCredentialsBackendUnitTestBase(unittest.TestCase):
  def setUp(self):
    self._credentials_type = None

  @benchmark.Disabled
  def testRealLoginIfPossible(self):
    credentials_path = _GetCredentialsPath()
    if not credentials_path:
      logging.warning('Credentials file not found, skipping test.')
      return

    options = options_for_unittests.GetCopy()
    with browser_finder.FindBrowser(options).Create(options) as b:
      b.credentials.credentials_path = credentials_path
      if not b.credentials.CanLogin(self._credentials_type):
        return
      ret = b.credentials.LoginNeeded(b.tabs[0], self._credentials_type)
      self.assertTrue(ret)

  @benchmark.Disabled
  def testRealLoginWithDontOverrideProfileIfPossible(self):
    credentials_path = _GetCredentialsPath()
    if not credentials_path:
      logging.warning('Credentials file not found, skipping test.')
      return

    options = options_for_unittests.GetCopy()

    # Login once to make sure our default profile is logged in.
    with browser_finder.FindBrowser(options).Create() as b:
      b.credentials.credentials_path = credentials_path

      if not b.credentials.CanLogin(self._credentials_type):
        return

      tab = b.tabs[0]

      # Should not be logged in, since this is a fresh credentials
      # instance.
      self.assertFalse(b.credentials.IsLoggedIn(self._credentials_type))

      # Log in.
      ret = b.credentials.LoginNeeded(tab, self._credentials_type)

      # Make sure login was successful.
      self.assertTrue(ret)
      self.assertTrue(b.credentials.IsLoggedIn(self._credentials_type))

      # Reset state. Now the backend thinks we're logged out, even
      # though we are logged in in our current browser session. This
      # simulates the effects of running with --dont-override-profile.
      b.credentials._ResetLoggedInState() # pylint: disable=W0212

      # Make sure the backend thinks we're logged out.
      self.assertFalse(b.credentials.IsLoggedIn(self._credentials_type))
      self.assertTrue(b.credentials.CanLogin(self._credentials_type))

      # Attempt to login again. This should detect that we've hit
      # the 'logged in' page instead of the login form, and succeed
      # instead of timing out.
      ret = b.credentials.LoginNeeded(tab, self._credentials_type)

      # Make sure our login attempt did in fact succeed and set the
      # backend's internal state to 'logged in'.
      self.assertTrue(ret)
      self.assertTrue(b.credentials.IsLoggedIn(self._credentials_type))

  def testLoginUsingMock(self):
    raise NotImplementedError()

  def _LoginUsingMock(self, backend, login_page_url, email_element_id,
                      password_element_id, form_element_id,
                      already_logged_in_js): # pylint: disable=R0201
    tab = simple_mock.MockObject()
    ar = simple_mock.MockObject()

    config = {'username': 'blah',
              'password': 'blargh'}

    tab.ExpectCall('Navigate', login_page_url)
    tab.ExpectCall('EvaluateJavaScript', already_logged_in_js).WillReturn(False)
    tab.ExpectCall('WaitForDocumentReadyStateToBeInteractiveOrBetter')

    ar.ExpectCall('WaitForJavaScriptCondition',
                  '(document.querySelector("#%s") !== null) || (%s)' % (
                      form_element_id, already_logged_in_js), 60)
    ar.ExpectCall('WaitForNavigate')

    def VerifyEmail(js):
      assert email_element_id in js
      assert 'blah' in js
    tab.ExpectCall('ExecuteJavaScript', _).WhenCalled(VerifyEmail)

    def VerifyPw(js):
      assert password_element_id in js
      assert 'largh' in js
    tab.ExpectCall('ExecuteJavaScript', _).WhenCalled(VerifyPw)

    def VerifySubmit(js):
      assert '.submit' in js or '.click' in js
    tab.ExpectCall('ExecuteJavaScript', _).WhenCalled(VerifySubmit)

    # Checking for form still up.
    tab.ExpectCall('EvaluateJavaScript', _).WillReturn(False)

    backend.LoginNeeded(tab, ar, config)

@@ -167,3107 +167,207 @@
 ort 
-logging%0Aimport os%0Aimport unittest%0A%0Afrom telemetry import benchmark%0Afrom telemetry.core import util%0Afrom telemetry.internal.browser import browser_finder%0Afrom telemetry.testing import options_for_unittests%0Afrom telemetry.testing import simple_mock%0A%0A_ = simple_mock.DONT_CARE%0A%0A%0Adef _GetCredentialsPath():%0A  # TODO: This shouldn't depend on tools/perf.%0A  credentials_path = os.path.join(util.GetChromiumSrcDir(),%0A      'tools', 'perf', 'data', 'credentials.json')%0A  if not os.path.exists(credentials_path):%0A    return None%0A  return credentials_path%0A%0A%0Aclass FormBasedCredentialsBackendUnitTestBase(unittest.TestCase):%0A  def setUp(self):%0A    self._credentials_type = None%0A%0A  @benchmark.Disabled%0A  def testRealLoginIfPossible(self):%0A    credentials_path = _GetCredentialsPath()%0A    if not credentials_path:%0A      logging.warning('Credentials file not found, skipping test.')%0A      return%0A%0A    options = options_for_unittests.GetCopy()%0A    with browser_finder.FindBrowser(options).Create(options) as b:%0A      b.credentials.credentials_path = credentials_path%0A      if not b.credentials.CanLogin(self._credentials_type):%0A        return%0A      ret = b.credentials.LoginNeeded(b.tabs%5B0%5D, self._credentials_type)%0A      self.assertTrue(ret)%0A%0A  @benchmark.Disabled%0A  def testRealLoginWithDontOverrideProfileIfPossible(self):%0A    credentials_path = _GetCredentialsPath()%0A    if not credentials_path:%0A      logging.warning('Credentials file not found, skipping test.')%0A      return%0A%0A    options = options_for_unittests.GetCopy()%0A%0A    # Login once to make sure our default profile is logged in.%0A    with browser_finder.FindBrowser(options).Create() as b:%0A      b.credentials.credentials_path = credentials_path%0A%0A      if not b.credentials.CanLogin(self._credentials_type):%0A        return%0A%0A      tab = b.tabs%5B0%5D%0A%0A      # Should not be logged in, since this is a fresh credentials%0A      # instance.%0A      self.assertFalse(b.credentials.IsLoggedIn(self._credentials_type))%0A%0A      # Log in.%0A      ret = b.credentials.LoginNeeded(tab, self._credentials_type)%0A%0A      # Make sure login was successful.%0A      self.assertTrue(ret)%0A      self.assertTrue(b.credentials.IsLoggedIn(self._credentials_type))%0A%0A      # Reset state. Now the backend thinks we're logged out, even%0A      # though we are logged in in our current browser session. This%0A      # simulates the effects of running with --dont-override-profile.%0A      b.credentials._ResetLoggedInState() # pylint: disable=W0212%0A%0A      # Make sure the backend thinks we're logged out.%0A      self.assertFalse(b.credentials.IsLoggedIn(self._credentials_type))%0A      self.assertTrue(b.credentials.CanLogin(self._credentials_type))%0A%0A      # Attempt to login again. This should detect that we've hit%0A      # the 'logged in' page instead of the login form, and succeed%0A      # instead of timing out.%0A      ret = b.credentials.LoginNeeded(tab, self._credentials_type)%0A%0A      # Make sure our login attempt did in fact succeed and set the%0A      # backend's internal state to 'logged in'.%0A      self.assertTrue(ret)%0A      self.assertTrue(b.credentials.IsLoggedIn(self._credentials_type))
+unittest%0A%0Afrom telemetry.testing import simple_mock%0A%0A_ = simple_mock.DONT_CARE%0A%0A%0Aclass FormBasedCredentialsBackendUnitTestBase(unittest.TestCase):%0A  def setUp(self):%0A    self._credentials_type = None
 %0A%0A  

Remove reference to chromium src dir in form_based_credentials_backend_unittest_base