Run all unittests from seperate py file - python

I have multiple py files with unit tests specified for specific module.
I want to import these unittests to seperate py file and run them from there, but I have trouble getting it working.
example of one of the unittest:
from webdriver_manager.chrome import ChromeDriverManager
from to_import import acceptConsent, URL_poznavacky, URL_poznavacky_vikendy, URL_poznavacky_rodiny, URL_pobocky
import time
from selenium import webdriver
import unittest
class TestPobocky_D(unittest.TestCase):
def setup_method(self, method):
self.driver = webdriver.Chrome(ChromeDriverManager().install())
self.vars = {}
def teardown_method(self, method):
self.driver.quit()
def test_pobocky_D(self):
self.driver.get(URL_pobocky)
acceptConsent(self.driver)
self.driver.maximize_window()
time.sleep(2)
mapa = self.driver.find_element_by_xpath("//*[#class='leaflet-pane leaflet-tile-pane']") ## jen jeden element, no need to call find_elementS
mapaDisplayed = mapa.is_displayed()
assert mapaDisplayed == True
mapaKolecka = self.driver.find_elements_by_xpath("//*[#class='leaflet-marker-icon marker-cluster marker-cluster-medium leaflet-zoom-animated leaflet-interactive']")
y=0
for _ in mapaKolecka:
mapaKoleckaDisplayed = mapaKolecka[y].is_displayed()
y=y+1
print("mapa kolecka")
assert mapaKoleckaDisplayed == True
pobockaBoxiky = self.driver.find_elements_by_xpath("//*[#class='f_branch-header f_anchor']")
x=0
for _ in pobockaBoxiky:
pobockaBoxikyDisplay = pobockaBoxiky[x].is_displayed()
print("boxiky")
assert pobockaBoxikyDisplay == True
x=x+1
basicInfo = self.driver.find_elements_by_xpath("//*[#class='f_branch-basicInfo']")
a=0
for _ in basicInfo:
basicInfoDisplay = basicInfo[a].is_displayed()
print("basic info ")
assert basicInfoDisplay == True
a=a+1
I want to import the whole class TestPobocky_D to new file and run it in seperate py file. I tried following:
import unittest
from pobocky import TestPobocky_D
TestPobocky_D(unittest.TestCase)
that just gives me this error
"Traceback (most recent call last):
File "C:/Users/KDK/Desktop/Automation_Local_Deploy_PyCharm/starter_local.py", line 4, in <module>
TestPobocky_D(unittest.TestCase)
File "C:\Users\KDK\anaconda3\lib\unittest\case.py", line 433, in __init__
testMethod = getattr(self, methodName)
TypeError: getattr(): attribute name must be string"
Anyone who can help me with this please ? Or point me to the right direction how to go about this.
Thanks in advance for every response

Can you please try as below?
starttest.py
import unittest
from pobocky import TestPobocky_D
if __name__ == '__main__':
unittest.main(argv=[''],verbosity=2, exit=False)
Run the command "python -m unittest starttest.py"

Related

EC.presence_of_element_located(*element) failing (Python)

