在我的条件下,我正在尝试为变量名称分配一个新值,但我收到的错误如下。
运行我的代码后,我得到了UnboundLocalError: local variable 'name' referenced before assignment
你有想法解决它吗?
如果变量是全局的
,我不知道为什么我会得到这个我的代码
import pytest
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from faker import Faker
fake = Faker("en_US")
name = fake.name()
def create_contributor_minimum_requirements(driver):
driver.find_element_by_css_selector(".btn.btn--primary").click()
WebDriverWait(driver, 30).until(
EC.visibility_of_element_located((By.XPATH, ".//*[@id='first-name']/input")))
driver.find_element_by_xpath(".//*[@id='first-name']/input").send_keys(contributor_name)
assert driver.find_element_by_css_selector(".actions-bar__nav-link.router-link-active").text == name
time.sleep(3)
duplicated_contributor_message = driver.find_element_by_css_selector(".field-error-text")
if duplicated_contributor_message.is_displayed():
name = fake.name() + fake.name()
driver.find_element_by_xpath(".//*[@id='first-name']/input").clear()
driver.find_element_by_xpath(".//*[@id='first-name']/input").send_keys(name)
driver.find_element_by_css_selector(".btn.save-button.btn--disabled-dark.btn--critical").click()
WebDriverWait(driver, 30).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, ".btn.save-button.btn--disabled-dark.btn--disabled")))
assert driver.find_element_by_css_selector(".btn.save-button.btn--disabled-dark.btn--disabled").is_enabled() == False
def search_created_contributor(driver):
driver.find_element_by_css_selector(".navbar__menu__item.navbar__menu__item--search").click()
WebDriverWait(driver, 30).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, ".search__input")))
driver.find_element_by_css_selector(".search__input").send_keys(name)
WebDriverWait(driver, 30).until(
EC.visibility_of_element_located((By.CSS_SELECTOR, ".search__results__list>li")))
def assert_created_contributor_is_found(driver):
assert name in driver.find_element_by_css_selector(".search__results__list>li").text
def test_case_one(driver):
login_to_cms(driver)
access_contributor_page(driver)
create_contributor_minimum_requirements(driver)
search_created_contributor(driver)
assert_created_contributor_is_found(driver)
答案 0 :(得分:1)
功能有自己的范围。要访问全局变量,您需要明确说出:
def create_contributor_minimum_requirements(driver):
global name
...
希望它有所帮助!