How to call a function from another class in python->sikuli? - python

How can i access methods of channel1 in channel2 so that test_script1,test_script2 is execute first and then test_script3,test_script4.
Note:- The main issue is when i am executing
suite1= unittest.TestLoader().loadTestsFromTestCase(channel1) and
suite2= unittest.TestLoader().loadTestsFromTestCase(channel2), i am getting two reprort tables.
But instead i want them to merge in one table consisting data of channel1 and channel2 classes both.
from sikuli import *
import unittest
import HTMLTestRunner
class channel1(unittest.TestCase):
def test_script1(self):
assert exists("1453186120180.png")
def test_script2(self):
assert exists("1453186901719.png")
class channel2(unittest.TestCase):
def test_script3(self):
assert exists("1453186120180.png")
def test_script4(self):
assert exists("1453186901719.png")
#channel2().test_script1()
#suite1 = unittest.TestLoader().loadTestsFromTestCase(_main_channel.channel1)
#ch1=channel1.test_script1()
#ch2=channel1.test_script2()
suite2= unittest.TestLoader().loadTestsFromTestCase(channel2)
#suite2 = unittest.TestLoader().loadTestsFromTestCase(obj2)
outfile = open("D:\\report.html", "wb") # path to report folder
#runner = HTMLTestRunner.HTMLTestRunner(stream=outfile, title=' Report Title', description='desc..' ).run(suite1)
runner = HTMLTestRunner.HTMLTestRunner(stream=outfile, title=' Report Title', description='desc..' ).run(suite1)
#runner = HTMLTestRunner.HTMLTestRunner(stream=outfile, title=' Report Title', description='desc..' ).run(suite2)
#runner.run(suite2)
Please help..

Related

Linux NoHup fails for Streaming API IG Markets where file is python