I am writing my first Python Selenium page factory and am getting an error regarding my waits.
My code is as follows
Basepage Class
class Basepage():
browser = None
def __init__(self, browser):
self.browser = browser
self.base_url = config.url
def wait_for_element(self, *element):
WebDriverWait(self.browser, 10).until(
EC.presence_of_element_located(*element)
)
def click_element(self, *element):
self.browser.find_element(*element).click()
def find_element(self, *element):
self.browser.find_element(*element)
CreatePage Class
class CreatePage(Basepage):
def isat_createpage(self):
self.wait_for_element(*CreatePageLocators.add_computer_title)
text = self.find_element(*CreatePageLocators.add_computer_title).text
if text == "Add a computer":
return True
else:
return False
Behave Step
#then('the user will be navigated to "Create_Computer" page')
def step_impl(context):
page = CreatePage(context.browser)
assert page.isat_createpage(), "not at ADD Computer page"
Locator I am using for the item
class CreatePageLocators:
add_computer_title = (By.XPATH, "//*[#id=\"main\"]/h1")
I am getting the error
Scenario: User can open Create Computer screen # features/UI_Tests/Create.feature:8
Given A user has navigated to the BB_Test_Webpage # steps/Backbase_common_steps.py:6
And add a new computer is clicked # steps/Backbase_common_steps.py:11
Then the user will be navigated to "Create_Computer" page # steps/web_create_steps.py:5
Traceback (most recent call last):
File "c:\users\richard.cariven\python\lib\site-packages\behave\model.py", line 1329, in run
match.run(runner.context)
File "c:\users\richard.cariven\python\lib\site-packages\behave\matchers.py", line 98, in run
self.func(context, *args, **kwargs)
File "steps\web_create_steps.py", line 8, in step_impl
assert page.isat_createpage(), "not at ADD Computer page"
File "C:\Users\richard.cariven\Documents\Backbase_Test_RC\modules\pages\createpage.py", line 15, in isat_createpage
self.wait_for_element(*CreatePageLocators.add_computer_title)
File "C:\Users\richard.cariven\Documents\Backbase_Test_RC\modules\pages\basepage.py", line 23, in wait_for_element
EC.presence_of_element_located(*element)
TypeError: __init__() takes 2 positional arguments but 3 were given
I imagine I am doing something very simple wrong. But help greatly appreciated
If you check the error it is mentioned about positional arguments.
EC.presence_of_element_located(*element)
TypeError: init() takes 2 positional arguments but 3 were given
Change the following inside function like that add one more parenthesis.
def wait_for_element(self, *element):
WebDriverWait(self.browser, 10).until(
EC.presence_of_element_located((By.XPATH, "//*[#id='main']/h1")))

Genetic Algorithm chromedriver snake

