UnboundLocalError: local variable : On Python - python

I have this code to run test on Jenkins cloud, the run works fine but on my machine a get this error : UnboundLocalError: local variable
My code :
# -*- coding: utf-8 -*-
import time
import unittest
import os
from selenium import webdriver
from com.POMProject.Pages.homePage import HomePage
from com.POMProject.Pages.loginPage import LoginPage
from com.POMProject.Setup.urls import beta_url
from com.POMProject.Setup.users import *
class LoginTest(unittest.TestCase):
#classmethod
def setUp(cls):
if os.getenv('CHROMEWEBDRIVER'):
chromewebdriverbin = os.getenv('CHROMEWEBDRIVER')
cls.driver = webdriver.Chrome(
executable_path=chromewebdriverbin)
cls.driver.implicitly_wait(50)
cls.driver.delete_all_cookies()
cls.driver.set_window_size(1224, 800)
def test_login_valid_user_password(self):
driver = self.driver
driver.get(beta_url)
login = LoginPage(driver)
home = HomePage(driver)
home.click_user_icon()
home.click_login_button()
login.enter_user(user_email)
login.click_next_button()
login.enter_password(user_password)
login.click_submit_button()
driver.quit()
print('Test Completed')
The error message:
E UnboundLocalError: local variable 'chromewebdriverbin' referenced before assignment

This error message...
UnboundLocalError: local variable 'chromewebdriverbin' referenced before assignment
...implies that the varible was referenced even before it was assigned a value.
Analysis
The main issue is, the following condition fails:
if os.getenv('CHROMEWEBDRIVER'):
Hence, the following line:
chromewebdriverbin = os.getenv('CHROMEWEBDRIVER')
never gets executed and the variable chromewebdriverbin is never assigned any value.
In this circumstance, when you refer to chromewebdriverbin in the line:
cls.driver = webdriver.Chrome(executable_path=chromewebdriverbin)
The above mentioned error is raised.
Reason
The most probable reason is, the environment variable CHROMEWEBDRIVER isn't set on the failing machine.

Fixed by adding chromedriver in local machine :
def setUp(cls):
if os.getenv('CHROMEWEBDRIVER'):
chromewebdriverbin = os.getenv('CHROMEWEBDRIVER')
else:
chromewebdriverbin = '/usr/bin/chromedriver'
cls.driver = webdriver.Chrome(
executable_path=chromewebdriverbin)

Related

undefined variable 'driver' / don't create new chrome instance

I am trying to call a click function, lastly in my /main.py file.
/main.py
"""Start Point"""
from data.find_pending_records import FindPendingRecords
from vital.vital_entry import VitalEntry
import sys
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import pandas as pd
if __name__ == "__main__":
try:
# for PENDING_RECORDS in FindPendingRecords().get_excel_data(): begin to loop through entire directory
PENDING_RECORDS = FindPendingRecords().get_excel_data()
# Do operations on PENDING_RECORDS
# Reads excel to map data from excel to vital
MAP_DATA = FindPendingRecords().get_mapping_data()
# Configures Driver
VITAL_ENTRY = VitalEntry()
# Start chrome and navigate to vital website
VITAL_ENTRY.instantiate_chrome()
# Begin processing Records
VITAL_ENTRY.process_records(PENDING_RECORDS, MAP_DATA)
# Save Record
VITAL_ENTRY.save_contact(driver)
print (PENDING_RECORDS)
print("All done")
except Exception as exc:
# print(exc)
raise
/vital_entry.py
class VitalEntry:
"""Vital Entry"""
def save_contact (self, driver):
driver.implicitly_wait(15)
driver.find_element_by_css_selector("#publishButton").click()
I am continuously getting this error in Prompt:
Traceback (most recent call last):
File "main.py", line 32, in <module>
VITAL_ENTRY.save_contact(driver)
NameError: name 'driver' is not defined
I do not want to create a new chrome session or window... I've also tried chaining this on my VITAL_ENTRY.process_records(PENDING_RECORDS, MAP_DATA) above. As you can see I am already importing the driver; and I am using it in the above calls - I don't want to create a new browser instance.
Here is the .instantiate_chrome() below:
def instantiate_chrome(self):
"""Create Chrome webdriver instance."""
self.options.headless = config.HEADLESS
if not self.options.headless:
self.options.add_argument("--start-maximized")
self.options.add_argument('--disable-infobars')
self.options.add_argument('--disable-gpu')
self.driver = webdriver.Chrome(options=self.options)
self.driver.set_page_load_timeout(30)
self.driver.implicitly_wait(15)
self.driver.get(config.VITAL_URL)
So you create the browser session, then you never pass it out of that function. If you want to use it elsewhere, your instantiate_chrome() code will need to return driver, then you'll need to assign it as I stated in my previous comment
driver= VITAL_ENTRY.instantiate_chrome()

Python Selenium Geckodrive

