Selenium behave error>> AttributeError: module 'selenium.webdriver' has no attribute 'find_element' - selenium-webdriver

I am unable to resolve this issue by following below answers
Selenium - Python - AttributeError: 'WebDriver' object has no attribute 'find_element_by_name'
I am using python behave with selenium webdriver in updated current version, feature file image attached & below is step file code.
import time
from behave import *
from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
# access on described PDP
#given('I am on bundle item page named as Nestor Occasional Table Set')
def step_impl(context):
context.driver = webdriver.Chrome(ChromeDriverManager().install())
context.driver.maximize_window() # for maximise windows
time.sleep(2)
context.driver.get(
"Project name removed myself")
time.sleep(2)
#then('Verify the bundle Product sku')
def step_impl(context):
prod_sku = context.driver.find_element(By.XPATH, "//div[#class='product-id' and #aria-label='ASL-T517-0-ROOM']")
# print(prod_sku)
displayed = prod_sku.is_displayed()
print(displayed)
time.sleep(5)
# if displayed is True:
# print('product sku is visible on the screen because displayed value is', displayed)
# else:
# print('product sku is not visible on the screen because displayed value is', displayed)
# time.sleep(0.5)
#then('Verify the bundle Product price')
def step_impl(context):
prod_price = context.driver.find_element(By.XPATH, "//span[#class='price-label' and #aria-label='Final Price']")
# price_view = prod_price.is_displayed()
# print(price_view)
assert prod_price.text == "$540.00"
time.sleep(0.5)
#when('I click on ADD TO CART button to add bundle product in to the cart')
def step_impl(context):
context.driver.find_element(By.XPATH, "//button[#class='button-basic theme-button btn-block']").click()
time.sleep(7)
#then('Verify the added bundle Product in to the cart')
def step_imp(context):
# added_product = context.driver.find_element_by_link_text('Bostwick Shoals Queen Panel Bed')
added_product = context.driver.find_element(By.XPATH, "//div[#id='cart-prodname' and #class='pr-0']")
prod_viewed = added_product.is_displayed()
print(prod_viewed)
time.sleep(1)
#then('Verify the added bundle Product price in to the cart')
def step_impl(context):
# price = context.driver.find_element_by_link_text('$2699.00')
# price = context.driver.find_element_by_xpath("//span[#class='price-label' and #aria-label='Final Price']")
price = context.driver.find_element(By.XPATH, "//div[#class='detail-type text-lg-right col-sm-4']")
# price_view = prod_price.is_displayed()
# print(price_view)
assert price.text == "$540.00 Free Home Delivery*"
assert price.text == "Free Home Delivery*"
time.sleep(1)

Related

Unable to perform action chains with Appium Python Client

I have spent much time to find a way to perform right click with appium python client on a application in windows platform. Unfortunately, I get the following exception:
selenium.common.exceptions.WebDriverException: Message: Currently only pen and touch pointer input source types are supported
My code is in the following lines:
import unittest
from typing import List, Optional, Tuple, TypeVar
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
class SimpleCalculatorTests(unittest.TestCase):
#classmethod
def setUpClass(self):
# set up appium
desired_caps = {}
desired_caps["app"] = "Root"
desired_caps["deviceName"] = "WindowsPC"
desired_caps["platformName"] = "Windows"
self.driver = webdriver.Remote(
command_executor='http://127.0.0.1:4723/wd/hub',
desired_capabilities=desired_caps)
#classmethod
def tearDownClass(self):
self.driver.quit()
def test_initialize(self):
communation_object = self.driver.find_element(By.XPATH, "/Pane[#ClassName=\"#32769\"][#Name=\"Desktop 1\"]/Window[#Name=\"ETS5™ - Neues Projekt\"][#AutomationId=\"windowApplication\"]/Custom[#AutomationId=\"eTS4UC\"]/Custom[#ClassName=\"Workspace\"]/Custom[#ClassName=\"ContentPanelContainer\"]/Custom[#AutomationId=\"Control\"]/Custom[#ClassName=\"ActiveComObjectDetailView\"]/DataGrid[#ClassName=\"DataGrid\"]/DataItem[#ClassName=\"DataGridRow\"][#Name=\"21: Ventilausgang 1 (Bezeichnung) - Eingang - Stellgröße\"]/Custom[#ClassName=\"DataGridCell\"][#Name=\"Ventilausgang 1 (Bezeichnung) - Eingang\"]/Text[#ClassName=\"TextBlock\"][#Name=\"Ventilausgang 1 (Bezeichnung) - Eingang\"]")
actions = ActionChains(self.driver)
actions.context_click(communation_object)
actions.perform()
if __name__ == '__main__':
suite = unittest.TestLoader().loadTestsFromTestCase(SimpleCalculatorTests)
unittest.TextTestRunner(verbosity=2).run(suite)
Is there any alternative to perform right click?