So I'm almost done completing a genetic algorithm for the snake game in python for this javascript snake game: http://patorjk.com/games/snake/
I've been getting an error for my code:
import selenium, os, urllib
from selenium import webdriver
import win32com.client as comctl
from random import randint
from operator import add
import time
import random
import lxml
from lxml import html
import requests
page=requests.get("http://patorjk.com/games/snake/")
tree=lxml.html.fromstring(page.content)
chromedriver="C:/Python34/Scripts/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
wsh = comctl.Dispatch("WScript.Shell")
wsh.AppActivate("patorjk.com/games/snake/")
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
driver.get('http://patorjk.com/games/snake/')
hidden_element = driver.find_element_by_id('sbTryAgain0')
def createIndividual(length, mintim, maxtim):
return [[random.uniform(mintim,maxtim) for x in range(length)],[randint(0,3) for x in range(length)],[]]
def changeInt(int1):
if(int1==0):
return '{UP}'
if(int1==1):
return '{RIGHT}'
if(int1==2):
return '{DOWN}'
if(int1==3):
return '{LEFT}'
def run(ind):
for x in range(len(ind[0])):
if hidden_element.is_displayed():
break
wsh.SendKeys(" ")
time.sleep(ind[0][x])
wsh.SendKeys(changeInt(ind[1][x]))
print(changeInt(ind[1][x]))
def indfit(time, pts):
tree=lxml.html.fromstring(page.content)
points=tree.xpath('//div[#class="snake-panel-component"]/text()')
for i in points:
if(points[i-1]==" " and points[i-2]==":"):
pts=int(points[i:len(points)-1])
#return (pts/time)
return pts
def createPopulation(size, length, mintim, maxtim):
population=[]
for x in range(size):
population.append(createIndividual(length, mintim, maxtim))
return population
def cyclePop(pop):
index1=0
for x in pop:
start_time=time.time()
pop1=pop[index1]
run(pop1)
pop[index1][2]=indfit(time.time()-start_time,1)
print("Fitness of individual ",(index1+1),": ",pop[index1][2])
wsh.SendKeys(" ")
index1+=1
print("Population Fitness: ",popFitScore(pop))
def popFitScore(pop):
sum1=0
for x in pop:
sum1+=x[2]
return sum1/len(pop)
def bubble_sort(items):
""" Implementation of bubble sort """
for i in range(len(items)):
for j in range(len(items)-1-i):
if items[j][2] > items[j+1][2]:
items[j], items[j+1] = items[j+1], items[j] # Swap!
def mixtraitscross(ind1,ind2):
index1=0
for i in ind1:
if index1%2==1:
ind1[index1]=ind2[index1]
index1+=1
def mixtraitsavg(ind1,ind2):
index1=0
for i in ind1:
if index1%2==1:
ind1[index1]=(ind1[index1]+ind2[index1])/2
index1+=1
def evolve(pop,mutrate,killpercent,sammin,sammax):
bubble_sort(pop)
startmutlen=(len(pop)-(killpercent*len(pop)))
mutrateind=mutrate*len(pop[0][0])
for ig in pop:
index1=pop.index(ig)
if index1>startmutlen:
for g in range(int(mutrateind)):
ig[0][randint(0,len(pop[0][0])-1)]=randint(0,3)
ig[1][randint(0,len(pop[0][0])-1)]=random.uniform(sammin,sammax)
else:
for iff in range(int(startmutlen-1)):
mixtraitscross(pop[index1][0],pop[index1+1][0])
mixtraitsavg(pop[index1][1],pop[index1+1][1])
#createPopulation(10, 20, 0, 5)
index8=0
while(index8<=50):
x=createPopulation(5,10,0,2)
cyclePop(x)
evolve(x,.30,.5,0,2)
index8+=1
so this is my code and i'm trying to make it so that if the element that says "You Died :(", it will stop running the individual and it will apply the time to the individual's fitness. I'm getting really confused with all of this chromedriver stuff with selenium and if I were able to get it to work, It would be perfect. the comment that says
#return (pts/time)
is what I want to be there, but until I am able to get the selenium working, the time is the same. I made it so that the time would be the same, but I want it so that it cuts off after it dies. Right now, I'm just having errors working with chromedriver, and I'm not exactly sure it's what I even want to be using. This is my error:
Traceback (most recent call last):
File "H:\Senior Year\CSAP2\Snakegenalg\SnakeJSGenAlg.py", line 27, in <module>
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\Application\chrome.exe')
File "C:\Users\lab301-user28\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 62, in __init__
self.service.start()
File "C:\Users\lab301-user28\AppData\Local\Continuum\Anaconda3\lib\site- packages\selenium\webdriver\common\service.py", line 86, in start
self.assert_process_still_running()
File "C:\Users\lab301-user28\AppData\Local\Continuum\Anaconda3\lib\site-packages\selenium\webdriver\common\service.py", line 99, in assert_process_still_running
% (self.path, return_code)
selenium.common.exceptions.WebDriverException: Message: Service C:\Program Files (x86)\Google\Chrome\Application\chrome.exe unexpectedly exited. Status code was: 0
Sorry if I'm really bad at coding and I'm getting bad at this simple stuff, I'm just in high school and learned python this month. I'm not using the shorthand for stuff right now because it confuses me, but I know my code is easy to follow

AttributeError: 'module' object has no attribute 'initialize'