Hey there just trying a basic browser launch using Firefox.
I've tried using executable path, if statement, and without an if statement and the browser will still not open. I've checked the shell and I don't have an error.My best guess is I'm missing an action of some sort I just need someone to point my in the right direction using my current code, thank you.
from selenium import webdriver
class testbot():
def botfox(self):
driver = self.driver = webdriver.firfox(geckodriver)
driver.get("https://wwww.google.com")
if __name__ == "__botfox__":
botfox()
ok, try this :)
from selenium import webdriver
class testbot():
def botfox(self):
self.driver = webdriver.Firefox()
self.driver.get("https://wwww.google.com")
if __name__ == '__main__':
testBotInstace = testbot()
testBotInstace.botfox()
I'd be surprised if that worked. Have you tried calling it via testbot().botfox() ?
webdriver.firfox would not work, as the syntax is webdriver.Firefox
webdriver.firfox(geckodriver) would not work as geckodriver is not defined anywhere
botfox() would not work because there is no function defined as that. There is one inside of testbot but you would need to first instantiate the class and then call it via testbot().botfox()

UnboundLocalError: local variable .. referenced before assignment

I am starting with python. I am trying a very simple class-structure, but i get an error.
This is my script:
class controller:
def initLocal(self):
path = input('path:')
local = local()
local.path = path
return local
class location:
pass
class local(location):
path = None
controller = controller()
local = controller.initLocal()
And this is the result i get in the console:
path:a
Traceback (most recent call last):
File "path\to\test.py", line 21, in <module>
local = controller.initLocal();
File "path\to\test.py", line 5, in initLocal
local = local();
UnboundLocalError: local variable 'local' referenced before assignment
I searched for this error, and found it usually has to do something with uncorrect scopes. I however do not see what i am doing wrong here. Is it 'illegal' to have a class instance with the same name as the class?
If i change the initLocal() method to this:
def initLocal(self):
path = input('path:')
locale = local()
locale.path = path
return locale
It works, but i cannot find out why, since controller = controller() does not cause any problems.
Can somebody tell me what i am doing wrong? I have the feeling it might be something really obvious, but i cannot figure out what it is.
class Location:
pass
class Local(location):
path = None
class Controller:
def initLocal(self):
path = raw_input('path:')
local = Local()
local.path = path
return local
controller = Controller()
local = controller.initLocal()

Selenium2Library code completion in PyCharm

I'm experimenting with creating a basic library extension for Robot Framework using Python, and I'm using PyCharm as the editor. For libraries imported directly code completion is working fine, but in this case I'm importing the Selenium2Library indirectly via a method:
def get_current_browser():
browser = BuiltIn().get_library_instance('Selenium2Library')._current_browser()
return browser
Which I call from other methods with something like
driver = get_current_browser()
This successfully grabs the webdriver browser instance from Robot Framework and lets me do as I please, but I don't get code hints when I go to edit a 'driver' variable. Is there way I can get hints in this scenario?
Here's the code in full:
from robot.libraries.BuiltIn import BuiltIn
from Selenium2Library.keywords.keywordgroup import KeywordGroup
import logging
def get_current_browser():
browser = BuiltIn().get_library_instance('Selenium2Library')._current_browser()
return browser
class MyLibrary(KeywordGroup):
def get_title_via_python(self):
driver = get_current_browser()
title = driver.title
logging.warn("checking title %s" % title)
return title
Try adding a docstring to your function to help PyCharm.
from selenium.webdriver import Remote # Remote imported only for code completion
def get_current_browser():
"""
:rtype: Remote
"""
browser = BuiltIn().get_library_instance('Selenium2Library')._current_browser()
return browser
More at http://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html

Python variable assigned by an outside module is accessible for printing but not for assignment in the target module

I have two files, one is in the webroot, and another is a bootstrap located one folder above the web root (this is CGI programming by the way).
The index file in the web root imports the bootstrap and assigns a variable to it, then calls a a function to initialize the application. Everything up to here works as expected.
Now, in the bootstrap file I can print the variable, but when I try to assign a value to the variable an error is thrown. If you take away the assignment statement no errors are thrown.
I'm really curious about how the scoping works in this situation. I can print the variable, but I can't asign to it. This is on Python 3.
index.py
# Import modules
import sys
import cgitb;
# Enable error reporting
cgitb.enable()
#cgitb.enable(display=0, logdir="/tmp")
# Add the application root to the include path
sys.path.append('path')
# Include the bootstrap
import bootstrap
bootstrap.VAR = 'testVar'
bootstrap.initialize()
bootstrap.py
def initialize():
print('Content-type: text/html\n\n')
print(VAR)
VAR = 'h'
print(VAR)
Thanks.
Edit: The error message
UnboundLocalError: local variable 'VAR' referenced before assignment
args = ("local variable 'VAR' referenced before assignment",)
with_traceback = <built-in method with_traceback of UnboundLocalError object at 0x00C6ACC0>
try this:
def initialize():
global VAR
print('Content-type: text/html\n\n')
print(VAR)
VAR = 'h'
print(VAR)
Without 'global VAR' python want to use local variable VAR and give you "UnboundLocalError: local variable 'VAR' referenced before assignment"
Don't declare it global, pass it instead and return it if you need to have a new value, like this:
def initialize(a):
print('Content-type: text/html\n\n')
print a
return 'h'
----
import bootstrap
b = bootstrap.initialize('testVar')

Categories

Resources