fixture 'self' not found - python

I'm new with Pytest-bdd. I'm trying to run a BDD test but I find always the same problem with the fixture. This is my code.I've tried without the #pytest.fixture and with only the step of #given gherkin step I get same result. fixture 'self'not found
import os
from appium import webdriver
from time import sleep
import pytest
from pytest_bdd import scenario, given, when, then, parsers
#pytest.fixture(autouse=True, scope='module')
def Setup (self):
"Setup for the test"
desired_caps = {}
self.driver = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
def Teardown():
self.driver.quit()
#scenario('features.feature','Prueba1')
#given('step 1')
def test_single_player_mode(self):
element1=self.driver.find_element_by_id("com.nestle.bagzielicious.beta:id/on_button_vegan")
element1.click()
sleep(1)

Usually those methods are all inside a class and then self refers to the class.
For example:
from unittest import TestCase
class DriverTestCase(TestCase):

Give the following code a try using Pytest:
import os
from appium import webdriver
from time import sleep
import pytest
from pytest_bdd import scenario, given, when, then, parsers
#pytest.fixture(autouse=True, scope='module')
def driver():
"Setup for the test"
desired_caps = {}
driver = webdriver.Remote('http://0.0.0.0:4723/wd/hub', desired_caps)
yield driver
driver.quit()
#scenario('features.feature','Prueba1')
#given('step 1')
def test_single_player_mode(driver):
element1=driver.find_element_by_id("com.nestle.bagzielicious.beta:id/on_button_vegan")
element1.click()
sleep(1)

Related

Even after executing the code successfully pytest says empty suite and is not printing the print statements

I am trying to run one method from a different module in pytest using import. It runs correctly but in the report it says empty suite. Its not printing the print statements.
roboForm.py -
import unittest
from selenium import webdriver
from selenium.webdriver.support.select import Select
class Roboform(unittest.TestCase):
def setUp(self):
# create a new Chrome session
self.driver = webdriver.Chrome()
self.driver.implicitly_wait(10)
self.driver.maximize_window()
self.driver.get("https://www.roboform.com/filling-tests")
def click_Custom_Form(self):
# get the xpath of the link and page
title = self.driver.title
assert title== "RoboForm Form Filling Tests"
print("We are on the right page")
#click on custom form link
self.custom_form = self.driver.find_element_by_xpath("//*[contains(text(),'Custom')]").click()
def close_browser(self):
self.driver.quit()
I am running the below code in pytest - test_classB.py
import self as self
from roboForm import Roboform
class Test():
Roboform.setUp(self)
print ("Browser and page launched from RoboForm")
self.driver.find_element_by_xpath("//*[contains(text(),'Custom')]").click()
print ("Test Passed")
Roboform.close_browser(self)
Getting the below error :
======================== no tests ran in 11.53 seconds ========================
Process finished with exit code 0
Empty suite
Empty suite
Agreed with #Corey Goldberg.
Try
def test_click_Custom_Form(self):
instead
def click_Custom_Form(self):

Quit driver instance in pytest after all the tests are executed

Below is the pytest class used to run 2 tests. Want to quit driver after both the tests are executed. used Teardown but it quits the driver after each test execution is completed
class FlightTest(unittest.TestCase):
driver = webdriver.Chrome(direct_path+'/resources/chromedriver.exe')
startup = StartUpPage(driver)
register = RegisterPage(driver)
def test_flight_registration(self):
dat = self.json_reader.read_from_file("testdata.json")
self.startup.navigate_to_url(dat['url'])\
.click_on_register_button()
self.register.create_user(dat['uid'], dat['pwd'], dat['con_pwd'])
def test_flight_sign_in(self,):
dat = self.json_reader.read_from_file("testdata.json")
self.startup.click_sign_in_link()
def tearDown(self):
self.driver.quit()
In unittest terms, you would need to use the setUpClass and tearDownClass class methods:
class FlightTest(unittest.TestCase):
#classmethod
def setUpClass(cls)
cls.driver = webdriver.Chrome()
cls.startup = StartUpPage(driver)
cls.register = RegisterPage(driver)
#classmethod
def tearDownClass(cls):
cls.driver.quit()
...
In pytest terms, you would create a class-scoped fixture:
import pytest
#pytest.fixture(scope="class")
def driver(request):
# code before 'yield' is executed before the tests
request.cls.driver = webdriver.Chrome()
request.cls.startup = StartUpPage(request.cls.driver)
request.cls.register = RegisterPage(request.cls.driver)
yield
# code after 'yield' is executed after the tests
request.cls.driver.quit()
#pytest.mark.usefixtures('driver')
class FlightTest(unittest.TestCase):
def test_spam(self):
self.driver.get('https://www.google.de')
def test_eggs(self):
self.driver.get('https://www.facebook.com')
An even better solution would be using the context manager property of the webdriver so it is automatically closed no matter what:
import pytest
#pytest.fixture(scope="class")
def driver(request):
with webdriver.Chrome() as driver:
request.cls.driver = driver
request.cls.startup = StartUpPage(driver)
request.cls.register = RegisterPage(driver)
yield
#pytest.mark.usefixtures('driver')
class FlightTest(unittest.TestCase):
def test_spam(self):
self.driver.get('https://www.google.de')
def test_eggs(self):
self.driver.get('https://www.facebook.com')

