1 year ago

#389156

test-img

Arthur

Django test - global variable from another script is not defined

I've been trying to run a second script from within the main one called by django's manage.py test. However, I'm getting this error:

File "<string>", line 254, in <module>
File "<string>", line 61, in login
NameError: name 'driver' is not defined

First, the test.py that runs during the manage.py test:

import sys
from django.contrib.staticfiles.testing import StaticLiveServerTestCase

#https://docs.djangoproject.com/en/3.1/topics/testing/tools/#testcase
#LiveServerTestCase

class TestReunioes(StaticLiveServerTestCase):        
    fixtures = ['fix_core.json','users.json']

    def testRun(self):
        exec(open("seleniumtest.py").read())

And the second script, seleniumtest.py:

import traceback
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys

url = "http://localhost:3000"

chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-gpu")
driver = webdriver.Chrome(options=chrome_options)
driver.get(url)
driver.set_window_size(1700, 850)
driver.implicitly_wait(20)

def login():
    user="teste"
    passwd="321"
    driver.find_element(By.NAME, "user").send_keys(user) #line 61 from the error
    driver.find_element(By.NAME, "passwd").send_keys(passwd)
    driver.find_element(By.NAME, "enter").click()
#
# Several other functions to test other parts
#
try:
    print("Starting test")
    login() #line 254 from the error
except:
    traceback.print_exc()
finally:
    driver.quit()

It's confusing me because if I run the seleniumtest.py from the command line, it works fine. It also works fine when called from a python file that is literally just the exec(open("seleniumtest.py").read()) . The error is only happening when called from the django test.

I know it's something about attribute/variable scope, but I don't know why this is happening, nor how to solve it.

python

django

0 Answers

Your Answer

Accepted video resources