Quellcode durchsuchen

Fix issue with login

Improve handeling of environment variables
joostsijm vor 2 Jahren
Ursprung
Commit
2cae6a3d51

+ 7 - 7
src/rival_regions_wrapper/authentication_handler.py

@@ -30,17 +30,16 @@ LOGIN_METHOD_DICT = {
 class AuthenticationHandler:
     """class for RR client"""
 
-    def __init__(self, show_window=False, captcha_key=None):
+    def __init__(self, show_window=False, captcha_key=None, debug=False):
         LOGGER.info(
-            'Initialize, show window: "%s", captcha key: "%s"',
-            show_window,
-            bool(captcha_key),
-        )
+                'Initialize, show window: "%s", captcha key: "%s", debug: %s',
+                show_window, bool(captcha_key), debug
+            )
         self.show_window = show_window
+        self.captcha_client = None
         if captcha_key:
             self.captcha_client = AnticaptchaClient(captcha_key)
-        else:
-            self.captcha_client = None
+        self.debug = debug
         self.login_method = None
         self.username = None
         self.password = None
@@ -92,6 +91,7 @@ class AuthenticationHandler:
             self.username,
             self.password,
             self.captcha_client,
+            self.debug,
         )
 
         cookies = []

+ 5 - 1
src/rival_regions_wrapper/browser.py

@@ -85,5 +85,9 @@ class Browser(webbot.Browser):
         self.add_cookie(cookie)
 
     def refresh(self):
-        """To pretent lint error"""
+        """To prevent lint error"""
         self.refresh()
+
+    def get_screenshot_as_file(self, filename):
+        """To prevent lint error"""
+        self.get_screenshot_as_file(filename)

+ 37 - 22
src/rival_regions_wrapper/login_methods.py

@@ -14,13 +14,18 @@ from rival_regions_wrapper.exceptions import (
 )
 
 
+# to write page source to html file
+# with open('source.html', 'w') as source:
+#     source.write(browser.get_page_source())
+
+
 # This should be working
-def login_google(show_window, username, password, captcha_client=None):
+def login_google(show_window, username, password, captcha_client=None, debug=False):
     """login using Google"""
     browser = Browser(show_window, DATA_DIR, "g_{}".format(username))
     LOGGER.info('Google: "%s": Login start', username)
     try:
-        # browser = Browser(show_window, DATA_DIR, 'g_{}'.format(username))
+        browser = Browser(show_window, DATA_DIR, 'g_{}'.format(username))
         browser.go_to("https://rivalregions.com/")
         google_login_link = browser.driver.find_element_by_css_selector(
             ".sa_link.gogo"
@@ -31,33 +36,43 @@ def login_google(show_window, username, password, captcha_client=None):
         LOGGER.info('Google: "%s": still RR session active', username)
         return browser
 
-    # browser.get_screenshot_as_file('test_1.png')
+    if debug:
+        browser.get_screenshot_as_file('test_1.png')
 
     if browser.driver.find_elements_by_css_selector("#gold"):
         LOGGER.info('Google: "%s": account already logged in', username)
         return browser
 
-    LOGGER.info('Google: "%s": Typing in username', username)
-    if not browser.driver.find_elements_by_css_selector("#Email"):
-        LOGGER.info('Google: "%s": problem with fill in password', username)
-        raise LoginException() from NoSuchElementException
-    browser.type(username, css_selector="#Email")
+    if browser.driver.find_elements_by_css_selector("#choose-account-0"):
+        LOGGER.info('Google: "%s": account is logged out', username)
+        browser.click(css_selector="#choose-account-0")
 
-    # browser.get_screenshot_as_file('test_2.png')
+        if debug:
+            browser.get_screenshot_as_file('test_2.png')
+    else:
+        LOGGER.info('Google: "%s": Typing in username', username)
+        if not browser.driver.find_elements_by_css_selector("#Email"):
+            LOGGER.info('Google: "%s": problem with fill in email', username)
+            raise LoginException() from NoSuchElementException
+        browser.type(username, css_selector="#Email")
 
-    LOGGER.info('Google: "%s": pressing next button', username)
-    browser.click(css_selector="#next")
-    time.sleep(0.5)
+        if debug:
+            browser.get_screenshot_as_file('test_3.png')
 
-    # browser.get_screenshot_as_file('test_3.png')
+        LOGGER.info('Google: "%s": pressing next button', username)
+        browser.click(css_selector="#next")
+        time.sleep(0.5)
+
+        if debug:
+            browser.get_screenshot_as_file('test_4.png')
 
     while browser.driver.find_elements_by_css_selector("#captcha-box"):
         LOGGER.info('Google: "%s": Captcha present', username)
         if not captcha_client:
             raise NoCaptchaClientException()
-        captcha_url = browser.find_elements(css_selector="#captcha-img img")[
-            0
-        ].get_attribute("src")
+        captcha_url = browser.find_elements(
+                css_selector="#captcha-img img"
+            )[0].get_attribute("src")
         LOGGER.debug('Google: "%s": Captcha url: "%s"', username, captcha_url)
         image = requests.get(captcha_url, stream=True).raw
         image.decode_content = True
@@ -74,7 +89,8 @@ def login_google(show_window, username, password, captcha_client=None):
         browser.click(css_selector="#next")
         time.sleep(0.5)
 
-        # browser.get_screenshot_as_file('test_4.png')
+        if debug:
+            browser.get_screenshot_as_file('test_5.png')
 
     if not browser.driver.find_elements_by_css_selector("#password"):
         LOGGER.info('Google: "%s": browser security issue', username)
@@ -90,19 +106,18 @@ def login_google(show_window, username, password, captcha_client=None):
             return browser
         raise LoginException()
 
-    # with open('source.html', 'w') as source:
-    #     source.write(browser.get_page_source())
-
     LOGGER.info('Google: "%s": Typing in password', username)
     browser.type(password, css_selector="input")
 
-    # browser.get_screenshot_as_file('test_5.png')
+    if debug:
+        browser.get_screenshot_as_file('test_6.png')
 
     LOGGER.info('Google: "%s": pressing sign in button', username)
     browser.click(css_selector="#submit")
     time.sleep(0.5)
 
-    # browser.get_screenshot_as_file('test_6.png')
+    if debug:
+        browser.get_screenshot_as_file('test_7.png')
 
     return browser
 

+ 2 - 2
src/rival_regions_wrapper/middleware.py

@@ -25,10 +25,10 @@ class MiddlewareBase(ABC):
 class LocalAuthentication(MiddlewareBase):
     """Local authentication"""
 
-    def __init__(self, show_window=False, captcha_client=None):
+    def __init__(self, show_window=False, captcha_client=None, debug=False):
         super().__init__()
         self.authentication_handler = AuthenticationHandler(
-            show_window, captcha_client
+            show_window, captcha_client, debug
         )
 
     def set_credentials(self, username, password, login_method):

+ 57 - 16
tests/conftest.py

@@ -47,60 +47,100 @@ def vcr(vcr):
 @pytest.fixture(scope="module")
 def conference_id():
     """Get conference id from environ variable"""
-    return os.environ.get('CONFERENCE_ID', None)
+    value = os.environ.get('CONFERENCE_ID', None)
+    if not value:
+        raise Exception(
+            'Load the following variable in your user environment: CONFERENCE_ID'
+        )
+    return value
 
 
 @pytest.fixture(scope="module")
 def message():
     """Get message from environ variable"""
-    return os.environ.get('MESSAGE', None)
+    value = os.environ.get('MESSAGE', None)
+    if not value:
+        raise Exception(
+            'Load the following variable in your user environment: MESSAGE'
+        )
+    return value
 
 
 @pytest.fixture(scope="module")
 def conference_title():
     """Get conference title from environ variable"""
-    return os.environ.get('CONFERENCE_TITLE', None)
+    value = os.environ.get('CONFERENCE_TITLE', None)
+    if not value:
+        raise Exception(
+            'Load the following variable in your user environment: CONFERENCE_TITLE'
+        )
+    return value
 
 
 @pytest.fixture(scope="module")
 def language_chat():
     """Get language chat from environ varriable"""
-    return os.environ.get('LANGUAGE_CHAT', None)
+    value = os.environ.get('LANGUAGE_CHAT', None)
+    if not value:
+        raise Exception(
+            'Load the following variable in your user environment: LANGUAGE_CHAT'
+        )
+    return value
 
 
 @pytest.fixture(scope="module")
 def perk():
     """Get perk from environ varriable"""
-    return os.environ.get('PERK', None)
+    value = os.environ.get('PERK', None)
+    if not value:
+        raise Exception(
+            'Load the following variable in your user environment: PERK'
+        )
+    return value
 
 
 @pytest.fixture(scope="module")
 def perk_upgrade_type():
     """Get perk upgrade type from environ varriable"""
-    return os.environ.get('PERK_UPGRADE_TYPE', None)
-
-
-def perk_upgrade_type():
-    """Get perk upgrade type from environ varriable"""
-    return os.environ.get('PERK_UPGRADE_TYPE', None)
+    value = os.environ.get('PERK_UPGRADE_TYPE', None)
+    if not value:
+        raise Exception(
+            'Load the following variable in your user environment: PERK_UPGRADE_TYPE'
+        )
+    return value
 
 
 @pytest.fixture(scope="module")
 def craft_item():
     """Get craft item from environ varriable"""
-    return os.environ.get('CRAFT_ITEM', None)
+    value = os.environ.get('CRAFT_ITEM', None)
+    if not value:
+        raise Exception(
+            'Load the following variable in your user environment: CRAFT_ITEM'
+        )
+    return value
 
 
 @pytest.fixture(scope="module")
 def craft_amount():
     """Get craft amount from environ varriable"""
-    return os.environ.get('CRAFT_AMOUNT', None)
+    value = os.environ.get('CRAFT_AMOUNT', None)
+    if not value:
+        raise Exception(
+            'Load the following variable in your user environment: CRAFT_AMOUNT'
+        )
+    return value
 
 
 @pytest.fixture(scope="module")
 def profile_id():
     """Get profile id from environ varriable"""
-    return os.environ.get('PROFILE_ID', None)
+    value = os.environ.get('PROFILE_ID', None)
+    if not value:
+        raise Exception(
+            'Load the following variable in your user environment: PROFILE_ID'
+        )
+    return value
 
 
 @pytest.fixture(scope="module")
@@ -109,14 +149,15 @@ def middleware():
     username = os.environ.get('USERNAME', None)
     password = os.environ.get('PASSWORD', None)
     login_method = os.environ.get('LOGIN_METHOD', None)
+    debug = os.environ.get('DEBUG', None)
     captcha_key = os.environ.get('CAPTCHA_KEY', None)
     if None in (username, password, login_method):
         raise MissingAuthenticationError(
             'Load the following variables in your user environment: '
-            'username, password, login_method'
+            'USERNAME, PASSWORD, LOGIN_METHOD'
         )
     _middleware = LocalAuthentication(
-            False, AnticaptchaClient(captcha_key)
+            False, AnticaptchaClient(captcha_key), debug
         )
     return _middleware.set_credentials(
             username, password, login_method