How to pass an url as argument through commandline to run selenium python test cases

Is there any proper way to using getting url in cmd as argument along testcases.py file?
I am running below commmand in cmd to run test cases of python file:
testcases.py "any url"
testcases.py have coding:
class JSAlertCheck(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome("E:\chromedriver.exe")
self.url = sys.argv[1]
def test_Case1(self):
driver = self.driver
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main(sys.argv[1])
As per the discussion Python unittest passing arguments the Python Pundits seems to convey that:
Unit tests should be stand-alone which will have no dependencies outside of their setUp() and tearDown() methods. This is to make sure that each tests has minimal side-effects and reactions to the other test. Passing in a parameter defeats this property of unittest and thus makes them sort of invalid. Using a Test Configuration would have been the easiest way and more appropiate as a unittest should never rely on foreign data to perform the test.
If you still want to do so, here is one of the working solution:
Code Block:
from selenium import webdriver
import unittest
import sys
class MyTest(unittest.TestCase):
URL = "foo"
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver = self.driver
driver.get(self.URL)
def test_Case1(self):
driver = self.driver
print(driver.title)
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
if len(sys.argv) > 1:
MyTest.URL = sys.argv.pop()
unittest.main()
CLI Command:
python unittest_cmdline_urlASarguments.py http://www.python.org
Output:
C:\Users\AtechM_03\LearnAutmation\PythonProject\readthedocs>python unittest_cmdline_urlASarguments.py http://www.python.org
[4448:5632:0606/205445.017:ERROR:install_util.cc(589)] Unable to create registry key HKLM\SOFTWARE\Policies\Google\Chrome for reading result=2
DevTools listening on ws://127.0.0.1:5634/devtools/browser/40cc6c16-1e52-4f49-a54f-08fac3ff7abc
Welcome to Python.org
.
----------------------------------------------------------------------
Ran 1 test in 9.534s
OK
C:\Users\AtechM_03\LearnAutmation\PythonProject\readthedocs>
Commandline Snapshot:

Trouble getting python selenium tests to run

I am creating an automation framework from scratch using selenium with python and would really like some input and advice on the best way to do so.
So far I have the following but my test script will not run. Please help!
script.py
from selenium import webdriver
class WebDriver(object):
def __init__(self, driver=None):
"""
__init__ setup webdriver test script class
"""
self.driver = driver
def setup(self):
self.driver = webdriver.Chrome()
def teardown(self):
self.driver.quit()
test.py
import script
class Test(script.WebDriver):
def search(self):
self.driver.get("www.google.com")
self.driver.find_element_by_id("lst-ib").clear()
I'm assuming you are trying to run this with python unittest. If so, your class should inherit from unittest.TestCase in order to mark that it contains test cases:
class WebDriver(unittest.TestCase)
...
class Test(script.WebDriver)
And second missing piece is "boiler plate code to run the test suite" (see explanation here) in test.py:
if __name__ == "__main__":
test.main()

Browser instantiating twice when using Selenium/Python/Nose

I'm creating a sample test using Selenium and the python bindings and running it with nose. I know I'm doing something wrong because the test opens two browsers (when setup is run, a Firefox window opens up and closes immediately, and then when the test runs driver.get, another window opens). I have the following project:
/test_project
/config
config.ini
/pages
__init__.py
test_page.py
/test_scripts
script.py
__init__.py
base.py
config_parser.py
config.ini:
[Selenium]
browser: firefox
base_url: http://www.google.com/
chromedriver_path:
base.py
from selenium import webdriver
from config_parser import Config
class TestCase(object):
def setup(self):
self.config = Config()
if self.config.read_config('Selenium', 'browser').lower() == 'firefox':
self.driver = webdriver.Firefox()
elif self.config.read_config('Selenium', 'browser').lower() == 'chrome':
self.driver = webdriver.Chrome(self.config.read_config('Selenium', 'chromedriver_path'))
def teardown(self):
self.driver.quit()
test_page.py
from config_parser import Config
class TestPage(object):
def __init__(self, driver):
self.driver = driver
self.config = Config()
def open(self):
self.driver.get(self.config.read_config('Selenium', 'base_url'))
import time
time.sleep(3)
script.py
from pages import test
from base import TestCase
class RandomTest(TestCase):
def test_foo(self):
x = test.TestPage(self.driver)
x.open()
assert 1 == 1
Can someone help me understand why two browser windows are opening and what I can do to correct this issue?
Thank you in advance.
This is because your base TestCase class is being recognized by nose test runner as a test too.
Mark it with #nottest decorator:
from selenium import webdriver
from config_parser import Config
from nose.tools import nottest
#nottest
class TestCase(object):
...

Categories