<commit_before># -*- coding: utf-8 -*-
'''
Smoothtest
Copyright (c) 2015 Juju. Inc

Code Licensed under MIT License. See LICENSE file.
'''
import unittest
import os

from selenium.common.exceptions import UnexpectedAlertPresentException
from smoothtest.webunittest.WebdriverManager import WebdriverManager
from smoothtest.Logger import Logger
from smoothtest.webunittest.XpathBrowser import XpathBrowser
from contextlib import contextmanager
from smoothtest.settings.default import SINGLE_TEST_LIFE
from selenium.webdriver.remote.webdriver import WebDriver


class WebUnitTestBase(unittest.TestCase):

    def _get_local_html_path(self, name):
        return os.path.join(os.path.dirname(__file__), 'html', name)

    def _local_path_to_url(self, path):
        return 'file://' + path

    def get_local_page(self, path):
        self.browser.get_url(self._local_path_to_url(path))

    @contextmanager
    def create_html(self, name, body, jquery=True, **kwargs):
        templ = '''
<!DOCTYPE html>
<html>
<head>
  {jquery}
  <title>{name}</title>
</head>
<body>
      {body}
</body>
</html>
        '''
        if jquery:
            jquery = ''
        else:
            jquery = ''
        
        kwargs.update(locals())
        html = templ.format(**kwargs)
        path = self._get_local_html_path(name + '.html')
        with open(path, 'w') as fh:
            fh.write(html)
        try:
            yield  path
        except:
            raise
        finally:
            os.remove(path)

    def setUp(self):
        self.__level_mngr = WebdriverManager().enter_level(level=SINGLE_TEST_LIFE)
        webdriver = self.__level_mngr.acquire_driver()
        logger = Logger(__name__)
        self.browser = XpathBrowser('', webdriver, logger, settings={})

    def tearDown(self):
        self.__level_mngr.exit_level()


class TestXpathBrowser(WebUnitTestBase):
    '''
    TODO:
    - test select/has/extract 
    - get_url (with condition)
    - get_path (with condition)
    - test wait
    '''

    def test_fill(self):
        body = '''
        <form>
          First name:<br>
          <input id=1 type="text" name="firstname">
          <br>
          Last name:<br>
          <input id=2 type="text" name="lastname">
        </form> 
        '''
        self.browser.set_base_url('http://mepinta.com/')
        self.assertEqual(self.browser.build_url('example'), 'http://mepinta.com/example')
        with self.create_html('test_fill', body) as path:
            self.get_local_page(path)
            self.assertTrue(self.browser.current_path().endswith('.html'))
            self.assertTrue(self.browser.current_url().endswith('.html'))
            self.assertIsInstance(self.browser.get_driver(), WebDriver)
            self.browser.fill_form(firstname='John1', lastname='Doe1')<commit_msg>Clean code<commit_after># -*- coding: utf-8 -*-
'''
Smoothtest
Copyright (c) 2015 Juju. Inc

Code Licensed under MIT License. See LICENSE file.
'''
from selenium.common.exceptions import UnexpectedAlertPresentException
from smoothtest.webunittest.WebdriverManager import WebdriverManager
from smoothtest.Logger import Logger
from smoothtest.webunittest.XpathBrowser import XpathBrowser
from contextlib import contextmanager
from smoothtest.settings.default import SINGLE_TEST_LIFE
from selenium.webdriver.remote.webdriver import WebDriver
import tempfile
import shutil
import unittest
import os


class WebUnitTestBase(unittest.TestCase):

    def _path_to_url(self, path):
        return 'file://' + path

    def get_local_page(self, path):
        self.browser.get_url(self._path_to_url(path))

    @contextmanager
    def create_html(self, name, body, **kwargs):
        templ = '''
<!DOCTYPE html>
<html>
<head>
  {jquery}
  <title>{name}</title>
</head>
<body>
      {body}
</body>
</html>
        '''
        jquery = ''
        kwargs.update(locals())
        html = templ.format(**kwargs)
        if not self._tempdir:
            self._tempdir = tempfile.mkdtemp(prefix='smoothtest')
        path = os.path.join(self._tempdir, name + '.html')
        # Create html page in temporary dir
        with open(path, 'w') as fh:
            fh.write(html)
        try:
            yield  path
        except:
            raise
        finally:
            os.remove(path)

    def setUp(self):
        self.__level_mngr = WebdriverManager().enter_level(level=SINGLE_TEST_LIFE)
        webdriver = self.__level_mngr.acquire_driver()
        logger = Logger(__name__)
        self.browser = XpathBrowser('', webdriver, logger, settings={})
        # Temp dir to save pages
        self._tempdir = None

    def tearDown(self):
        self.__level_mngr.exit_level()
        if self._tempdir:
            shutil.rmtree(self._tempdir, ignore_errors=True)
            self._tempdir = None


class TestXpathBrowser(WebUnitTestBase):
    '''
    TODO:
    - test select/has/extract 
    - get_url (with condition)
    - get_path (with condition)
    - test wait
    '''

    def test_fill(self):
        body = '''
        <form>
          First name:<br>
          <input id=1 type="text" name="firstname">
          <br>
          Last name:<br>
          <input id=2 type="text" name="lastname">
        </form> 
        '''
        self.browser.set_base_url('http://mepinta.com/')
        self.assertEqual(self.browser.build_url('example'), 'http://mepinta.com/example')
        with self.create_html('test_fill', body) as path:
            self.get_local_page(path)
            self.assertTrue(self.browser.current_path().endswith('.html'))
            self.assertTrue(self.browser.current_url().endswith('.html'))
            self.assertIsInstance(self.browser.get_driver(), WebDriver)
            self.browser.fill_form(firstname='John1', lastname='Doe1')
{'fraction_non_alphanumeric': 0.12086580086580087, 'fraction_numerical': 0.003116883116883117, 'mean_word_length': 2.639571518588532, 'pattern_counts': {'":': 0, '<': 35, '<?xml version=': 0, '>': 35, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4733501', 'n_tokens_mistral': 1807, 'n_tokens_neox': 1742, 'n_words': 363}