Python webapp Google app engine: no module named six

The following code should take 2 dates from input.html and display months and years in output.html, but the Google app engine returns an error saying module six is missing, even though I have added all the site packages in my project library.
What am I doing wrong?
import webapp2
import jinja2
import os
import time
import datetime
import sys
from dateutil.rrule import rrule, MONTHLY
sys.path.append(os.path.join(os.path.dirname(__file__), "libs"))
template_dir = os.path.join(os.path.dirname(__file__), 'templates')
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
autoescape = True)
def render_str(template, **params):
t = jinja_env.get_template(template)
return t.render(params)
class MainHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
self.response.out.write(*a, **kw)
def render_str(self, template, **params):
return render_str(template, **params)
def render(self, template, **kw):
self.write(self.render_str(template, **kw))
def get(self):
self.render('input.html')
def post(self):
frmstring=self.request.get('from')
tostring=self.request.get('to')
frm=time.strptime(frms,"%Y-%m")
to=time.strptime(tos,"%Y-%m")
dates = [dt for dt in rrule(MONTHLY, dtstart=frm, until=to)]
months_choices = []
for i in range(1,13):
months_choices.append(datetime.date(2008, i, 1).strftime('%B'))
self.render('output.html',dates = dates,months_choices=months_choices)
app = webapp2.WSGIApplication([
('/', MainHandler)
], debug=True)
You need to vendor six into your environment.
Run
pip install -t lib six
Then add these lines to your apppengine_config.py file (or create it)
# appengine_config.py
from google.appengine.ext import vendor
# Add any libraries install in the "lib" folder.
vendor.add('lib')
See https://cloud.google.com/appengine/docs/standard/python/tools/using-libraries-python-27#installing_a_third-party_library for more details
The six module is not provided by the AppEngine environment. Have you included it in your lib/ directory?

Unittest Jinja2 and Webapp2 : template not found

I use Jinja2 with Webapp2 on a GAE project.
I have a base RequestHandler as describe in webapp2_extras.jinja2:
import webapp2
from webapp2_extras import jinja2
def jinja2_factory(app):
"""Set configuration environment for Jinja."""
config = {my config...}
j = jinja2.Jinja2(app, config=config)
return j
class BaseHandler(webapp2.RequestHandler):
#webapp2.cached_property
def jinja2(self):
# Returns a Jinja2 renderer cached in the app registry.
return jinja2.get_jinja2(factory=jinja2_factory, app=self.app)
def render_response(self, _template, **context):
# Renders a template and writes the result to the response.
rv = self.jinja2.render_template(_template, **context)
self.response.write(rv)
And a view handler as:
class MyHandler(BaseHandler):
def get(self):
context = {'message': 'Hello, world!'}
self.render_response('my_template.html', **context)
My templates are in the default location (templates).
The app works well on dev server, and the template is correctly rendered.
But when I try to unittest MyHandler with
import unittest
import webapp2
import webstest
class MyHandlerTest(unittest.TestCase):
def setUp(self):
application = webapp2.WSGIApplication([('/', MyHandler)])
self.testapp = webtest.TestApp(application)
def test_response(self):
response = application.get_response('/')
...
application.get_response('/my-view') raise an exception: TemplateNotFound: my_template.html.
Is there something I missed? Like a jinja2 environment or template loader configuration?
Problem origin:
Jinja2 default loader searches files in a relative ./templates/ directory. When you run your GAE application on the development server this path is relative to the root of your application. But when you run your unittests this path is relative to your unittest files.
Solution:
Not really an ideal solution, but here a trick I did to solve my problem.
I updated the jinja2 factory to add a dynamic template path, set in app config:
def jinja2_factory(app):
"""Set configuration environment for Jinja."""
config = {'template_path': app.config.get('templates_path', 'templates'),}
j = jinja2.Jinja2(app, config=config)
return j
And I set an absolute path to the templates in the setUp of my unittests:
class MyHandlerTest(unittest.TestCase):
def setUp(self):
# Set template path for loader
start = os.path.dirname(__file__)
rel_path = os.path.join(start, '../../templates') # Path to my template
abs_path = os.path.realpath(rel_path)
application.config.update({'templates_path': abs_path})