# randomize.py
import os
import sys
import re
import shuti1
import json
import cProfile
import random
li = ["dog dot", "do don't", "dumb-dumb", "no match"]
for element in li:
m = re.match("(d\w+)\W(d\w+)", element)
if m:
print(m.groups())
for _, __ in enumerate(sys.path):
shuti1.initialize('Hello', '!', 'HackerEarth')
print __
while True:
li_random = random.choice(li)
print li_random
if li[0] in li_random:
break
# shuti1.py
import sys
import randomize
import collections
import math
from collections import Counter
class HackerEarth(object):
def __init__(self, name, role, hobby):
self.name = name
self.role = role
self.hobby = hobby
def print_details(self):
print "Name:", self.name
print "Role:", self.role
print "Hobby:", self.hobb
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
cnt[word] += 1
def initialize(greet, character, company):
print greet, character, company
when i run the program i got the error like:
Traceback (most recent call last):
File "C:/Users/SAGAR/Desktop/randomize.py", line 5, in <module>
import shuti1
File "C:\Python34\shuti1.py", line 3, in <module>
import randomize
File "C:/Users/SAGAR/Desktop\randomize.py", line 18, in <module>
shuti1.initialize('Hello', '!', 'HackerEarth')
AttributeError: 'module' object has no attribute 'initialize'
I'm gonna take a guess that initialize is part of the HackerEarth class as you didn't indent much to be sure. If that's the case, initialize is not part of the module, it is part of the class, so you would need a HackerEarth object in order to call it.
If that isn't the case, it could be the cyclic imports that Peter Wood mentioned (sorry, don't know how to tag!). What that means is that you are importing shuti1.py into randomize.py and randomize.py into shuti1.py. This can be confirmed looking at the error message:
File "C:/Users/SAGAR/Desktop/randomize.py", line 5, in
import shuti1
File "C:\Python34\shuti1.py", line 3, in
import randomize
Lastly, it could be caused by an IDE if you are using one. Pycharm requires all imported files to be in the project or part of your python directory. Check for something like that if you can't fix it with the other 2 things.
Hope it helps

Python weird NameError

I have a NameError that I cannot seem to be able to find the reason for. The error trace ends like this.
Traceback (most recent call last):
File ".../new_main.py", line 61, in <module>
if __name__ == "__main__": main()
File ".../new_main.py", line 39, in main
mp = build()
File ".../common.py", line 54, in build
m = r.build_from_config(map_config, character_config)
File ".../config_reader.py", line 148, in build_from_config
item["squares"]
File ".../new_map.py", line 49, in build_map
self.view = MapView(self)
File ".../new_map.py", line 135, in __init__
self.screen = reset_screen()
NameError: name 'reset_screen' is not defined
The class MapView() is in the file new_map.py and that file has this line in the imports:
from common import *
And the file common.py has the following function in it.
def reset_screen():
# check if display has been initialized
if not pygame.display.get_init():
pygame.init()
# set screen
#flags = pygame.FULLSCREEN | pygame.DOUBLEBUF
screen = pygame.display.set_mode( options.window_size )
# fill with black
screen.fill(BLACK)
return screen
What am I missing?
E: here are my imports for each file.
new_main.py:
from common import *
from new_map import Map, MapView
import pygame, sys
common.py:
import pygame
import options
from config_reader import ConfigReader
from constants import *
from coordinates import Coordinates
config_reader.py:
from action import Action
from new_map import Map
from object_type import ObjectType
from squaretype import SquareType
from new_character import Character
from coordinates import Coordinates
import direction
new_map.py:
from square import Square
from common import *
from constants import *
from coordinates import Coordinates
from map_object import MapObject
from object_type import ObjectType
from new_character import Character
from turn import TurnController
import pygame, os
Looking at your trace i can also just figure that in your common.py your are including new_map.py which causes the import in new_map to fail. If i do that to my test files, i get the same error:
my main - which imports both but still won't cause circular reference:
if __name__ == "__main__":
from common import * # <-- this is ok
from new_map import * # <-- this is no problem
do_something()
test()
my commons:
from new_map import * # <--- this will cause the problem
def reset_screen():
return 1
def do_something():
return test()
my new_map:
from common import * # <--- this will fail then
def test():
return reset_screen()
So you will have to split you common.py to the parts using new_map and the other that don't, and in new_map then import the version that holds the functions without new_map inclusion.
common_map.py
from new_map import *
def do_something()
return test()
common_nomap.py
def reset_screen()
return 1
new_map.py:
from common_nomap import *
def test()
return reset_screen()
main.py
if __name__ == "__main__":
from common_map import * # <-- this is ok
from new_map import * # <-- this is no problem
do_something()
test()
2 possible scenarios I can think of:
Circular deps: it looks like common.py activates the function in new_map.py (via config_reader.py), which might cause new_map.py not to import common.py
Is there a common package you might be importing instead of common.py?