This is quite a specific question regarding nohup in linux, which runs a python file.
Back-story, I am trying to save down streaming data (from IG markets broadcast signal). And, as I am trying to run it via a remote-server (so I don't have to keep my own local desktop up 24/7),
somehow, the nohup will not engage when it 'listen's to a broadcast signal.
Below, is the example python code
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
IG Markets Stream API sample with Python
"""
user_ = 'xxx'
password_ = 'xxx'
api_key_ = 'xxx' # this is the 1st api key
account_ = 'xxx'
acc_type_ = 'xxx'
fileLoc = 'marketdata_IG_spx_5min.csv'
list_ = ["CHART:IX.D.SPTRD.DAILY.IP:5MINUTE"]
fields_ = ["UTM", "LTV", "TTV", "BID_OPEN", "BID_HIGH", \
"BID_LOW", "BID_CLOSE",]
import time
import sys
import traceback
import logging
import warnings
warnings.filterwarnings('ignore')
from trading_ig import (IGService, IGStreamService)
from trading_ig.lightstreamer import Subscription
cols_ = ['timestamp', 'data']
# A simple function acting as a Subscription listener
def on_prices_update(item_update):
# print("price: %s " % item_update)
print("xxxxxxxx
))
# A simple function acting as a Subscription listener
def on_charts_update(item_update):
# print("price: %s " % item_update)
print(xxxxxx"\
.format(
stock_name=item_update["name"], **item_update["values"]
))
res_ = [xxxxx"\
.format(
stock_name=item_update["name"], **item_update["values"]
).split(' '))]
# display(pd.DataFrame(res_))
try:
data_ = pd.read_csv(fileLoc)[cols_]
data_ = data_.append(pd.DataFrame(res_, columns = cols_))
data_.to_csv(fileLoc)
print('there is data and we are reading it')
# display(data_)
except:
pd.DataFrame(res_, columns = cols_).to_csv(fileLoc)
print('there is no data and we are saving first time')
time.sleep(60) # sleep for 1 min
def main():
logging.basicConfig(level=logging.INFO)
# logging.basicConfig(level=logging.DEBUG)
ig_service = IGService(
user_, password_, api_key_, acc_type_
)
ig_stream_service = IGStreamService(ig_service)
ig_session = ig_stream_service.create_session()
accountId = account_
################ my code to set sleep function to sleep/read at only certain time intervals
s_time = time.time()
############################
# Making a new Subscription in MERGE mode
subscription_prices = Subscription(
mode="MERGE",
# make sure to put L1 in front of the instrument name
items= list_,
fields= fields_
)
# adapter="QUOTE_ADAPTER")
# Adding the "on_price_update" function to Subscription
subscription_prices.addlistener(on_charts_update)
# Registering the Subscription
sub_key_prices = ig_stream_service.ls_client.subscribe(subscription_prices)
print('this is the line here')
input("{0:-^80}\n".format("HIT CR TO UNSUBSCRIBE AND DISCONNECT FROM \
LIGHTSTREAMER"))
# Disconnecting
ig_stream_service.disconnect()
if __name__ == '__main__':
main()
#######
Then, I try to run it on linux using this command : nohup python marketdata.py
where marketdata.py is basically the python code above.
Somehow, the nohup will not engage....... Any experts/guru who might see what I am missing in my code?

PyQgis: item is not the expected type on a QgsMapCanvas

I am currently working on a PyQgis based standalone application and I need to add various QgsRubberBand to my Canvas.
I made a subclass of it : LineAnnotation.
The problem is that when I use the method "QgsMapCanvas.itemAt(event.pos() )" on a "canvasPressEvent", it returns a "qgis._gui.QgsRubberBand" object, not a "LineAnnotation".
Did I do something wrong ? The rest of my program can't work if it doesn't recognize that it's a LineAnnotation as it contains several new methods that I need to use.
Also I can't interact with the item at all, if I try to use one of the methods from QgsRubberBand, the application crashes.
Here is the code with the problem:
from qgis.gui import QgsMapCanvas, QgsLayerTreeMapCanvasBridge, QgsRubberBand
from qgis.core import QgsApplication, QgsProject, QgsPointXY, QgsGeometry
from qgis.PyQt.QtGui import QColor
import sys
class LineAnnotation(QgsRubberBand):
def __init__(self, canvas):
QgsRubberBand.__init__(self, canvas)
self.setColor(QColor("red") )
self.setWidth(10)
class Interface(QgsMapCanvas):
def __init__(self):
QgsMapCanvas.__init__(self)
self.setCanvasColor(QColor("#182F36") )
project_path = "project_path"
project = QgsProject.instance()
project.read(project_path)
layer_tree = QgsLayerTreeMapCanvasBridge(project.layerTreeRoot(), canvas=self)
layer_tree.setAutoSetupOnFirstLayer(False)
self.zoomToFeatureExtent(project.mapLayersByName('layer_name')[0].extent() )
self.enableAntiAliasing(True)
self.setAcceptDrops(True)
self.setParallelRenderingEnabled(True)
p1 = QgsPointXY(524670.46860305720474571, 5470375.41737424582242966)
p2 = QgsPointXY(589864.10151600651443005, 5487531.63656186405569315)
r = LineAnnotation(self)
r.setToGeometry(QgsGeometry.fromPolylineXY([p1, p2]) )
def mousePressEvent(self, event) -> None:
item = self.itemAt(event.pos() )
print(type(item) )
# Output is "<class 'qgis._gui.QgsRubberBand'>"
# Expected: "<class 'LineAnnotation'>"
class StackOverflow:
def __init__(self):
qgs = QgsApplication([], True)
qgs.setDoubleClickInterval(250)
qgs.initQgis()
graphicUI = Interface()
graphicUI.showMaximized()
sys.exit(qgs.exec_() )
if __name__ == '__main__':
app = StackOverflow()
> output: \<class 'qgis.\_gui.QgsRubberBand'\>
> Desired output: \<class 'lineAnnotation.LineAnnotation'\>
Problem seems to occur in versions prior to Qgis 3.26, my problem was solved after updating to latest version (3.28).

Unable to successfully patch functions of Azure ContainerClient

I have been trying to patch the list_blobs() function of ContainerClient, have not been able to do this successfully, this code outputs a MagicMock() function - but the function isn't patched as I would expect it to be (Trying to patch with a list ['Blob1', 'Blob2'].
#################Script File
import sys
from datetime import datetime, timedelta
import pyspark
import pytz
import yaml
# from azure.storage.blob import BlobServiceClient, ContainerClient
from pyspark.dbutils import DBUtils as dbutils
import azure.storage.blob
# Open Config
def main():
spark_context = pyspark.SparkContext.getOrCreate()
spark_context.addFile(sys.argv[1])
stream = None
stream = open(sys.argv[1], "r")
config = yaml.load(stream, Loader=yaml.FullLoader)
stream.close()
account_key = dbutils.secrets.get(scope=config["Secrets"]["Scope"], key=config["Secrets"]["Key Name"])
target_container = config["Storage Configuration"]["Container"]
target_account = config["Storage Configuration"]["Account"]
days_history_to_keep = config["Storage Configuration"]["Days History To Keep"]
connection_string = (
"DefaultEndpointsProtocol=https;AccountName="
+ target_account
+ ";AccountKey="
+ account_key
+ ";EndpointSuffix=core.windows.net"
)
blob_service_client: azure.storage.blob.BlobServiceClient = (
azure.storage.blob.BlobServiceClient.from_connection_string(connection_string)
)
container_client: azure.storage.blob.ContainerClient = (
blob_service_client.get_container_client(target_container)
)
blobs = container_client.list_blobs()
print(blobs)
print(blobs)
utc = pytz.UTC
delete_before_date = utc.localize(
datetime.today() - timedelta(days=days_history_to_keep)
)
for blob in blobs:
if blob.creation_time < delete_before_date:
print("Deleting Blob: " + blob.name)
container_client.delete_blob(blob, delete_snapshots="include")
if __name__ == "__main__":
main()
#################Test File
import unittest
from unittest import mock
import DeleteOldBlobs
class DeleteBlobsTest(unittest.TestCase):
def setUp(self):
pass
#mock.patch("DeleteOldBlobs.azure.storage.blob.ContainerClient")
#mock.patch("DeleteOldBlobs.azure.storage.blob.BlobServiceClient")
#mock.patch("DeleteOldBlobs.dbutils")
#mock.patch("DeleteOldBlobs.sys")
#mock.patch('DeleteOldBlobs.pyspark')
def test_main(self, mock_pyspark, mock_sys, mock_dbutils, mock_blobserviceclient, mock_containerclient):
# mock setup
config_file = "Delete_Old_Blobs_UnitTest.yml"
mock_sys.argv = ["unused_arg", config_file]
mock_dbutils.secrets.get.return_value = "A Secret"
mock_containerclient.list_blobs.return_value = ["ablob1", "ablob2"]
# execute test
DeleteOldBlobs.main()
# TODO assert actions taken
# mock_sys.argv.__get__.assert_called_with()
# dbutils.secrets.get(scope=config['Secrets']['Scope'], key=config['Secrets']['Key Name'])
if __name__ == "__main__":
unittest.main()
Output:
<MagicMock name='BlobServiceClient.from_connection_string().get_container_client().list_blobs()' id='1143355577232'>
What am I doing incorrectly here?
I'm not able to execute your code in this moment, but I have tried to simulate it. To do this I have created the following 3 files in the path: /<path-to>/pkg/sub_pkg1 (where pkg and sub_pkg1 are packages).
File ContainerClient.py
def list_blobs(self):
return "blob1"
File DeleteOldBlobs.py
from pkg.sub_pkg1 import ContainerClient
# Open Config
def main():
blobs = ContainerClient.list_blobs()
print(blobs)
print(blobs)
File DeleteBlobsTest.py
import unittest
from unittest import mock
from pkg.sub_pkg1 import DeleteOldBlobs
class DeleteBlobsTest(unittest.TestCase):
def setUp(self):
pass
def test_main(self):
mock_containerclient = mock.MagicMock()
with mock.patch("DeleteOldBlobs.ContainerClient.list_blobs", mock_containerclient.list_blobs):
mock_containerclient.list_blobs.return_value = ["ablob1", "ablob2"]
DeleteOldBlobs.main()
if __name__ == '__main__':
unittest.main()
If you execute the test code you obtain the output:
['ablob1', 'ablob2']
['ablob1', 'ablob2']
This output means that the function list_blobs() is mocked by mock_containerclient.list_blobs.
I don't know if the content of this post can be useful for you, but I'm not able to simulate better your code in this moment.
I hope you can inspire to my code to find your real solution.
The structure of the answer didn't match my solution, perhaps both will work but it was important for me to patch pyspark even though i never call it, or exceptions would get thrown when my code tried to interact with spark.
Perhaps this will be useful to someone:
#mock.patch("DeleteOldBlobs.azure.storage.blob.BlobServiceClient")
#mock.patch("DeleteOldBlobs.dbutils")
#mock.patch("DeleteOldBlobs.sys")
#mock.patch('DeleteOldBlobs.pyspark')
def test_list_blobs_called_once(self, mock_pyspark, mock_sys, mock_dbutils, mock_blobserviceclient):
# mock setup
config_file = "Delete_Old_Blobs_UnitTest.yml"
mock_sys.argv = ["unused_arg", config_file]
account_key = 'Secret Key'
mock_dbutils.secrets.get.return_value = account_key
bsc_mock: mock.Mock = mock.Mock()
container_client_mock = mock.Mock()
blob1 = Blob('newblob', datetime.today())
blob2 = Blob('oldfile', datetime.today() - timedelta(days=20))
container_client_mock.list_blobs.return_value = [blob1, blob2]
bsc_mock.get_container_client.return_value = container_client_mock
mock_blobserviceclient.from_connection_string.return_value = bsc_mock
# execute test
DeleteOldBlobs.main()
#Assert Results
container_client_mock.list_blobs.assert_called_once()

How To Delete A Row In Excel Sheet Using Python?

I am working on a Selenium program using Python where I want to delete a row in the Excel sheet using Openpyxl library. The issue is I don't know how to implement the delete function in my program. Below here have 2 classes, AutoTest.py which is the testing class and NewCard.py which is the class where I implemented POM(Page Object Model). May I know how to implement the function to delete just 1 row in accordance with my program?
AutoTest.py
import unittest
import HtmlTestRunner
from selenium import webdriver
import openpyxl
import sys
sys.path.append("C:\Users\lukegoh\Desktop\Python Projects\SoftwareAutomationTesting")
from pageObjects.LoginPage import LoginPage
from pageObjects.HomePage import Homepage
from pageObjects.NewCard import NewCard
excpath = r"C:\Users\lukegoh\Desktop\Python Projects\SoftwareAutomationTesting\excel\new\ABT0475EC Card Init Detailed Rpt Test 01 - v13_1.xlsx"
excsheetName = "ABT0475EC Card Initialization D"
class AutoTest(unittest.TestCase):
baseURL = "https://10.2.5.215:33000/viewTopUpRequest"
username = "ezltest2svc"
password = "Password123!"
driver = webdriver.Chrome()
#classmethod
def setUpClass(cls):
cls.driver.get(cls.baseURL)
cls.driver.maximize_window()
cls.driver.implicitly_wait(10)
def test_1(self): #This is scenario 1- to create request for new card
lp = LoginPage(self.driver)
hp = Homepage(self.driver)
np = NewCard(self.driver)
lp.setUsername(self.username)
lp.setPassword(self.password)
lp.clickLogin()
hp.clickutil()
hp.clickreqNewCard()
np.setJobOrder()
np.clickExcel()
np.setTopUpAmount()
np.calculateAmount()
if not np.clickSubmit():
np.deleteRow(excpath,excsheetName,3)
else:
print("Test Passed")
# #classmethod
# def tearDownClass(cls):
# cls.driver.close()
# print("Test Completed")
#if __name__ == '__main__':
# unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='C:/Users/lukegoh/Desktop/Python Projects/SoftwareAutomationTesting/reports'))
NewCard.py
import openpyxl
class NewCard:
jobOrder_xpath="//body/div[#id='wrapper']/div[3]/div[1]/div[1]/div[1]/div[1]/input[1]"
excelButton_xpath="//input[#id='img']"
topup_textbox_xpath="//input[#id='input-live']"
calculateAmount_xpath="(//button[#type='button'])[4]"
buttonSubmit_xpath="(//button[#type='button'])[5]"
def __init__(self,driver):
self.driver=driver
def setJobOrder(self):
self.driver.find_element_by_xpath(self.jobOrder_xpath).send_keys("AutoTest1")
def clickExcel(self):
self.driver.find_element_by_xpath(self.excelButton_xpath).send_keys(r"C:\Users\lukegoh\Desktop\Python Projects\SoftwareAutomationTesting\excel\new\ABT0475EC Card Init Detailed Rpt Test 01 - v13_1.xlsx")
def setTopUpAmount(self):
self.driver.find_element_by_xpath(self.topup_textbox_xpath).send_keys("10")
def calculateAmount(self):
self.driver.find_element_by_xpath(self.calculateAmount_xpath).click()
def clickSubmit(self):
self.driver.find_element_by_xpath(self.buttonSubmit_xpath).click()
def deleteRow(file, sheetName, rownum):
workbook = openpyxl.load_workbook(file)
sheet = workbook.get_sheet_by_name(sheetName)
sheet.cell(row=rownum).
workbook.save(file)
If you check OpenPyXL docs, it has something called delete_rows()
Syntax delete_rows(idx, amount=1), it deletes from idx and goes on deleting for amount
import openpyxl
filename = "example.xlsx"
wb = openpyxl.load_workbook(filename)
sheet = wb['Sheet1']
sheet.delete_rows(row_number, 1)
wb.save(filename)
Docs for delete_rows(): https://openpyxl.readthedocs.io/en/stable/api/openpyxl.worksheet.worksheet.html#openpyxl.worksheet.worksheet.Worksheet.delete_rows
use pandas
import pandas as pd
df = pd.read_excel("test.xlsx")
df = df.drop(df.index[1])
df.to_excel('test1.xlsx')

How to excuite test classes in suite one after the other?

I have written a test suite to execute all my test classes one after the other .
But the problem is that while executing , its taking the methods from both class and executing at once.
so i want to write a code where all methods in one class will be executed
and later it will proceed to the next test class.
Test class code
from pages.Home.hamburger_page import HamburgerPage
from utilites.testStatus import TestStatus
import pytest
import unittest
#pytest.mark.usefixtures("oneTimeSetUp", "setUp")
class hamburgerTest(unittest.TestCase):
#pytest.fixture(autouse=True)
def classSetup(self, oneTimeSetUp):
self.ha = HamburgerPage(self.driver)
self.ts = TestStatus(self.driver)
#pytest.mark.run(order=1)
def test_hamburger_menu_latest_WAF021(self):
result = self.ha.find_latest()
self.ts.markFinal("To find latest link", result, "Click on latest link")
#pytest.mark.run(order=2)
def test_hamburger_menu_top__WAF022(self):
result = self.ha.find_topics_links()
self.ts.markFinal("To find top link", result, "Click on top link")
#pytest.mark.run(order=3)
def test_hamburger_menu_badges__WAF023(self):
result = self.ha.find_badges()
self.ts.markFinal("To find badges link", result, "Click on badges link")
#pytest.mark.run(order=4)
def test_hamburger_menu_users__WAF024(self):
result = self.ha.find_users()
self.ts.markFinal("To find user link ", result,"Click on users link")
#pytest.mark.run(order=5)
def test_hamburger_menu_groups__WAF025(self):
result = self.ha.find_groups()
self.ts.markFinal("To find groups link", result, "Click on groups link")
#pytest.mark.run(order=6)
def test_hamburger_menu_announcements__WAF026(self):
result = self.ha.find_announcements()
self.ts.markFinal("To find announcements link", result, "Click on announcements link")
Second Test
from pages.Home.topic_page import topicPage
from utilites.testStatus import TestStatus
import pytest
import unittest
import time
#pytest.mark.usefixtures("oneTimeSetUp","setUp")
class TopicTest(unittest.TestCase):
#pytest.fixture(autouse=True)
def classSetup(self,oneTimeSetUp):
self.tp = topicPage(self.driver)
self.ts = TestStatus(self.driver)
#pytest.mark.run(order=1)
def test_header_login(self):
self.tp.find_header_logIn()
#pytest.mark.run(order=2)
def test_validLogin(self):
self.tp.getelements("xxxxxx#xxx.com", "xxxxx")
time.sleep(3)
#pytest.mark.run(order=3)
def test_FirstLinkInAnnouncements(self):
self.tp.find_first_announcement_link()
time.sleep(3)
#pytest.mark.run(order=5)
def test_TitleVerfication(self):
self.tp.find_title()
time.sleep(5)
#pytest.mark.run(order=4)
def test_ReplyDropDown(self):
self.tp.find_scrollupfull()
time.sleep(4)
self.tp.find_topic_page_reply()
Test Suite
import unittest
from tests.Home.hamburger_test import hamburgerTest
from tests.Home.topic_test import TopicTest
# Get all tests from the test classes
tc1 = unittest.TestLoader().loadTestsFromTestCase(hamburgerTest)
tc2 = unittest.TestLoader().loadTestsFromTestCase(TopicTest)
# Create a test suite combining all test classes
Test1 = unittest.TestSuite([tc1, tc2])
unittest.TextTestRunner(verbosity=2).run(Test1)
you should execute tc1 and tc2 separately. for eg.
Test1 = unittest.TestSuite([tc1])
Test2 = unittest.TestSuite([tc2])
unittest.TextTestRunner(verbosity=2).run(Test1)
unittest.TextTestRunner(verbosity=2).run(Test2)
Hope this will solve your issue.
You are using pytest-ordering plugin (https://pytest-ordering.readthedocs.io/en/develop/).
You're setting the order in which tests should be executed. It makes pytest execute tests from highest order (1) to lowest. Tests with the same order can be found in both classes, which is why pytest is jumping between classses.

Categories