no such table -- django

I am using south, and I have syncdb but alas i get stuck with this database error, can you help me fix this and maybe tell me how to fix something like this in the future.
this missing database table error is comming up in a couple of different places dealing with something called salesflow_contact I have a folder salesflow with a models.py file with a class of Contact with a capitol,
the error shown is from trying to post some content to the table, but i also get an error with the pagination view browsecontacts
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/addacontact
Django Version: 1.4.2
Python Version: 2.7.3
Installed Applications:
('django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.admin',
'django.contrib.admindocs',
'south',
'sekizai')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/core/handlers/base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "/home/brian/projects/steprider/steprider/views.py" in Add_a_contact
36. new_contact = form.save(request.user)
File "/home/brian/projects/steprider/salesflow/forms.py" in save
23. contact.save()
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/base.py" in save
463. self.save_base(using=using, force_insert=force_insert, force_update=force_update)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/base.py" in save_base
551. result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/manager.py" in _insert
203. return insert_query(self.model, objs, fields, **kwargs)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in insert_query
1593. return query.get_compiler(using=using).execute_sql(return_id)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
909. for sql, params in self.as_sql():
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in as_sql
872. for obj in self.query.objs
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/django_extensions-0.9-py2.7.egg/django_extensions/db/fields/__init__.py" in pre_save
135. value = unicode(self.create_slug(model_instance, add))
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/django_extensions-0.9-py2.7.egg/django_extensions/db/fields/__init__.py" in create_slug
122. while not slug or queryset.filter(**kwargs):
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in __nonzero__
130. iter(self).next()
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in _result_iter
118. self._fill_cache()
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in _fill_cache
892. self._result_cache.append(self._iter.next())
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/query.py" in iterator
291. for row in compiler.results_iter():
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in results_iter
763. for rows in self.execute_sql(MULTI):
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/models/sql/compiler.py" in execute_sql
818. cursor.execute(sql, params)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/backends/util.py" in execute
40. return self.cursor.execute(sql, params)
File "/home/brian/virt_env/virt_step/local/lib/python2.7/site-packages/Django-1.4.2-py2.7.egg/django/db/backends/sqlite3/base.py" in execute
344. return Database.Cursor.execute(self, query, params)
Exception Type: DatabaseError at /addacontact
Exception Value: no such table: salesflow_contact
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# steprider.salesflow.forms.py
#
# Copyright 2012 BRIAN SCOTT CARPENTER <KlanestroTalisman#gmail.com>
from django.forms import ModelForm
from salesflow import models
from django import forms
from django.template.defaultfilters import slugify
class ContactForm(ModelForm):
description = forms.CharField(widget=forms.Textarea)
class Meta:
model = models.Contact
exclude = ("user","slug")
def save(self, user):
contact = super(ContactForm, self).save(commit=False)
contact.user = user
contact.save()
return contact
class Contact_History_Form:
class Meta:
model = models.Contact_History
exclude = ("user","slug")
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# views.py
#
# Copyright 2012 BRIAN SCOTT CARPENTER <KlanestroTalisman#gmail.com>
from django.shortcuts import render_to_response,get_object_or_404
from django.template import RequestContext
from salesflow.forms import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from salesflow.models import Contact
def home (request):
""" This is the Home view"""
return render_to_response(('index.html') ,context_instance=RequestContext(request))
def server_error(request, template_name='templates/500.html'):
"""
500 error handler.
Templates: `500.html`
Context:
STATIC_URL
Path of static media (e.g. "media.example.org")
"""
t = loader.get_template(template_name)
return HttpResponseServerError(
t.render(Context({'STATIC_URL': settings.STATIC_URL})))
def Add_a_contact(request):
"""give them a page so they can donate and save it to a database."""
if request.method == 'POST':
form = ContactForm(request.POST,request.FILES)
if form.is_valid():
new_contact = form.save(request.user)
return HttpResponseRedirect(reverse(item, args=(new_contact.slug,)))
else:
form = ContactForm()
return render_to_response('salesflow/addacontact.html',{'form': form},context_instance=RequestContext(request))
def browse_contacts(request):
contact_list = Contact.objects.all()
paginator = Paginator(contact_list,15)
page = request.GET.get('page')
try:
contacts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
contacts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
contacts = paginator.page(paginator.num_pages)
return render_to_response('salesflow/browsecontacts.html',
{"contacts":contacts,
"site":settings.SITE_DOMAIN},
context_instance=RequestContext(request))
The error is pretty straight forward; you have no table called salesflow_contact.
You'd need to run migrate assuming it has the initial schemamigration salesflow --initial first table creation migration.
syncdb will not create tables for south-managed models, which is most likely your problem. You can bypass this with syncdb --all but if it's truly south-managed, you should run migrate salesflow and it should create the tables assuming you have the schemamigration salesflow --initial migration in there.