Python Attribute Error: object has no attribute 'self'

I have a problem in class inheritance in Python; maybe it's not related to inheritance, but I have no other idea. I'm working with selenium web-driver. Here's the code I use:
from selenium import webdriver
class UIInterface(object):
def __init__(self):
self.driver = webdriver.Ie()
self.driver.get('URL')
def parentMethod(self, itemClassName = ''):
allElements = self.getAllElements()
return [el for el in allElements if el.get_attribute('type') == 'checkbox']
def getAllElements(self):
return self.driver.find_elements_by_tag_name('input')
class InterfaceChild(UIInterface):
def __init__(self):
super(InterfaceChild, self).__init__()
def childMethod(self):
returnedList = self.parentMethod(itemClassName = 'SomeClassName')
for item in returnedList:
print item.get_attribute('innerHTML')
This code gives me an error for line returnedList = self.parentMethod(itemClassName = 'SomeClassName'); the error description is this:
(<type 'exceptions.AttributeError'>, AttributeError("'InterfaceChild' object has no attribute 'self'",), <traceback object at 0x000000000418E5C8>)
I thought it might be related to inheritance, so I tried to put parentMethod and getAllElements in the class InterfaceChild; same exception raised. Any idea about this??
EDIT 1:
This is the main method for making instance of classes:
if __name__ == '__main__':
ieInterface = InterfaceChild()
ieInterface.childMethod()
This is the complete stack-trace:
Traceback (most recent call last):
File "C:\Program Files\Eclipse\eclipse-jee-helios-win32\eclipse-jee-helios-win32\plugins\org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1446, in <module>
debugger.run(setup['file'], None, None)
File "C:\Program Files\Eclipse\eclipse-jee-helios-win32\eclipse-jee-helios-win32\plugins\org.python.pydev_2.8.2.2013090511\pysrc\pydevd.py", line 1092, in run
pydev_imports.execfile(file, globals, locals) #execute the script
File "D:\workspace\testCode.py", line 133, in main
ieInterface.childMethod()
File "D:\workspace\testCode.py", line 33, in childMethod
returnedList = self.parentMethod(itemClassName = 'SomeClassName')
File "D:\workspace\testCode.py", line 45, in parentMethod
allElements = self.getAllElements()
AttributeError: 'InterfaceChild' object has no attribute 'self'
I installed selenium with pip under Python 2.7 and changed the code to use Chrome driver[1] instead and changed the checker to make sure there would be some input tags being found. full code below. I'm running the code on Mac OS X. it works just fine.
So I guess the issue here is not the code. (Windows is not a friend of Python, perhaps :).
from selenium import webdriver
class UIInterface(object):
def __init__(self):
self.driver = webdriver.Chrome()
self.driver.get('http://duckduckgo.com')
def parentMethod(self, itemClassName = ''):
allElements = self.getAllElements()
result = [el for el in allElements]
print('===', result)
return result
def getAllElements(self):
return self.driver.find_elements_by_tag_name('input')
class InterfaceChild(UIInterface):
def __init__(self):
super(InterfaceChild, self).__init__()
def childMethod(self):
returnedList = self.parentMethod(itemClassName = 'SomeClassName')
for item in returnedList:
print item.get_attribute('innerHTML')
if __name__ == '__main__':
ieInterface = InterfaceChild()
ieInterface.childMethod()
The output looks like:
('===', [<selenium.webdriver.remote.webelement.WebElement object at 0x10e145cd0>, <selenium.webdriver.remote.webelement.WebElement object at 0x10e145d10>, <selenium.webdriver.remote.webelement.WebElement object at 0x10e145d50>])
[1] http://chromedriver.storage.googleapis.com/index.html?path=2.9/

Categories