I currently am doing some automated testing via Appium and python for testing an Android application. I'd like to abstract away some of the details so the tests read easier.
Right now I have just have an entire class doing the testing. For example, I'd like to turn this:
# authentication
self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
username = self.driver.find_element_by_name('username')
password = self.driver.find_element_by_name('pw')
username.send_keys('some username')
password.send_keys('some password')
login_button = self.driver.find_element_by_name('Login')
login_button.click()
Into something like this:
Authentication.login(self.driver, 'largedata_lgabriel#hmbnet.com', 'R3DruM24')
Where our Authentication class might look like this:
class Authentication:
def login(driver, username, password):
input_username = driver.find_element_by_name('username')
input_password = driver.find_element_by_name('pw')
input_username.send_keys(username)
input_password.send_keys(password)
login_button = driver.find_element_by_name('Login')
login_button.click()
This would require creating an 'Authentication' class, but I'm unsure how to import these methods into my main testing class, and how to share the web driver object.
Here's how I structure this kind of thing. I also use unittest.TestCase which I want to highly recommend for any python automation; it'll allow you to lean on setUpClass, tearDownClass (one-time for all the derivative tests), and setUp, tearDown (before each test function) to do a lot of the set up and tear down stuff you need to do.
For my iOS-specific Appium tests:
Base file: ios_base.py
class iOSBase(unittest.TestCase):
#classmethod
def setUpClass(self):
# Set up logging if you want it
# Set up the XCode and iOS Simulator details you need if you're doing iOS
# Set up Appium
def setUp(self):
# Per test, I like to log the start of each test
self.log.info("--- {0} ---".format(self._testMethodName))
# etc. on setUp / tearDown stuff, whatever you need
# Helpful function like you have in mind
def login(self, username, password):
# You'll get self.driver for free by using setUpClass, yea!
Test file(s): test_login.py
from ios_base import iOSBase
class iOSLoginTests(iOSBase):
# Add any additional login-specific setUp you might want here, see also super()
def test_valid_login(self):
self.login(good_username, good_password)
def test_login_invalid_username(self):
self.login(bad_username, good_password)
# etc.
Related
I have a following simplified code example:
from urllib.parse import urlparse, parse_qs
from selenium import webdriver
import pytest
#pytest.fixture(scope="module")
def driver():
options = webdriver.ChromeOptions()
_driver = webdriver.Chrome(options=options)
yield _driver
_driver.close()
#pytest.mark.parametrize("instance_name", ["instance1", "instance2"])
class TestInstance:
#pytest.fixture
def authorization_code(self, instance_name, driver):
driver.get(f"https://{instance_name}.com")
...do some UI actions here
authorization_code = parse_qs(urlparse(redirected_url).query)["code"][0]
#pytest.fixture
def access_token(self, authorization_code):
...obtain access_token here using authorization code
return "access_token"
def test_case_1(self, access_token):
...do some API calls using access_token
def test_case_2(self, access_token):
...do some API calls using access_token
What I would like to do is to execute UI actions in the authorization_code function once and obtain one access_token per instance.
Currently my UI actions are executed for every test case, leading to the fact that UI actions actually execute 2 * 2 = 4 times.
Is it possible to do with pytest?
Or maybe I am missing something in my setup?
In general I would just change the fixture scope: currently it gets recreated every time it is called, hence the reuse of ui actions. This is by design to ensure fixtures are clean. If your fixture didn't depend on the function-level fixture instance you could just put scope="class". (See the docs on scopes).
In this case I'd be tempted to handle the caching myself:
import pytest
from datetime import datetime
#pytest.mark.parametrize("instance", ("instance1", "instance2"))
class TestClass:
#pytest.fixture()
def authcode(self, instance, authcodes={}, which=[0]):
if not instance in authcodes:
authcodes[
instance
] = f"authcode {which[0]} for {instance} at {datetime.now()}"
which[0] += 1
return authcodes[instance]
def test1(self, authcode):
print(authcode)
def test2(self, authcode):
print(authcode)
(which is just used to prove that we don't regenerate the fixture).
This feels inelegant and I'm open to better ways of doing it.
I'm trying to create a test suite with pytest and Selenium using Page Object Models for pattern designing. For using my page classes on my tests, I just imported them inside my TestClass __init__ method, since they need to instanced with a driver.
I know that, by default, pytest ignores classes with an __init__ method. I also know, by reading here that it's possible to configure where pytest collects tests. Is it also possible to make it consider class tests with __init__, instead of returning an "Empty Suite" error?
#pytest.fixture(scope="session")
def driver_init(request):
from selenium import webdriver
driver = webdriver.Chrome()
session = request.node
page = PageFunctions(driver)
login_page = LoginPage(driver)
registration_page = RegistrationPage(driver)
for item in session.items:
cls = item.getparent(pytest.Class)
setattr(cls.obj, "driver", driver)
setattr(cls.obj, "page", page)
setattr(cls.obj, "login", login_page)
setattr(cls.obj, "registration", registration_page)
Pytest and Unittest have some different conventions. Mixing the two in the same test function is usually worth avoiding.
If you're working exclusively with Pytest, you would pass in your fixtures as arguments to your test function, e.g.:
import pytest
from selenium import webdriver
#pytest.fixture
def driver():
driver = webdriver.Chrome()
return driver
def test_func(driver):
# `driver` is found by pytest in the fixture above and
# automatically passed in
request = ... # Instantiate your request (not in your included code)
session = request.node
page = PageFunctions(driver)
login_page = LoginPage(driver)
registration_page = RegistrationPage(driver)
# Make some assertions about your data, e.g.:
assert page is not None
You haven't included all of the object definitions/imports so it's hard to see what you're trying to accomplish with the test, but hopefully that gives you an idea of the pytest conventions.
I currently have Python 3.7.3 with robotframework 3.1.1 and created a Python library (MySite.py) like this:
from selenium import webdriver
from collections import namedtuple
from HomePage import *
class Pages(object):
def __init__(self, handle):
self._pages = {}
self._home_window = handle
pass
#property
def home_window(self):
return self._home_window
#home_window.setter
def home_window(self, v):
self._home_window = v
#property
def homePage(self):
return self._pages['home']
def add(self, name, page):
self._pages[name] = page
def get(self, name):
return self._pages[name]
def getPages(self):
return self._pages
class MySite(object):
def __init__(self):
self._driver = None
#property
def driver(self):
return self._driver
#driver.setter
def driver(self, v):
self._driver = v
def close_all_windows(self):
# Close all windows
pages = self.pages.getPages()
for name, page in pages.items():
page.close()
def open_my_page(self):
self.driver = webdriver.Ie("IEDriverServer_Win32_3.141.0\\IEDriverServer.exe")
# Define pages
self.pages = Pages(self.driver.current_window_handle)
self.pages.add('home', HomePage(self.driver, self.pages))
# Open browser
self.driver.get(www.mypage.com)
# Code to wait to finish loading the page
When I create a Robot script to open and close the browser in one test case, it works:
*** Settings ***
Library MySite.py
*** Test Case ***
Open Browser to mypage.com and close browser
Open My Page
Close All Windows
But when I create a Robot script to open a browser in one test case and then on another test case to close it I get AttributeError: 'MySite' object has no attribute 'pages':
*** Settings ***
Library MySite.py
*** Test Case ***
Open Browser to mypage.com
Open My Page
Close Browser
Close All Windows
It seems like my instance variables are not being saved off for the second robot test. Do you know why this may be? Or what I am doing wrong?
By default, a new instance of the library is created for each test. You need to set the scope such that an instance of the class is created once for each suite or once for each test run.
This is mentioned in the user guide, in a section titled Test Library Scope:
Test libraries can control when new libraries are created with a class attribute ROBOT_LIBRARY_SCOPE. This attribute must be a string and it can have the following three values:
TEST CASE
A new instance is created for every test case. A possible suite setup and suite teardown share yet another instance. This is the default.
TEST SUITE
A new instance is created for every test suite. The lowest-level test suites, created from test case files and containing test cases, have instances of their own, and higher-level suites all get their own instances for their possible setups and teardowns.
GLOBAL
Only one instance is created during the whole test execution and it is shared by all test cases and test suites. Libraries created from modules are always global.
(emphasis mine)
To set the scope to "TEST SUITE" so that the instance is created only once for the whole suite, you would start your class definition like this:
class MySite(object):
ROBOT_LIBRARY_SCOPE = 'TEST SUITE'
Programing is a new thing for me and probably I am missing something obvious.
I would like to create a separate file and class for setup my webdriver for Appium tests, but I got errors like:
in test_login main_page = MainPage(self.driver)
AttributeError: 'test_Login_iOS' object has no attribute 'driver'
Currently I have two files: one with test case and other with methods for test steps:
test_Login_iOS.py:
class test_Login_iOS(unittest.TestCase):
def setUp(self):
logging.info("WebDriver request initiated. Waiting for response, this may take a while.")
# choose desired capabilities from desired_capabilities.py
desired_capabilities = DesiredCapabilities.desired_capabilities_for_iOS_iPad
self.driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_capabilities)
self.driver.implicitly_wait(15) # seconds
def test_login(self):
logging.info("starting Test Case 1: login into active account")
welcome_page = WelcomePage(self.driver)
welcome_page.click_login_button()
login_page = LoginPage(self.driver)
and second file, page_ios.py:
class BasePage(unittest.TestCase):
"""
:type driver: appium.webdriver.Remote
"""
def __init__(self, driver):
super().__init__()
self.driver = driver
When I add new test case I have to add to it the same setUp method like in previous test case, so I would like to create a new class "Setup" that could be shared across multiple test cases.
Goal is to move setUp method to separate file and new class.
I have a class that I try to mock in tests. The class is located in server/cache.py and looks like:
class Storage(object):
def __init__(self, host, port):
# set up connection to a storage engine
def store_element(self, element, num_of_seconds):
# store something
def remove_element(self, element):
# remove something
This class is used in server/app.py similar to this one:
import cache
STORAGE = cache.Storage('host', 'port')
STORAGE.store_element(1, 5)
Now the problem arise when I try to mock it in the tests:
import unittest, mock
import server.app as application
class SomeTest(unittest.TestCase):
# part1
def setUp(self):
# part2
self.app = application.app.test_client()
This clearly does not work during the test, if I can't connect to a storage. So I have to mock it somehow by writing things in 'part1, part2'.
I tried to achieve it with
#mock.patch('server.app.cache') # part 1
mock.side_effect = ... # hoping to overwriting the init function to do nothing
But it still tries to connect to a real host. So how can I mock a full class here correctly? P.S. I reviewed many many questions which look similar to me, but in vain.