Web2py Google App Engine Testing

I'm building an GAE app with web2py and am struggling with setting up a test framework.
I've looked into:
web2py_utils
nosegae
Googler Ikai Lan's suggestions
gaetestbed which was merged into GAE apis
Here's a unit test I attempted:
import unittest
import nose
from nose.tools import *
from google.appengine.ext import testbed
from google.appengine.datastore import datastore_stub_itil
class UserModelTest(unittest.TestCase):
def setUp(self):
# First, create an instance of the Testbed class.
self.testbed = testbed.Testbed()
# Then activate the testbed, which prepares the service stubs for use.
self.testbed.activate()
# Initialize the datastore stub with this policy.
self.testbed.init_datastore_v3_stub(consistency_policy=self.policy)
self.env = new_env(app='fb', controller='default')
self.db = copy_db(self.env, db_name='db', db_link='sqlite:memory')
self.user = self.db.auth_user.insert(first_name='Bob', last_name='Narley', fb_id=1, password='testtest')
self.dream = self.db.dream.insert(title='Graduate UC Santa Cruz with Computer Science degree by June 8, 2012.',
type='education', owner = self.user, progress=92.0)
self.task1 = self.db.task.insert(dream=self.dream, title='Buy batteries for calculator', solution='Go to Walmart at 12:00pm October 30, 2012 and buy Duracell AAA.',
status=1)
self.task2 = self.db.task.insert(dream=self.dream, title='Make Winston happy',
solution='Make banana milk',
status=0)
self.user.update_record(tasks=[self.task1, self.task2])
def tearDown(self):
self.testbed.deactivate()
def test_create_user(self):
assert_equal('Bob', self.user.first_name)
assert_equal(1, self.user.fb_id)
assert_equal('testtest', self.user.password)
def test_user_has_many_tasks(self):
tasks = self.db(self.db.task.id.belongs(self.user.tasks)).select()
assert_equal(2, len(tasks))
run_fb_tests.py:
from web2py_utils.test_runner import run
import sys
run(path = sys.path[0],
app = 'fb',
test_key = 'superSecret',
test_options = {'verbosity': 3, 'with-gae': True, 'without-sandbox': True},
coverage_report = 'logs/coverage_report.txt',
DO_COVER = True,
DO_NOSE = True,)
I get the following error when execute my run_fb_tests.py
ImportError: No module named google.appengine.ext
I've been banging my head for days now with many errors. This is only one of many
How do you setup a testing framework in web2py for GAE apps?
Where is your script run_fb_tests.py? If it is in the web2py folder I get a similar error, but if you place it in google_appenine, or in the containing folder of the google_appengine then I get no import errors.

Resources