'Python Global Variable Not Defined - Declared inside Class
I've seen a lot of questions on global variables, but for some reason I still can't get mine to work.
Here is my scenario - I have my individual test cases and a separate python script that includes different functions for the various error messages you can get in the application I'm testing. If one of the validations fails, I want the function to increment a failure variable and then the main test script will check to see if it's a pass or fail.
class ErrorValidations:
failures = 0
def CheckforError1(driver):
global failures
try:
if error1.is_displayed():
failures += 1
def CheckforError2(driver):
global failures
try:
if error2.is_displayed():
failures += 1
def CheckforError3(driver):
global failures
try:
if error3.is_displayed():
failures += 1
This is a heavily edited example of where the validations get used:
from functionslist import ErrorValidations
def test(driver, browser, test_state):
_modules = driver.find_elements_by_xpath('//div[@class="navlink"]')
for i in _modules:
i.click()
ErrorValidations.CheckforError1(driver)
ErrorValidations.CheckforError2(driver)
ErrorValidations.CheckforError3(driver)
if ErrorValidations.failures > 0:
driver.report.AppendToReport( i.text, "The " + i.text + "page was not able to load without errors.", "fail", "")
else:
driver.report.AppendToReport( i.text, "The " + i.text + "page was able to load without errors.", "pass", "")
The test is not properly incrementing the failures variable and I get the error: name 'failures' is not defined, but I'm not sure where else to define it.
Solution 1:[1]
You're declaring a class attribute 'failures', not a global, within the ErrorValidations
Instead of using global failures try:
class ErrorValidations:
failures = 0
def CheckforError1(driver):
try:
if error1.is_displayed():
ErrorValidations.failures += 1
A true global would be declared outside of the class
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | gibbonofdoom |