repo_id
stringclasses
208 values
file_path
stringlengths
31
190
content
stringlengths
1
2.65M
__index_level_0__
int64
0
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/ssh_util.py
""" Qxf2 Services: Utility script to ssh into a remote server * Connect to the remote server * Execute the given command * Upload a file * Download a file """ import paramiko import os,sys,time sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from conf import ssh_conf as conf_file import socket class Ssh_Util: "Class to connect to remote server" def __init__(self): self.ssh_output = None self.ssh_error = None self.client = None self.host= conf_file.HOST self.username = conf_file.USERNAME self.password = conf_file.PASSWORD self.timeout = float(conf_file.TIMEOUT) self.commands = conf_file.COMMANDS self.pkey = conf_file.PKEY self.port = conf_file.PORT self.uploadremotefilepath = conf_file.UPLOADREMOTEFILEPATH self.uploadlocalfilepath = conf_file.UPLOADLOCALFILEPATH self.downloadremotefilepath = conf_file.DOWNLOADREMOTEFILEPATH self.downloadlocalfilepath = conf_file.DOWNLOADLOCALFILEPATH def connect(self): "Login to the remote server" try: #Paramiko.SSHClient can be used to make connections to the remote server and transfer files print("Establishing ssh connection...") self.client = paramiko.SSHClient() #Parsing an instance of the AutoAddPolicy to set_missing_host_key_policy() changes it to allow any host. self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #Connect to the server if (self.password == ''): private_key = paramiko.RSAKey.from_private_key_file(self.pkey) self.client.connect(hostname=self.host, port=self.port, username=self.username,pkey=private_key ,timeout=self.timeout, allow_agent=False, look_for_keys=False) print("Connected to the server",self.host) else: self.client.connect(hostname=self.host, port=self.port,username=self.username,password=self.password,timeout=self.timeout, allow_agent=False, look_for_keys=False) print("Connected to the server",self.host) except paramiko.AuthenticationException: print("Authentication failed, please verify your credentials") result_flag = False except paramiko.SSHException as sshException: print("Could not establish SSH connection: %s" % sshException) result_flag = False except socket.timeout as e: print("Connection timed out") result_flag = False except Exception as e: print('\nException in connecting to the server') print('PYTHON SAYS:',e) result_flag = False self.client.close() else: result_flag = True return result_flag def execute_command(self,commands): """Execute a command on the remote host.Return a tuple containing an integer status and a two strings, the first containing stdout and the second containing stderr from the command.""" self.ssh_output = None result_flag = True try: if self.connect(): for command in commands: print("Executing command --> {}".format(command)) stdin, stdout, stderr = self.client.exec_command(command,timeout=10) self.ssh_output = stdout.read() self.ssh_error = stderr.read() if self.ssh_error: print("Problem occurred while running command:"+ command + " The error is " + self.ssh_error) result_flag = False else: print("Command execution completed successfully",command) self.client.close() else: print("Could not establish SSH connection") result_flag = False except socket.timeout as e: print("Command timed out.", command) self.client.close() result_flag = False except paramiko.SSHException: print("Failed to execute the command!",command) self.client.close() result_flag = False return result_flag def upload_file(self,uploadlocalfilepath,uploadremotefilepath): "This method uploads the file to remote server" result_flag = True try: if self.connect(): ftp_client= self.client.open_sftp() ftp_client.put(uploadlocalfilepath,uploadremotefilepath) ftp_client.close() self.client.close() else: print("Could not establish SSH connection") result_flag = False except Exception as e: print('\nUnable to upload the file to the remote server',uploadremotefilepath) print('PYTHON SAYS:',e) result_flag = False ftp_client.close() self.client.close() return result_flag def download_file(self,downloadremotefilepath,downloadlocalfilepath): "This method downloads the file from remote server" result_flag = True try: if self.connect(): ftp_client= self.client.open_sftp() ftp_client.get(downloadremotefilepath,downloadlocalfilepath) ftp_client.close() self.client.close() else: print("Could not establish SSH connection") result_flag = False except Exception as e: print('\nUnable to download the file from the remote server',downloadremotefilepath) print('PYTHON SAYS:',e) result_flag = False ftp_client.close() self.client.close() return result_flag #---USAGE EXAMPLES if __name__=='__main__': print("Start of %s"%__file__) #Initialize the ssh object ssh_obj = Ssh_Util() #Sample code to execute commands if ssh_obj.execute_command(ssh_obj.commands) is True: print("Commands executed successfully\n") else: print ("Unable to execute the commands" ) #Sample code to upload a file to the server if ssh_obj.upload_file(ssh_obj.uploadlocalfilepath,ssh_obj.uploadremotefilepath) is True: print ("File uploaded successfully", ssh_obj.uploadremotefilepath) else: print ("Failed to upload the file") #Sample code to download a file from the server if ssh_obj.download_file(ssh_obj.downloadremotefilepath,ssh_obj.downloadlocalfilepath) is True: print ("File downloaded successfully", ssh_obj.downloadlocalfilepath) else: print ("Failed to download the file")
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/xpath_util.py
""" Qxf2 Services: Utility script to generate XPaths for the given URL * Take the input URL from the user * Parse the HTML content using beautifilsoup * Find all Input and Button tags * Guess the XPaths * Generate Variable names for the xpaths * To run the script in Gitbash use command 'python -u utils/xpath_util.py' """ from selenium import webdriver from bs4 import BeautifulSoup import re class Xpath_Util: "Class to generate the xpaths" def __init__(self): "Initialize the required variables" self.elements = None self.guessable_elements = ['input','button'] self.known_attribute_list = ['id','name','placeholder','value','title','type','class'] self.variable_names = [] self.button_text_lists = [] self.language_counter = 1 def generate_xpath(self,soup): "generate the xpath and assign the variable names" result_flag = False try: for guessable_element in self.guessable_elements: self.elements = soup.find_all(guessable_element) for element in self.elements: if (not element.has_attr("type")) or (element.has_attr("type") and element['type'] != "hidden"): for attr in self.known_attribute_list: if element.has_attr(attr): locator = self.guess_xpath(guessable_element,attr,element) if len(driver.find_elements_by_xpath(locator))==1: result_flag = True variable_name = self.get_variable_names(element) # checking for the unique variable names if variable_name != '' and variable_name not in self.variable_names: self.variable_names.append(variable_name) print ("%s_%s = %s"%(guessable_element, variable_name.encode('utf-8'), locator.encode('utf-8'))) break else: print (locator.encode('utf-8') + "----> Couldn't generate appropriate variable name for this xpath") break elif guessable_element == 'button' and element.getText(): button_text = element.getText() if element.getText() == button_text.strip(): locator = xpath_obj.guess_xpath_button(guessable_element,"text()",element.getText()) else: locator = xpath_obj.guess_xpath_using_contains(guessable_element,"text()",button_text.strip()) if len(driver.find_elements_by_xpath(locator))==1: result_flag = True #Check for ascii characters in the button_text matches = re.search(r"[^\x00-\x7F]",button_text) if button_text.lower() not in self.button_text_lists: self.button_text_lists.append(button_text.lower()) if not matches: # Striping and replacing characters before printing the variable name print ("%s_%s = %s"%(guessable_element,button_text.strip().strip("!?.").encode('utf-8').lower().replace(" + ","_").replace(" & ","_").replace(" ","_"), locator.encode('utf-8'))) else: # printing the variable name with ascii characters along with language counter print ("%s_%s_%s = %s"%(guessable_element,"foreign_language",self.language_counter, locator.encode('utf-8')) + "---> Foreign language found, please change the variable name appropriately") self.language_counter +=1 else: # if the variable name is already taken print (locator.encode('utf-8') + "----> Couldn't generate appropriate variable name for this xpath") break except Exception as e: print ("Exception when trying to generate xpath for:%s"%guessable_element) print ("Python says:%s"%str(e)) return result_flag def get_variable_names(self,element): "generate the variable names for the xpath" # condition to check the length of the 'id' attribute and ignore if there are numerics in the 'id' attribute. Also ingnoring id values having "input" and "button" strings. if (element.has_attr('id') and len(element['id'])>2) and bool(re.search(r'\d', element['id'])) == False and ("input" not in element['id'].lower() and "button" not in element['id'].lower()): self.variable_name = element['id'].strip("_") # condition to check if the 'value' attribute exists and not having date and time values in it. elif element.has_attr('value') and element['value'] != '' and bool(re.search(r'([\d]{1,}([/-]|\s|[.])?)+(\D+)?([/-]|\s|[.])?[[\d]{1,}',element['value']))== False and bool(re.search(r'\d{1,2}[:]\d{1,2}\s+((am|AM|pm|PM)?)',element['value']))==False: # condition to check if the 'type' attribute exists # getting the text() value if the 'type' attribute value is in 'radio','submit','checkbox','search' # if the text() is not '', getting the getText() value else getting the 'value' attribute # for the rest of the type attributes printing the 'type'+'value' attribute values. Doing a check to see if 'value' and 'type' attributes values are matching. if (element.has_attr('type')) and (element['type'] in ('radio','submit','checkbox','search')): if element.getText() !='': self.variable_name = element['type']+ "_" + element.getText().strip().strip("_.") else: self.variable_name = element['type']+ "_" + element['value'].strip("_.") else: if element['type'].lower() == element['value'].lower(): self.variable_name = element['value'].strip("_.") else: self.variable_name = element['type']+ "_" + element['value'].strip("_.") # condition to check if the "name" attribute exists and if the length of "name" attribute is more than 2 printing variable name elif element.has_attr('name') and len(element['name'])>2: self.variable_name = element['name'].strip("_") # condition to check if the "placeholder" attribute exists and is not having any numerics in it. elif element.has_attr('placeholder') and bool(re.search(r'\d', element['placeholder'])) == False: self.variable_name = element['placeholder'].strip("_?*.").encode('ascii',errors='ignore') # condition to check if the "type" attribute exists and not in text','radio','button','checkbox','search' # and printing the variable name elif (element.has_attr('type')) and (element['type'] not in ('text','button','radio','checkbox','search')): self.variable_name = element['type'] # condition to check if the "title" attribute exists elif element.has_attr('title'): self.variable_name = element['title'] # condition to check if the "role" attribute exists elif element.has_attr('role') and element['role']!="button": self.variable_name = element['role'] else: self.variable_name = '' return self.variable_name.lower().replace("+/- ","").replace("| ","").replace(" / ","_"). \ replace("/","_").replace(" - ","_").replace(" ","_").replace("&","").replace("-","_"). \ replace("[","_").replace("]","").replace(",","").replace("__","_").replace(".com","").strip("_") def guess_xpath(self,tag,attr,element): "Guess the xpath based on the tag,attr,element[attr]" #Class attribute returned as a unicodeded list, so removing 'u from the list and joining back if type(element[attr]) is list: element[attr] = [i.encode('utf-8') for i in element[attr]] element[attr] = ' '.join(element[attr]) self.xpath = "//%s[@%s='%s']"%(tag,attr,element[attr]) return self.xpath def guess_xpath_button(self,tag,attr,element): "Guess the xpath for button tag" self.button_xpath = "//%s[%s='%s']"%(tag,attr,element) return self.button_xpath def guess_xpath_using_contains(self,tag,attr,element): "Guess the xpath using contains function" self.button_contains_xpath = "//%s[contains(%s,'%s')]"%(tag,attr,element) return self.button_contains_xpath #-------START OF SCRIPT-------- if __name__ == "__main__": print ("Start of %s"%__file__) #Initialize the xpath object xpath_obj = Xpath_Util() #Get the URL and parse url = input("Enter URL: ") #Create a chrome session driver = webdriver.Chrome() driver.get(url) #Parsing the HTML page with BeautifulSoup page = driver.execute_script("return document.body.innerHTML").encode('utf-8') #returns the inner HTML as a string soup = BeautifulSoup(page, 'html.parser') #execute generate_xpath if xpath_obj.generate_xpath(soup) is False: print ("No XPaths generated for the URL:%s"%url) driver.quit()
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/results.py
""" Tracks test results and logs them. Keeps counters of pass/fail/total. """ import logging from utils.Base_Logging import Base_Logging class Results(object): """ Base class for logging intermediate test outcomes """ def __init__(self, level=logging.DEBUG, log_file_path=None): self.logger = Base_Logging(log_file_name=log_file_path, level=level) self.total = 0 # Increment whenever success or failure are called self.passed = 0 # Increment everytime success is called self.written = 0 # Increment when conditional_write is called # Increment when conditional_write is called with True self.written_passed = 0 self.failure_message_list = [] def assert_results(self): """ Check if the test passed or failed """ assert self.passed == self.total def write(self, msg, level='info'): """ This method use the logging method """ self.logger.write(msg, level) def record(self, condition, msg, level='debug', indent=1): """ Write out either the positive or the negative message based on flag """ if condition: self.written_passed += 1 prefix = '' for i in range(indent if indent > 0 else 0): prefix = prefix + ' ' self.written += 1 self.write(prefix + msg + (' False' if condition else ' True'), level) def conditional_write(self, condition, positive, negative, level='info', pre_format=" - "): """ Write out either the positive or the negative message based on flag """ if condition: self.write(pre_format + positive, level) self.written_passed += 1 else: self.write(pre_format + negative, level) self.written += 1 def log_result(self, flag, positive, negative, level='info'): """ Write out the result of the test """ if flag is True: self.success(positive, level=level) if flag is False: self.failure(negative, level=level) raise Exception self.write('~~~~~~~~\n', level) def success(self, msg, level='info', pre_format='PASS: '): """ Write out a success message """ self.logger.write(pre_format + msg, level) self.total += 1 self.passed += 1 def failure(self, msg, level='info', pre_format='FAIL: '): """ Write out a failure message """ self.logger.write(pre_format + msg, level) self.total += 1 self.failure_message_list.append(pre_format + msg) def get_failure_message_list(self): """ Return the failure message list """ return self.failure_message_list def write_test_summary(self): """ Print out a useful, human readable summary """ self.write('\n************************\n--------RESULT--------\nTotal number of checks=%d' % self.total) self.write('Total number of checks passed=%d\n----------------------\n************************\n\n' % self.passed) self.write('Total number of mini-checks=%d' % self.written) self.write('Total number of mini-checks passed=%d' % self.written_passed) failure_message_list = self.get_failure_message_list() if len(failure_message_list) > 0: self.write('\n--------FAILURE SUMMARY--------\n') for msg in failure_message_list: self.write(msg)
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/Image_Compare.py
""" Qxf2 Services: Utility script to compare images * Compare two images(actual and expected) smartly and generate a resultant image * Get the sum of colors in an image """ from PIL import Image, ImageChops import math,operator,os def rmsdiff(im1,im2): "Calculate the root-mean-square difference between two images" h = ImageChops.difference(im1, im2).histogram() # calculate rms return math.sqrt(sum(h*(i**2) for i, h in enumerate(h)) / (float(im1.size[0]) * im1.size[1])) def is_equal(img_actual,img_expected,result): "Returns true if the images are identical(all pixels in the difference image are zero)" result_flag = False if not os.path.exists(img_actual): print('Could not locate the generated image: %s'%img_actual) if not os.path.exists(img_expected): print('Could not locate the baseline image: %s'%img_expected) if os.path.exists(img_actual) and os.path.exists(img_expected): actual = Image.open(img_actual) expected = Image.open(img_expected) result_image = ImageChops.difference(actual,expected) color_matrix = ([0] + ([255] * 255)) result_image = result_image.convert('L') result_image = result_image.point(color_matrix) result_image.save(result)#Save the result image if (ImageChops.difference(actual,expected).getbbox() is None): result_flag = True else: #Let's do some interesting processing now result_flag = analyze_difference_smartly(result) if result_flag is False: print("Since there is a difference in pixel value of both images, we are checking the threshold value to pass the images with minor difference") #Now with threshhold! result_flag = True if rmsdiff(actual,expected) < 958 else False #For temporary debug purposes print('RMS diff score: ',rmsdiff(actual,expected)) return result_flag def analyze_difference_smartly(img): "Make an evaluation of a difference image" result_flag = False if not os.path.exists(img): print('Could not locate the image to analyze the difference smartly: %s'%img) else: my_image = Image.open(img) #Not an ideal line, but we dont have any enormous images pixels = list(my_image.getdata()) pixels = [1 for x in pixels if x!=0] num_different_pixels = sum(pixels) print('Number of different pixels in the result image: %d'%num_different_pixels) #Rule 1: If the number of different pixels is <10, then pass the image #This is relatively safe since all changes to objects will be more than 10 different pixels if num_different_pixels < 10: result_flag = True return result_flag def get_color_sum(img): "Get the sum of colors in an image" sum_color_pixels = -1 if not os.path.exists(img): print('Could not locate the image to sum the colors: %s'%actual) else: my_image = Image.open(img) color_matrix = ([0] + ([255] * 255)) my_image = my_image.convert('L') my_image = my_image.point(color_matrix) #Not an ideal line, but we don't have any enormous images pixels = list(my_image.getdata()) sum_color_pixels = sum(pixels) print('Sum of colors in the image %s is %d'%(img,sum_color_pixels)) return sum_color_pixels #--START OF SCRIPT if __name__=='__main__': # Please update below img1, img2, result_img values before running this script img1 = r'Add path of first image' img2 = r'Add path of second image' result_img= r'Add path of result image' #please add path along with resultant image name which you want # Compare images and generate a resultant difference image result_flag = is_equal(img1,img2,result_img) if (result_flag == True): print("Both images are matching") else: print("Images are not matching") # Get the sum of colors in an image get_color_sum(img1)
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/email_util.py
""" A simple IMAP util that will help us with account activation * Connect to your imap host * Login with username/password * Fetch latest messages in inbox * Get a recent registration message * Filter based on sender and subject * Return text of recent messages [TO DO](not in any particular order) 1. Extend to POP3 servers 2. Add a try catch decorator 3. Enhance get_latest_email_uid to make all parameters optional """ #The import statements import: standard Python modules,conf import os,sys,time,imaplib,email,datetime sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import conf.email_conf as conf_file class Email_Util: "Class to interact with IMAP servers" def connect(self,imap_host): "Connect with the host" self.mail = imaplib.IMAP4_SSL(imap_host) return self.mail def login(self,username,password): "Login to the email" result_flag = False try: self.mail.login(username,password) except Exception as e: print('\nException in Email_Util.login') print('PYTHON SAYS:') print(e) print('\n') else: result_flag = True return result_flag def get_folders(self): "Return a list of folders" return self.mail.list() def select_folder(self,folder): "Select the given folder if it exists. E.g.: [Gmail]/Trash" result_flag = False response = self.mail.select(folder) if response[0] == 'OK': result_flag = True return result_flag def get_latest_email_uid(self,subject=None,sender=None,time_delta=10,wait_time=300): "Search for a subject and return the latest unique ids of the emails" uid = None time_elapsed = 0 search_string = '' if subject is None and sender is None: search_string = 'ALL' if subject is None and sender is not None: search_string = '(FROM "{sender}")'.format(sender=sender) if subject is not None and sender is None: search_string = '(SUBJECT "{subject}")'.format(subject=subject) if subject is not None and sender is not None: search_string = '(FROM "{sender}" SUBJECT "{subject}")'.format(sender=sender,subject=subject) print(" - Automation will be in search/wait mode for max %s seconds"%wait_time) while (time_elapsed < wait_time and uid is None): time.sleep(time_delta) result,data = self.mail.uid('search',None,str(search_string)) if data[0].strip() != '': #Check for an empty set uid = data[0].split()[-1] time_elapsed += time_delta return uid def fetch_email_body(self,uid): "Fetch the email body for a given uid" email_body = [] if uid is not None: result,data = self.mail.uid('fetch',uid,'(RFC822)') raw_email = data[0][1] email_msg = email.message_from_string(raw_email) email_body = self.get_email_body(email_msg) return email_body def get_email_body(self,email_msg): "Parse out the text of the email message. Handle multipart messages" email_body = [] maintype = email_msg.get_content_maintype() if maintype == 'multipart': for part in email_msg.get_payload(): if part.get_content_maintype() == 'text': email_body.append(part.get_payload()) elif maintype == 'text': email_body.append(email_msg.get_payload()) return email_body def logout(self): "Logout" result_flag = False response, data = self.mail.logout() if response == 'BYE': result_flag = True return result_flag #---EXAMPLE USAGE--- if __name__=='__main__': #Fetching conf details from the conf file imap_host = conf_file.imaphost username = conf_file.username password = conf_file.app_password #Initialize the email object email_obj = Email_Util() #Connect to the IMAP host email_obj.connect(imap_host) #Login if email_obj.login(username,password): print("PASS: Successfully logged in.") else: print("FAIL: Failed to login") #Get a list of folder folders = email_obj.get_folders() if folders != None or []: print("PASS: Email folders:", email_obj.get_folders()) else: print("FAIL: Didn't get folder details") #Select a folder if email_obj.select_folder('Inbox'): print("PASS: Successfully selected the folder: Inbox") else: print("FAIL: Failed to select the folder: Inbox") #Get the latest email's unique id uid = email_obj.get_latest_email_uid(wait_time=300) if uid != None: print("PASS: Unique id of the latest email is: ",uid) else: print("FAIL: Didn't get unique id of latest email") #A. Look for an Email from provided sender, print uid and check it's contents uid = email_obj.get_latest_email_uid(sender="Andy from Google",wait_time=300) if uid != None: print("PASS: Unique id of the latest email with given sender is: ",uid) #Check the text of the latest email id email_body = email_obj.fetch_email_body(uid) data_flag = False print(" - Automation checking mail contents") for line in email_body: line = line.replace('=','') line = line.replace('<','') line = line.replace('>','') if "Hi Email_Util" and "This email was sent to you" in line: data_flag = True break if data_flag == True: print("PASS: Automation provided correct Email details. Email contents matched with provided data.") else: print("FAIL: Provided data not matched with Email contents. Looks like automation provided incorrect Email details") else: print("FAIL: After wait of 5 mins, looks like there is no email present with given sender") #B. Look for an Email with provided subject, print uid, find Qxf2 POM address and compare with expected address uid = email_obj.get_latest_email_uid(subject="Qxf2 Services: Public POM Link",wait_time=300) if uid != None: print("PASS: Unique id of the latest email with given subject is: ",uid) #Get pom url from email body email_body = email_obj.fetch_email_body(uid) expected_pom_url = "https://github.com/qxf2/qxf2-page-object-model" pom_url = None data_flag = False print(" - Automation checking mail contents") for body in email_body: search_str = "/qxf2/" body = body.split() for element in body: if search_str in element: pom_url = element data_flag = True break if data_flag == True: break if data_flag == True and expected_pom_url == pom_url: print("PASS: Automation provided correct mail details. Got correct Qxf2 POM url from mail body. URL: %s"%pom_url) else: print("FAIL: Actual POM url not matched with expected pom url. Actual URL got from email: %s"%pom_url) else: print("FAIL: After wait of 5 mins, looks like there is no email present with given subject") #C. Look for an Email with provided sender and subject and print uid uid = email_obj.get_latest_email_uid(subject="get more out of your new Google Account",sender="[email protected]",wait_time=300) if uid != None: print("PASS: Unique id of the latest email with given subject and sender is: ",uid) else: print("FAIL: After wait of 5 mins, looks like there is no email present with given subject and sender") #D. Look for an Email with non-existant sender and non-existant subject details uid = email_obj.get_latest_email_uid(subject="Activate your account",sender="[email protected]",wait_time=120) #you can change wait time by setting wait_time variable if uid != None: print("FAIL: Unique id of the latest email with non-existant subject and non-existant sender is: ",uid) else: print("PASS: After wait of 2 mins, looks like there is no email present with given non-existant subject and non-existant sender")
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/Tesults.py
import tesults import conf.tesults_conf as conf_file cases = [] def add_test_case(data): cases.append(data) def post_results_to_tesults (): token = conf_file.target_token_default # uses default token unless otherwise specified data = { 'target': token, 'results': { 'cases': cases } } print ('-----Tesults output-----') if len(data['results']['cases']) > 0: print (data) print('Uploading results to Tesults...') ret = tesults.results(data) print ('success: ' + str(ret['success'])) print ('message: ' + str(ret['message'])) print ('warnings: ' + str(ret['warnings'])) print ('errors: ' + str(ret['errors'])) else: print ('No test results.')
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/__init__.py
"Check if dict item exist for given key else return none" def get_dict_item(from_this, get_this): """ get dic object item """ if not from_this: return None item = from_this if isinstance(get_this, str): if get_this in from_this: item = from_this[get_this] else: item = None else: for key in get_this: if isinstance(item, dict) and key in item: item = item[key] else: return None return item
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/post_test_reports_to_slack.py
''' A Simple API util which used to post test reports on Slack Channel. Steps to Use: 1. Generate Slack incoming webhook url by reffering our blog: https://qxf2.com/blog/post-pytest-test-results-on-slack/ & add url in our code 2. Generate test report log file by adding ">log/pytest_report.log" command at end of py.test command for e.g. py.test -k example_form -I Y -r F -v > log/pytest_report.log Note: Your terminal must be pointed to root address of our POM while generating test report file using above command 3. Check you are calling correct report log file or not ''' import json,os,requests def post_reports_to_slack(): #To generate incoming webhook url ref: https://qxf2.com/blog/post-pytest-test-results-on-slack/ url= "incoming webhook url" #Add your Slack incoming webhook url here #To generate pytest_report.log file add ">pytest_report.log" at end of py.test command for e.g. py.test -k example_form -I Y -r F -v > log/pytest_report.log test_report_file = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','log','pytest_report.log'))#Change report file name & address here with open(test_report_file, "r") as in_file: testdata = "" for line in in_file: testdata = testdata + '\n' + line # Set Slack Pass Fail bar indicator color according to test results if 'FAILED' in testdata: bar_color = "#ff0000" else: bar_color = "#36a64f" data = {"attachments":[ {"color": bar_color, "title": "Test Report", "text": testdata} ]} json_params_encoded = json.dumps(data) slack_response = requests.post(url=url,data=json_params_encoded,headers={"Content-type":"application/json"}) if slack_response.text == 'ok': print('\n Successfully posted pytest report on Slack channel') else: print('\n Something went wrong. Unable to post pytest report on Slack channel. Slack Response:', slack_response) #---USAGE EXAMPLES if __name__=='__main__': post_reports_to_slack()
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/BrowserStack_Library.py
""" First version of a library to interact with BrowserStack's artifacts. For now, this is useful for: a) Obtaining the session URL b) Obtaining URLs of screenshots To do: a) Handle expired sessions better """ import os,requests,sys from conf import remote_credentials as remote_credentials class BrowserStack_Library(): "BrowserStack library to interact with BrowserStack artifacts" def __init__(self): "Constructor for the BrowserStack library" self.browserstack_url = "https://www.browserstack.com/automate/" self.auth = self.get_auth() def get_auth(self): "Set up the auth object for the Requests library" USERNAME = remote_credentials.USERNAME PASSWORD = remote_credentials.ACCESS_KEY auth = (USERNAME,PASSWORD) return auth def get_build_id(self): "Get the build ID" self.build_url = self.browserstack_url + "builds.json" builds = requests.get(self.build_url, auth=self.auth).json() build_id = builds[0]['automation_build']['hashed_id'] return build_id def get_sessions(self): "Get a JSON object with all the sessions" build_id = self.get_build_id() sessions= requests.get(self.browserstack_url + 'builds/%s/sessions.json'%build_id, auth=self.auth).json() return sessions def get_active_session_id(self): "Return the session ID of the first active session" session_id = None sessions = self.get_sessions() for session in sessions: #Get session id of the first session with status = running if session['automation_session']['status']=='running': session_id = session['automation_session']['hashed_id'] break return session_id def get_session_url(self): "Get the session URL" build_id = self.get_build_id() session_id = self.get_active_session_id() session_url = self.browserstack_url + 'builds/%s/sessions/%s'%(build_id,session_id) return session_url def get_session_logs(self): "Return the session log in text format" build_id = self.get_build_id() session_id = self.get_active_session_id() session_log = requests.get(self.browserstack_url + 'builds/%s/sessions/%s/logs'%(build_id,session_id),auth=self.auth).text return session_log def get_latest_screenshot_url(self): "Get the URL of the latest screenshot" session_log = self.get_session_logs() #Process the text to locate the URL of the last screenshot #Extract the https://s2.amazonaws from example lines: #2016-2-9 4:42:39:52 RESPONSE {"state":"success","sessionId":"f77e1de6e4f42a72e6a6ecfd80ed07b95036ca35","hCode":29018101,"value":"https://s3.amazonaws.com/testautomation/f77e1de6e4f42a72e6a6ecfd80ed07b95036ca35/screenshot-selenium-b14d4ec62a.png","class":"org.openqa.selenium.remote.Response","status":0} #[2016-2-9 4:42:45:892] REQUEST [[2016-2-9 4:42:45:892]] GET /session/f77e1de6e4f42a72e6a6ecfd80ed07b95036ca35/title {} #2016-2-9 4:42:45:957 RESPONSE {"state":"success","sessionId":"f77e1de6e4f42a72e6a6ecfd80ed07b95036ca35","hCode":19687124,"value":"New Member Registration & Signup - Chess.com","class":"org.openqa.selenium.remote.Response","status":0} screenshot_request = session_log.split('screenshot {}')[-1] response_result = screenshot_request.split('REQUEST')[0] image_url = response_result.split('https://')[-1] image_url = image_url.split('.png')[0] screenshot_url = 'https://' + image_url + '.png' return screenshot_url
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/Custom_Exceptions.py
""" This utility is for Custom Exceptions. a) Stop_Test_Exception You can raise generic exceptions using just a string. This is particularly useful when you want to end a test midway based on some condition """ class Stop_Test_Exception(Exception): "Raise when a critical step fails and test needs to stop" def __init__(self,message): "Initializer" self.message=message def __str__(self): "Return the message in exception format" return self.message
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/Base_Logging.py
""" Qxf2 Services: A plug-n-play class for logging. This class wraps around Python's loguru module. """ import os, inspect import datetime import sys from loguru import logger class Base_Logging(): "A plug-n-play class for logging" def __init__(self,log_file_name=None,level="DEBUG",format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {module} | {message}"): "Constructor for the logging class" self.log_file_name=log_file_name self.log_file_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','log')) self.level=level self.format=format self.log = self.set_log(self.log_file_name,self.level,self.format) def set_log(self,log_file_name,level,format,test_module_name=None): "Add an handler sending log messages to a sink" if test_module_name is None: test_module_name = self.get_calling_module() if not os.path.exists(self.log_file_dir): os.makedirs(self.log_file_dir) if log_file_name is None: log_file_name = self.log_file_dir + os.sep + test_module_name + '.log' else: log_file_name = self.log_file_dir + os.sep + log_file_name logger.add(log_file_name,level=level,format=format, rotation="30 days", filter=None, colorize=None, serialize=False, backtrace=True, enqueue=False, catch=True) def get_calling_module(self): "Get the name of the calling module" calling_file = inspect.stack()[-1][1] if 'runpy' in calling_file: calling_file = inspect.stack()[4][1] calling_filename = calling_file.split(os.sep) #This logic bought to you by windows + cygwin + git bash if len(calling_filename) == 1: #Needed for calling_filename = calling_file.split('/') self.calling_module = calling_filename[-1].split('.')[0] return self.calling_module def write(self,msg,level='info'): "Write out a message" fname = inspect.stack()[2][3] #May be use a entry-exit decorator instead d = {'caller_func': fname} if level.lower()== 'debug': logger.debug("{module} | {msg}",module=d['caller_func'],msg=msg) elif level.lower()== 'info': logger.info("{module} | {msg}",module=d['caller_func'],msg=msg) elif level.lower()== 'warn' or level.lower()=='warning': logger.warning("{module} | {msg}",module=d['caller_func'],msg=msg) elif level.lower()== 'error': logger.error("{module} | {msg}",module=d['caller_func'],msg=msg) elif level.lower()== 'critical': logger.critical("{module} | {msg}",module=d['caller_func'],msg=msg) else: logger.critical("Unknown level passed for the msg: {}", msg)
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/testrail.py
# # TestRail API binding for Python 3.x (API v2, available since # TestRail 3.0) # # Learn more: # # http://docs.gurock.com/testrail-api2/start # http://docs.gurock.com/testrail-api2/accessing # # Copyright Gurock Software GmbH. See license.md for details. # import urllib.request, urllib.error import json, base64 class APIClient: def __init__(self, base_url): self.user = '' self.password = '' if not base_url.endswith('/'): base_url += '/' self.__url = base_url + 'index.php?/api/v2/' print ("API") # # Send Get # # Issues a GET request (read) against the API and returns the result # (as Python dict). # # Arguments: # # uri The API method to call including parameters # (e.g. get_case/1) # def send_get(self, uri): return self.__send_request('GET', uri, None) # # Send POST # # Issues a POST request (write) against the API and returns the result # (as Python dict). # # Arguments: # # uri The API method to call including parameters # (e.g. add_case/1) # data The data to submit as part of the request (as # Python dict, strings must be UTF-8 encoded) # def send_post(self, uri, data): return self.__send_request('POST', uri, data) def __send_request(self, method, uri, data): url = self.__url + uri request = urllib.request.Request(url) if (method == 'POST'): request.data = bytes(json.dumps(data), 'utf-8') auth = str( base64.b64encode( bytes('%s:%s' % (self.user, self.password), 'utf-8') ), 'ascii' ).strip() request.add_header('Authorization', 'Basic %s' % auth) request.add_header('Content-Type', 'application/json') e = None try: response = urllib.request.urlopen(request).read() except urllib.error.HTTPError as ex: response = ex.read() e = ex if response: result = json.loads(response.decode()) else: result = {} if e != None: if result and 'error' in result: error = '"' + result['error'] + '"' else: error = 'No additional error message received' raise APIError('TestRail API returned HTTP %s (%s)' % (e.code, error)) return result class APIError(Exception): pass
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/Test_Runner_Class.py
""" Test Runner class. Lets you setup testrail and run a bunch of tests one after the other """ import os,subprocess class Test_Runner_Class: "Test Runner class" def __init__(self,base_url='http://qxf2.com',testrail_flag='N',browserstack_flag='N',os_name='Windows',os_version='7',browser='firefox',browser_version='33'): "Constructor" self.python_executable = "python" self.util_directory = os.path.abspath((os.path.dirname(__file__))) self.test_directory = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','tests')) self.setup_testrail_script = os.path.join(self.util_directory,"setup_testrail.py") self.reset(base_url=base_url, testrail_flag=testrail_flag, browserstack_flag=browserstack_flag, os_name=os_name, os_version=os_version, browser=browser, browser_version=browser_version) def check_file_exists(self,file_path): "Check if the config file exists and is a file" file_exist_flag = True if os.path.exists(file_path): if not os.path.isfile(file_path): print('\n****') print('Script file provided is not a file: ') print(file_path) print('****') file_exist_flag = False else: print('\n****') print('Unable to locate the provided script file: ') print(file_path) print('****') conf_flag = False return file_exist_flag def reset(self,base_url=None,testrail_flag=None,browserstack_flag=None,os_name=None,os_version=None,browser=None,browser_version=None): "Reset the private variables" if base_url is not None: self.base_url = base_url if testrail_flag is not None: self.testrail_flag = testrail_flag if browserstack_flag is not None: self.browserstack_flag = browserstack_flag if os_name is not None: self.os_name = os_name if os_version is not None: self.os_version = os_version if browser is not None: self.browser = browser if browser_version is not None: self.browser_version = browser_version def run_test(self,test_name): "Run the test script with the given command line options" testscript_args_list = self.setup_test_script_args_list(test_name) self.run_script(testscript_args_list) def run_setup_testrail(self,test_name=None,test_run_name='',case_ids_list=None,name_override_flag=True): "Run the setup_testrail with given command line options" if self.testrail_flag.lower() == 'y': testrail_args_list = self.setup_testrail_args_list(test_name,test_run_name,case_ids_list,name_override_flag) self.run_script(testrail_args_list) def run_script(self,args_list): "Run the script on command line with given args_list" print("\nWill be running the following script:") print(' '.join(args_list)) print("Starting..") subprocess.call(args_list,shell=True) print("Done!") def setup_testrail_args_list(self,test_name=None,test_run_name='',case_ids_list=None,name_override_flag=True): "Convert the command line arguments into list for setup_testrail.py" args_list = [] #python setup_testrail.py -r test_run_name -d test_run_description if self.check_file_exists(self.setup_testrail_script): args_list = [self.python_executable,self.setup_testrail_script] if test_run_name != '': args_list.append("-r") args_list.append(test_run_name) if test_name is not None: args_list.append("-d") args_list.append(test_name) if name_override_flag is False: args_list.append("-n") args_list.append("N") if case_ids_list is not None: args_list.append("-c") case_ids_list = ','.join(case_ids_list) args_list.append(case_ids_list) return args_list def setup_test_script_args_list(self,test_name): "convert the command line arguments into list for test script" args_list = [] #python test_script.py -x Y test_script_name = test_name + ".py" test_script_name = os.path.join(self.test_directory,test_script_name) if self.check_file_exists(test_script_name): args_list = [self.python_executable,test_script_name,"-b",self.browser,"-u",self.base_url,"-x",self.testrail_flag,"-s",self.browserstack_flag,"-o",self.os_version,"-v",self.browser_version,"-p",self.os_name] return args_list
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/excel_compare.py
""" Qxf2 Services: Utility script to compare two excel files using openxl module """ import openpyxl import os class Excel_Compare(): def is_equal(self,xl_actual,xl_expected): "Method to compare the Actual and Expected xl file" result_flag = True if not os.path.exists(xl_actual): result_flag = False print('Could not locate the excel file: %s'%xl_actual) if not os.path.exists(xl_expected): result_flag = False print('Could not locate the excel file %s'%xl_expected) if os.path.exists(xl_actual) and os.path.exists(xl_expected): #Open the xl file and put the content to list actual_xlfile = openpyxl.load_workbook(xl_actual) xl_sheet = actual_xlfile.active actual_file = [] for row in xl_sheet.iter_rows(min_row=1, max_col=xl_sheet.max_column, max_row=xl_sheet.max_row): for cell in row: actual_file.append(cell.value) exp_xlfile = openpyxl.load_workbook(xl_expected) xl_sheet = exp_xlfile.active exp_file = [] for row in xl_sheet.iter_rows(min_row=1, max_col=xl_sheet.max_column, max_row=xl_sheet.max_row): for cell in row: exp_file.append(cell.value) #If there is row and column mismatch result_flag = False if (len(actual_file)!= len(exp_file)): result_flag = False print("Mismatch in number of rows or columns. The actual row or column count didn't match with expected row or column count") else: for actual_row, actual_col in zip(actual_file,exp_file): if actual_row == actual_col: pass else: print("Mismatch between actual and expected file at position(each row consists of 23 coordinates):",actual_file.index(actual_row)) print("Data present only in Actual file: %s"%actual_row) print("Data present only in Expected file: %s"%actual_col) result_flag = False return result_flag #---USAGE EXAMPLES if __name__=='__main__': print("Start of %s"%__file__) # Enter the path details of the xl files here file1 = 'Add path to the first xl file' file2 = 'Add path to the second xl file' #Initialize the excel object xl_obj = Excel_Compare() #Sample code to compare excel files if xl_obj.is_equal(file1,file2) is True: print("Data matched in both the excel files\n") else: print("Data mismatch between the actual and expected excel files")
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/Option_Parser.py
""" Class to wrap around parsing command line options """ import os, sys import optparse class Option_Parser: "The option parser class" def __init__(self,usage="\n----\n%prog -b <OPTIONAL: Browser> -c <OPTIONAL: configuration_file> -u <OPTIONAL: APP URL> -a <OPTIONAL: API URL> -r <Test Run Id> -t <OPTIONAL: testrail_configuration_file> -s <OPTIONAL: sauce flag>\n----\nE.g.: %prog -b FF -c .conf -u http://qxf2.com -r 2 -t testrail.conf -s Y\n---" ): "Class initializer" self.usage=usage self.parser=optparse.OptionParser() self.set_standard_options() def set_standard_options(self): "Set options shared by all tests over here" self.parser.add_option("-B","--browser", dest="browser", default="firefox", help="Browser. Valid options are firefox, ie and chrome") self.parser.add_option("-U","--app_url", dest="url", default="https://qxf2.com", help="The url of the application") self.parser.add_option("-A","--api_url", dest="api_url", default="http://35.167.62.251/", help="The url of the api") self.parser.add_option("-X","--testrail_flag", dest="testrail_flag", default='N', help="Y or N. 'Y' if you want to report to TestRail") self.parser.add_option("-R","--test_run_id", dest="test_run_id", default=None, help="The test run id in TestRail") self.parser.add_option("-M","--remote_flag", dest="remote_flag", default="N", help="Run the test in remote flag: Y or N") self.parser.add_option("-O","--os_version", dest="os_version", help="The operating system: xp, 7", default="7") self.parser.add_option("--ver", dest="browser_version", help="The version of the browser: a whole number", default=45) self.parser.add_option("-P","--os_name", dest="os_name", help="The operating system: Windows , Linux", default="Windows") self.parser.add_option("-G","--mobile_os_name", dest="mobile_os_name", help="Enter operating system of mobile. Ex: Android, iOS", default="Android") self.parser.add_option("-H","--mobile_os_version", dest="mobile_os_version", help="Enter version of operating system of mobile: 8.1.0", default="6.0") self.parser.add_option("-I","--device_name", dest="device_name", help="Enter device name. Ex: Emulator, physical device name", default="Google Nexus 6") self.parser.add_option("-J","--app_package", dest="app_package", help="Enter name of app package. Ex: bitcoininfo", default="com.dudam.rohan.bitcoininfo") self.parser.add_option("-K","--app_activity", dest="app_activity", help="Enter name of app activity. Ex: .MainActivity", default=".MainActivity") self.parser.add_option("-Q","--device_flag", dest="device_flag", help="Enter Y or N. 'Y' if you want to run the test on device. 'N' if you want to run the test on emulator.", default="N") self.parser.add_option("-D","--app_name", dest="app_name", help="Enter application name to be uploaded.Ex:Bitcoin Info_com.dudam.rohan.bitcoininfo.apk.", default="Bitcoin Info_com.dudam.rohan.bitcoininfo.apk") self.parser.add_option("-T","--tesults_flag", dest="tesults_flag", help="Enter Y or N. 'Y' if you want to report results with Tesults", default="N") self.parser.add_option("-N","--app_path", dest="app_path", help="Enter app path") self.parser.add_option("--remote_project_name", dest="remote_project_name", help="The project name if its run in BrowserStack", default=None) self.parser.add_option("--remote_build_name", dest="remote_build_name", help="The build name if its run in BrowserStack", default=None) def add_option(self,option_letter,option_word,dest,help_text): "Add an option to our parser" self.parser.add(option_letter, option_word, dest, help=help_text) def get_options(self): "Get the command line arguments passed into the script" (options,args)=self.parser.parse_args() return options def check_file_exists(self,file_path): "Check if the config file exists and is a file" self.conf_flag = True if os.path.exists(file_path): if not os.path.isfile(file_path): print('\n****') print('Config file provided is not a file: ') print(file_path) print('****') self.conf_flag = False else: print('\n****') print('Unable to locate the provided config file: ') print(file_path) print('****') self.conf_flag = False return self.conf_flag def check_options(self,options): "Check if the command line options are valid" result_flag = True if options.browser is not None: result_flag &= True else: result_flag = False print("Browser cannot be None. Use -B to specify a browser") if options.url is not None: result_flag &= True else: result_flag = False print("Url cannot be None. Use -U to specify a url") if options.api_url is not None: result_flag &= True else: result_flag = False print("API URL cannot be None. Use -A to specify a api url") if options.remote_flag.lower() == 'y': if options.browser_version is not None: result_flag &= True else: result_flag = False print("Browser version cannot be None. Use --ver to specify a browser version") if options.os_name is not None: result_flag &= True else: result_flag = False print("The operating system cannot be None. Use -P to specify an OS") if options.os_version is not None: result_flag &= True else: result_flag = False print("The OS version cannot be None. Use -O to specify an OS version") # Options for appium mobile tests. if options.mobile_os_name is not None: result_flag &= True else: result_flag = False print("The mobile operating system cannot be None. Use -G to specify an OS.") if options.mobile_os_version is not None: result_flag &= True else: result_flag = False print("The mobile operating system version cannot be None. Use -H to specify an OS version.") if options.device_name is not None: result_flag &= True else: result_flag = False print("The device name cannot be None. Use -I to specify device name.") if options.app_package is not None: result_flag &= True else: result_flag = False print("The application package name cannot be None. Use -J to specify application package name.") if options.app_activity is not None: result_flag &= True else: result_flag = False print("The application activity name cannot be None. Use -K to specify application activity name.") if options.device_flag.lower() == 'n': result_flag &= True else: result_flag = False print("The device flag cannot be None. Use -Q to specify device flag.") return result_flag def print_usage(self): "Print the option parser's usage string" print(self.parser.print_usage())
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/email_pytest_report.py
""" Qxf2 Services: Utility script to send pytest test report email * Supports both text and html formatted messages * Supports text, html, image, audio files as an attachment To Do: * Provide support to add multiple attachment Note: * We added subject, email body message as per our need. You can update that as per your requirement. * To generate html formatted test report, you need to use pytest-html plugin. To install it use command: pip install pytest-html * To generate pytest_report.html file use following command from the root of repo e.g. py.test --html = log/pytest_report.html * To generate pytest_report.log file use following command from the root of repo e.g. py.test -k example_form -r F -v > log/pytest_report.log """ import smtplib import os,sys from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.audio import MIMEAudio from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase import mimetypes from email import encoders sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) import conf.email_conf as conf_file class Email_Pytest_Report: "Class to email pytest report" def __init__(self): self.smtp_ssl_host = conf_file.smtp_ssl_host self.smtp_ssl_port = conf_file.smtp_ssl_port self.username = conf_file.username self.password = conf_file.app_password self.sender = conf_file.sender self.targets = conf_file.targets def get_test_report_data(self,html_body_flag= True,report_file_path= 'default'): "get test report data from pytest_report.html or pytest_report.txt or from user provided file" if html_body_flag == True and report_file_path == 'default': #To generate pytest_report.html file use following command e.g. py.test --html = log/pytest_report.html test_report_file = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','log','pytest_report.html'))#Change report file name & address here elif html_body_flag == False and report_file_path == 'default': #To generate pytest_report.log file add ">pytest_report.log" at end of py.test command e.g. py.test -k example_form -r F -v > log/pytest_report.log test_report_file = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','log','pytest_report.log'))#Change report file name & address here else: test_report_file = report_file_path #check file exist or not if not os.path.exists(test_report_file): raise Exception("File '%s' does not exist. Please provide valid file"%test_report_file) with open(test_report_file, "r") as in_file: testdata = "" for line in in_file: testdata = testdata + '\n' + line return testdata def get_attachment(self,attachment_file_path = 'default'): "Get attachment and attach it to mail" if attachment_file_path == 'default': #To generate pytest_report.html file use following command e.g. py.test --html = log/pytest_report.html attachment_report_file = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','log','pytest_report.html'))#Change report file name & address here else: attachment_report_file = attachment_file_path #check file exist or not if not os.path.exists(attachment_report_file): raise Exception("File '%s' does not exist. Please provide valid file"%attachment_report_file) # Guess encoding type ctype, encoding = mimetypes.guess_type(attachment_report_file) if ctype is None or encoding is not None: ctype = 'application/octet-stream' # Use a binary type as guess couldn't made maintype, subtype = ctype.split('/', 1) if maintype == 'text': fp = open(attachment_report_file) attachment = MIMEText(fp.read(), subtype) fp.close() elif maintype == 'image': fp = open(attachment_report_file, 'rb') attachment = MIMEImage(fp.read(), subtype) fp.close() elif maintype == 'audio': fp = open(attachment_report_file, 'rb') attachment = MIMEAudio(fp.read(), subtype) fp.close() else: fp = open(attachment_report_file, 'rb') attachment = MIMEBase(maintype, subtype) attachment.set_payload(fp.read()) fp.close() # Encode the payload using Base64 encoders.encode_base64(attachment) # Set the filename parameter attachment.add_header('Content-Disposition', 'attachment', filename=os.path.basename(attachment_report_file)) return attachment def send_test_report_email(self,html_body_flag = True,attachment_flag = False,report_file_path = 'default'): "send test report email" #1. Get html formatted email body data from report_file_path file (log/pytest_report.html) and do not add it as an attachment if html_body_flag == True and attachment_flag == False: testdata = self.get_test_report_data(html_body_flag,report_file_path) #get html formatted test report data from log/pytest_report.html message = MIMEText(testdata,"html") # Add html formatted test data to email #2. Get text formatted email body data from report_file_path file (log/pytest_report.log) and do not add it as an attachment elif html_body_flag == False and attachment_flag == False: testdata = self.get_test_report_data(html_body_flag,report_file_path) #get html test report data from log/pytest_report.log message = MIMEText(testdata) # Add text formatted test data to email #3. Add html formatted email body message along with an attachment file elif html_body_flag == True and attachment_flag == True: message = MIMEMultipart() #add html formatted body message to email html_body = MIMEText('''<p>Hello,</p> <p>&nbsp; &nbsp; &nbsp; &nbsp; Please check the attachment to see test built report.</p> <p><strong>Note: For best UI experience, download the attachment and open using Chrome browser.</strong></p> ''',"html") # Add/Update email body message here as per your requirement message.attach(html_body) #add attachment to email attachment = self.get_attachment(report_file_path) message.attach(attachment) #4. Add text formatted email body message along with an attachment file else: message = MIMEMultipart() #add test formatted body message to email plain_text_body = MIMEText('''Hello,\n\tPlease check attachment to see test built report. \n\nNote: For best UI experience, download the attachment and open using Chrome browser.''')# Add/Update email body message here as per your requirement message.attach(plain_text_body) #add attachment to email attachment = self.get_attachment(report_file_path) message.attach(attachment) message['From'] = self.sender message['To'] = ', '.join(self.targets) message['Subject'] = 'Script generated test report' # Update email subject here #Send Email server = smtplib.SMTP_SSL(self.smtp_ssl_host, self.smtp_ssl_port) server.login(self.username, self.password) server.sendmail(self.sender, self.targets, message.as_string()) server.quit() #---USAGE EXAMPLES if __name__=='__main__': print("Start of %s"%__file__) #Initialize the Email_Pytest_Report object email_obj = Email_Pytest_Report() #1. Send html formatted email body message with pytest report as an attachment #Here log/pytest_report.html is a default file. To generate pytest_report.html file use following command to the test e.g. py.test --html = log/pytest_report.html email_obj.send_test_report_email(html_body_flag=True,attachment_flag=True,report_file_path= 'default') #Note: We commented below code to avoid sending multiple emails, you can try the other cases one by one to know more about email_pytest_report util. ''' #2. Send html formatted pytest report email_obj.send_test_report_email(html_body_flag=True,attachment_flag=False,report_file_path= 'default') #3. Send plain text formatted pytest report email_obj.send_test_report_email(html_body_flag=False,attachment_flag=False,report_file_path= 'default') #4. Send plain formatted email body message with pytest reports an attachment email_obj.send_test_report_email(html_body_flag=False,attachment_flag=True,report_file_path='default') #5. Send different type of attachment image_file = ("C:\\Users\\Public\\Pictures\\Sample Pictures\\Koala.jpg") # add attachment file here email_obj.send_test_report_email(html_body_flag=False,attachment_flag=True,report_file_path= image_file) '''
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/csv_compare.py
""" Qxf2 Services: Utility script to compare two csv files. """ import csv,os class Csv_Compare(): def is_equal(self,csv_actual,csv_expected): "Method to compare the Actual and Expected csv file" result_flag = True if not os.path.exists(csv_actual): result_flag = False print('Could not locate the csv file: %s'%csv_actual) if not os.path.exists(csv_expected): result_flag = False print('Could not locate the csv file: %s'%csv_expected) if os.path.exists(csv_actual) and os.path.exists(csv_expected): #Open the csv file and put the content to list with open(csv_actual, 'r') as actual_csvfile, open(csv_expected, 'r') as exp_csvfile: reader = csv.reader(actual_csvfile) actual_file = [row for row in reader] reader = csv.reader(exp_csvfile) exp_file = [row for row in reader] if (len(actual_file)!= len(exp_file)): result_flag = False print("Mismatch in number of rows. The actual row count didn't match with expected row count") else: for actual_row, actual_col in zip(actual_file,exp_file): if actual_row == actual_col: pass else: print("Mismatch between actual and expected file at Row: ",actual_file.index(actual_row)) print("Row present only in Actual file: %s"%actual_row) print("Row present only in Expected file: %s"%actual_col) result_flag = False return result_flag #---USAGE EXAMPLES if __name__=='__main__': print("Start of %s"%__file__) #Fill in the file1 and file2 paths file1 = 'Add path for the first file here' file2 = 'Add path for the second file here' #Initialize the csv object csv_obj = Csv_Compare() #Sample code to compare csv files if csv_obj.is_equal(file1,file2) is True: print("Data matched in both the csv files\n") else: print("Data mismatch between the actual and expected csv files")
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/test_path.py
import os,sys import shutil sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from conf import test_path_conf as conf #get details from conf file for POM src_pom_files_list = conf.src_pom_files_list dst_folder_pom = conf.dst_folder_pom #check if POM folder exists and then copy files if os.path.exists(dst_folder_pom): for every_src_pom_file in src_pom_files_list: shutil.copy2(every_src_pom_file,dst_folder_pom)
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/Wrapit.py
""" Class to hold miscellaneous but useful decorators for our framework """ from inspect import getfullargspec from page_objects.Base_Page import Base_Page class Wrapit(): "Wrapit class to hold decorator functions" def _exceptionHandler(f): "Decorator to handle exceptions" argspec = getfullargspec(f) def inner(*args,**kwargs): try: return f(*args,**kwargs) except Exception as e: args[0].write('You have this exception') args[0].write('Exception in method: %s'%str(f.__name__)) args[0].write('PYTHON SAYS: %s'%str(e)) #we denote None as failure case return None return inner def _screenshot(func): "Decorator for taking screenshots" def wrapper(*args,**kwargs): result = func(*args,**kwargs) screenshot_name = '%003d'%args[0].screenshot_counter + '_' + func.__name__ args[0].screenshot_counter += 1 args[0].save_screenshot(screenshot_name) return result return wrapper def _check_browser_console_log(func): "Decorator to check the browser's console log for errors" def wrapper(*args,**kwargs): #As IE driver does not support retrieval of any logs, #we are bypassing the read_browser_console_log() method result = func(*args, **kwargs) if "ie" not in str(args[0].driver): result = func(*args, **kwargs) log_errors = [] new_errors = [] log = args[0].read_browser_console_log() if log != None: for entry in log: if entry['level']=='SEVERE': log_errors.append(entry['message']) if args[0].current_console_log_errors != log_errors: #Find the difference new_errors = list(set(log_errors) - set(args[0].current_console_log_errors)) #Set current_console_log_errors = log_errors args[0].current_console_log_errors = log_errors if len(new_errors)>0: args[0].failure("\nBrowser console error on url: %s\nMethod: %s\nConsole error(s):%s"%(args[0].get_current_url(),func.__name__,'\n----'.join(new_errors))) return result return wrapper _exceptionHandler = staticmethod(_exceptionHandler) _screenshot = staticmethod(_screenshot) _check_browser_console_log = staticmethod(_check_browser_console_log)
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/setup_testrail.py
""" One off utility script to setup TestRail for an automated run This script can: a) Add a milestone if it does not exist b) Add a test run (even without a milestone if needed) c) Add select test cases to the test run using the setup_testrail.conf file d) Write out the latest run id to a 'latest_test_run.txt' file This script will NOT: a) Add a project if it does not exist """ import os,ConfigParser,time from .Test_Rail import Test_Rail from optparse import OptionParser def check_file_exists(file_path): #Check if the config file exists and is a file conf_flag = True if os.path.exists(file_path): if not os.path.isfile(file_path): print('\n****') print('Config file provided is not a file: ') print(file_path) print('****') conf_flag = False else: print('\n****') print('Unable to locate the provided config file: ') print(file_path) print('****') conf_flag = False return conf_flag def check_options(options): "Check if the command line options are valid" result_flag = True if options.test_cases_conf is not None: result_flag = check_file_exists(os.path.abspath(os.path.join(os.path.dirname(__file__),'..','conf',options.test_cases_conf))) return result_flag def save_new_test_run_details(filename,test_run_name,test_run_id): "Write out latest test run name and id" fp = open(filename,'w') fp.write('TEST_RUN_NAME=%s\n'%test_run_name) fp.write('TEST_RUN_ID=%s\n'%str(test_run_id)) fp.close() def setup_testrail(project_name='POM DEMO',milestone_name=None,test_run_name=None,test_cases_conf=None,description=None,name_override_flag='N',case_ids_list=None): "Setup TestRail for an automated run" #1. Get project id #2. if milestone_name is not None # create the milestone if it does not already exist #3. if test_run_name is not None # create the test run if it does not already exist # TO DO: if test_cases_conf is not None -> pass ids as parameters #4. write out test runid to latest_test_run.txt conf_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','conf')) config = ConfigParser.ConfigParser() tr_obj = Test_Rail() #1. Get project id project_id = tr_obj.get_project_id(project_name) if project_id is not None: #i.e., the project exists #2. if milestone_name is not None: # create the milestone if it does not already exist if milestone_name is not None: tr_obj.create_milestone(project_name,milestone_name) #3. if test_run_name is not None # create the test run if it does not already exist # if test_cases_conf is not None -> pass ids as parameters if test_run_name is not None: case_ids = [] #Set the case ids if case_ids_list is not None: #Getting case ids from command line case_ids = case_ids_list.split(',') else: #Getting case ids based on given description(test name) if description is not None: if check_file_exists(os.path.join(conf_dir,test_cases_conf)): config.read(os.path.join(conf_dir,test_cases_conf)) case_ids = config.get(description,'case_ids') case_ids = case_ids.split(',') #Set test_run_name if name_override_flag.lower() == 'y': test_run_name = test_run_name + "-" + time.strftime("%d/%m/%Y/%H:%M:%S") + "_for_" #Use description as test_run_name if description is None: test_run_name = test_run_name + "All" else: test_run_name = test_run_name + str(description) tr_obj.create_test_run(project_name,test_run_name,milestone_name=milestone_name,case_ids=case_ids,description=description) run_id = tr_obj.get_run_id(project_name,test_run_name) save_new_test_run_details(os.path.join(conf_dir,'latest_test_run.txt'),test_run_name,run_id) else: print('Project does not exist: ',project_name) print('Stopping the script without doing anything.') #---START OF SCRIPT if __name__=='__main__': #This script takes an optional command line argument for the TestRail run id usage = '\n----\n%prog -p <OPTIONAL: Project name> -m <OPTIONAL: milestone_name> -r <OPTIONAL: Test run name> -t <OPTIONAL: test cases conf file> -d <OPTIONAL: Test run description>\n----\nE.g.: %prog -p "Secure Code Warrior - Test" -m "Pilot NetCetera" -r commit_id -t setup_testrail.conf -d Registration\n---' parser = OptionParser(usage=usage) parser.add_option("-p","--project", dest="project_name", default="POM DEMO", help="Project name") parser.add_option("-m","--milestone", dest="milestone_name", default=None, help="Milestone name") parser.add_option("-r","--test_run_name", dest="test_run_name", default=None, help="Test run name") parser.add_option("-t","--test_cases_conf", dest="test_cases_conf", default="setup_testrail.conf", help="Test cases conf listing test names and ids you want added") parser.add_option("-d","--test_run_description", dest="test_run_description", default=None, help="The name of the test Registration_Tests/Intro_Run_Tests/Sales_Demo_Tests") parser.add_option("-n","--name_override_flag", dest="name_override_flag", default="Y", help="Y or N. 'N' if you don't want to override the default test_run_name") parser.add_option("-c","--case_ids_list", dest="case_ids_list", default=None, help="Pass all case ids with comma separated you want to add in test run") (options,args) = parser.parse_args() #Run the script only if the options are valid if check_options(options): setup_testrail(project_name=options.project_name, milestone_name=options.milestone_name, test_run_name=options.test_run_name, test_cases_conf=options.test_cases_conf, description=options.test_run_description, name_override_flag=options.name_override_flag, case_ids_list=options.case_ids_list) else: print('ERROR: Received incorrect input arguments') print(parser.print_usage())
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/utils/copy_framework_template.py
""" This script would copy the required framework files from the input source to the input destination given by the user. 1. Copy files from POM to the newly created destination directory. 2. Verify if the destination directory is created and create the sub-folder to copy files from POM\Conf. 3. Verify if the destination directory is created and create the sub-folder to copy files from POM\Page_Objects. 4. Verify if the destination directory is created and create the sub-folder to copy files from POM\Utils. """ import os,sys import shutil from optparse import OptionParser sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from conf import copy_framework_template_conf as conf def copy_framework_template(src_folder,dst_folder): "run the test" #1. Copy files from POM to the newly created destination directory. #1a. Get details from conf file src_files_list = conf.src_files_list #1b. Create the new destination directory os.makedirs(dst_folder) #1c. Check if destination folder exists and then copy files if os.path.exists(dst_folder): for every_src_file in src_files_list: shutil.copy2(every_src_file,dst_folder) #2. Verify if the destination directory is created and create the sub-folder to copy files from POM\Conf. #2a. Get details from conf file for Conf src_conf_files_list = conf.src_conf_files_list dst_folder_conf = conf.dst_folder_conf #2b. Create the conf sub-folder if os.path.exists(dst_folder): os.mkdir(dst_folder_conf) #2c. Check if conf folder exists and then copy files if os.path.exists(dst_folder_conf): for every_src_conf_file in src_conf_files_list: shutil.copy2(every_src_conf_file,dst_folder_conf) #3. Verify if the destination directory is created and create the sub-folder to copy files from POM\Page_Objects. #3a. Get details from conf file for Page_Objects src_page_objects_files_list = conf.src_page_objects_files_list dst_folder_page_objects = conf.dst_folder_page_objects #3b. Create the page_object sub-folder if os.path.exists(dst_folder): os.mkdir(dst_folder_page_objects) #3c. Check if page_object folder exists and then copy files if os.path.exists(dst_folder_page_objects): for every_src_page_objects_file in src_page_objects_files_list: shutil.copy2(every_src_page_objects_file,dst_folder_page_objects) #4. Verify if the destination directory is created and create the sub-folder to copy files from POM\Utils. #4a. Get details from conf file for Utils folder src_utils_files_list = conf.src_utils_files_list dst_folder_utils = conf.dst_folder_utils #4b. Create the utils destination directory if os.path.exists(dst_folder): os.mkdir(dst_folder_utils) #4c. Check if utils folder exists and then copy files if os.path.exists(dst_folder_utils): for every_src_utils_file in src_utils_files_list: shutil.copy2(every_src_utils_file,dst_folder_utils) #---START OF SCRIPT if __name__=='__main__': #run the test parser=OptionParser() parser.add_option("-s","--source",dest="src",help="The name of the source folder: ie, POM",default="POM") parser.add_option("-d","--destination",dest="dst",help="The name of the destination folder: ie, client name",default="Myntra") (options,args) = parser.parse_args() copy_framework_template(options.src,options.dst)
0
qxf2_public_repos/makemework/utils
qxf2_public_repos/makemework/utils/gmail/__init__.py
""" GMail! Woo! """ __title__ = 'gmail' __version__ = '0.1' __author__ = 'Charlie Guo' __build__ = 0x0001 __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2013 Charlie Guo' from .gmail import Gmail from .mailbox import Mailbox from .message import Message from .exceptions import GmailException, ConnectionError, AuthenticationError from .utils import login, authenticate
0
qxf2_public_repos/makemework/utils
qxf2_public_repos/makemework/utils/gmail/message.py
import datetime import email import re import time import os from email.header import decode_header, make_header from imaplib import ParseFlags class Message(): def __init__(self, mailbox, uid): self.uid = uid self.mailbox = mailbox self.gmail = mailbox.gmail if mailbox else None self.message = None self.headers = {} self.subject = None self.body = None self.html = None self.to = None self.fr = None self.cc = None self.delivered_to = None self.sent_at = None self.flags = [] self.labels = [] self.thread_id = None self.thread = [] self.message_id = None self.attachments = None def is_read(self): return ('\\Seen' in self.flags) def read(self): flag = '\\Seen' self.gmail.imap.uid('STORE', self.uid, '+FLAGS', flag) if flag not in self.flags: self.flags.append(flag) def unread(self): flag = '\\Seen' self.gmail.imap.uid('STORE', self.uid, '-FLAGS', flag) if flag in self.flags: self.flags.remove(flag) def is_starred(self): return ('\\Flagged' in self.flags) def star(self): flag = '\\Flagged' self.gmail.imap.uid('STORE', self.uid, '+FLAGS', flag) if flag not in self.flags: self.flags.append(flag) def unstar(self): flag = '\\Flagged' self.gmail.imap.uid('STORE', self.uid, '-FLAGS', flag) if flag in self.flags: self.flags.remove(flag) def is_draft(self): return ('\\Draft' in self.flags) def has_label(self, label): full_label = '%s' % label return (full_label in self.labels) def add_label(self, label): full_label = '%s' % label self.gmail.imap.uid('STORE', self.uid, '+X-GM-LABELS', full_label) if full_label not in self.labels: self.labels.append(full_label) def remove_label(self, label): full_label = '%s' % label self.gmail.imap.uid('STORE', self.uid, '-X-GM-LABELS', full_label) if full_label in self.labels: self.labels.remove(full_label) def is_deleted(self): return ('\\Deleted' in self.flags) def delete(self): flag = '\\Deleted' self.gmail.imap.uid('STORE', self.uid, '+FLAGS', flag) if flag not in self.flags: self.flags.append(flag) trash = '[Gmail]/Trash' if '[Gmail]/Trash' in self.gmail.labels() else '[Gmail]/Bin' if self.mailbox.name not in ['[Gmail]/Bin', '[Gmail]/Trash']: self.move_to(trash) # def undelete(self): # flag = '\\Deleted' # self.gmail.imap.uid('STORE', self.uid, '-FLAGS', flag) # if flag in self.flags: self.flags.remove(flag) def move_to(self, name): self.gmail.copy(self.uid, name, self.mailbox.name) if name not in ['[Gmail]/Bin', '[Gmail]/Trash']: self.delete() def archive(self): self.move_to('[Gmail]/All Mail') def parse_headers(self, message): hdrs = {} for hdr in message.keys(): hdrs[hdr] = message[hdr] return hdrs def parse_flags(self, headers): return list(ParseFlags(headers)) # flags = re.search(r'FLAGS \(([^\)]*)\)', headers).groups(1)[0].split(' ') def parse_labels(self, headers): if re.search(r'X-GM-LABELS \(([^\)]+)\)', headers): labels = re.search(r'X-GM-LABELS \(([^\)]+)\)', headers).groups(1)[0].split(' ') return map(lambda l: l.replace('"', '').decode("string_escape"), labels) else: return list() def parse_subject(self, encoded_subject): dh = decode_header(encoded_subject) default_charset = 'ASCII' return ''.join([ unicode(t[0], t[1] or default_charset) for t in dh ]) def parse(self, raw_message): raw_headers = raw_message[0] raw_email = raw_message[1] self.message = email.message_from_string(raw_email) self.headers = self.parse_headers(self.message) self.to = self.message['to'] self.fr = self.message['from'] self.delivered_to = self.message['delivered_to'] self.subject = self.parse_subject(self.message['subject']) if self.message.get_content_maintype() == "multipart": for content in self.message.walk(): if content.get_content_type() == "text/plain": self.body = content.get_payload(decode=True) elif content.get_content_type() == "text/html": self.html = content.get_payload(decode=True) elif self.message.get_content_maintype() == "text": self.body = self.message.get_payload() self.sent_at = datetime.datetime.fromtimestamp(time.mktime(email.utils.parsedate_tz(self.message['date'])[:9])) self.flags = self.parse_flags(raw_headers) self.labels = self.parse_labels(raw_headers) if re.search(r'X-GM-THRID (\d+)', raw_headers): self.thread_id = re.search(r'X-GM-THRID (\d+)', raw_headers).groups(1)[0] if re.search(r'X-GM-MSGID (\d+)', raw_headers): self.message_id = re.search(r'X-GM-MSGID (\d+)', raw_headers).groups(1)[0] # Parse attachments into attachment objects array for this message self.attachments = [ Attachment(attachment) for attachment in self.message._payload if not isinstance(attachment, basestring) and attachment.get('Content-Disposition') is not None ] def fetch(self): if not self.message: response, results = self.gmail.imap.uid('FETCH', self.uid, '(BODY.PEEK[] FLAGS X-GM-THRID X-GM-MSGID X-GM-LABELS)') self.parse(results[0]) return self.message # returns a list of fetched messages (both sent and received) in chronological order def fetch_thread(self): self.fetch() original_mailbox = self.mailbox self.gmail.use_mailbox(original_mailbox.name) # fetch and cache messages from inbox or other received mailbox response, results = self.gmail.imap.uid('SEARCH', None, '(X-GM-THRID ' + self.thread_id + ')') received_messages = {} uids = results[0].split(' ') if response == 'OK': for uid in uids: received_messages[uid] = Message(original_mailbox, uid) self.gmail.fetch_multiple_messages(received_messages) self.mailbox.messages.update(received_messages) # fetch and cache messages from 'sent' self.gmail.use_mailbox('[Gmail]/Sent Mail') response, results = self.gmail.imap.uid('SEARCH', None, '(X-GM-THRID ' + self.thread_id + ')') sent_messages = {} uids = results[0].split(' ') if response == 'OK': for uid in uids: sent_messages[uid] = Message(self.gmail.mailboxes['[Gmail]/Sent Mail'], uid) self.gmail.fetch_multiple_messages(sent_messages) self.gmail.mailboxes['[Gmail]/Sent Mail'].messages.update(sent_messages) self.gmail.use_mailbox(original_mailbox.name) # combine and sort sent and received messages return sorted(dict(received_messages.items() + sent_messages.items()).values(), key=lambda m: m.sent_at) class Attachment: def __init__(self, attachment): self.name = attachment.get_filename() # Raw file data self.payload = attachment.get_payload(decode=True) # Filesize in kilobytes self.size = int(round(len(self.payload)/1000.0)) def save(self, path=None): if path is None: # Save as name of attachment if there is no path specified path = self.name elif os.path.isdir(path): # If the path is a directory, save as name of attachment in that directory path = os.path.join(path, self.name) with open(path, 'wb') as f: f.write(self.payload)
0
qxf2_public_repos/makemework/utils
qxf2_public_repos/makemework/utils/gmail/gmail.py
from __future__ import absolute_import import re import imaplib from .mailbox import Mailbox from .utf import encode as encode_utf7, decode as decode_utf7 from .exceptions import * class Gmail(): # GMail IMAP defaults GMAIL_IMAP_HOST = 'imap.gmail.com' GMAIL_IMAP_PORT = 993 # GMail SMTP defaults # TODO: implement SMTP functions GMAIL_SMTP_HOST = "smtp.gmail.com" GMAIL_SMTP_PORT = 587 def __init__(self): self.username = None self.password = None self.access_token = None self.imap = None self.smtp = None self.logged_in = False self.mailboxes = {} self.current_mailbox = None # self.connect() def connect(self, raise_errors=True): # try: # self.imap = imaplib.IMAP4_SSL(self.GMAIL_IMAP_HOST, self.GMAIL_IMAP_PORT) # except socket.error: # if raise_errors: # raise Exception('Connection failure.') # self.imap = None self.imap = imaplib.IMAP4_SSL(self.GMAIL_IMAP_HOST, self.GMAIL_IMAP_PORT) # self.smtp = smtplib.SMTP(self.server,self.port) # self.smtp.set_debuglevel(self.debug) # self.smtp.ehlo() # self.smtp.starttls() # self.smtp.ehlo() return self.imap def fetch_mailboxes(self): response, mailbox_list = self.imap.list() if response == 'OK': for mailbox in mailbox_list: mailbox_name = mailbox.split('"/"')[-1].replace('"', '').strip() mailbox = Mailbox(self) mailbox.external_name = mailbox_name self.mailboxes[mailbox_name] = mailbox def use_mailbox(self, mailbox): if mailbox: self.imap.select(mailbox) self.current_mailbox = mailbox def mailbox(self, mailbox_name): if mailbox_name not in self.mailboxes: mailbox_name = encode_utf7(mailbox_name) mailbox = self.mailboxes.get(mailbox_name) if mailbox and not self.current_mailbox == mailbox_name: self.use_mailbox(mailbox_name) return mailbox def create_mailbox(self, mailbox_name): mailbox = self.mailboxes.get(mailbox_name) if not mailbox: self.imap.create(mailbox_name) mailbox = Mailbox(self, mailbox_name) self.mailboxes[mailbox_name] = mailbox return mailbox def delete_mailbox(self, mailbox_name): mailbox = self.mailboxes.get(mailbox_name) if mailbox: self.imap.delete(mailbox_name) del self.mailboxes[mailbox_name] def login(self, username, password): self.username = username self.password = password if not self.imap: self.connect() try: imap_login = self.imap.login(self.username, self.password) self.logged_in = (imap_login and imap_login[0] == 'OK') if self.logged_in: self.fetch_mailboxes() except imaplib.IMAP4.error: raise AuthenticationError # smtp_login(username, password) return self.logged_in def authenticate(self, username, access_token): self.username = username self.access_token = access_token if not self.imap: self.connect() try: auth_string = 'user=%s\1auth=Bearer %s\1\1' % (username, access_token) imap_auth = self.imap.authenticate('XOAUTH2', lambda x: auth_string) self.logged_in = (imap_auth and imap_auth[0] == 'OK') if self.logged_in: self.fetch_mailboxes() except imaplib.IMAP4.error: raise AuthenticationError return self.logged_in def logout(self): self.imap.logout() self.logged_in = False def label(self, label_name): return self.mailbox(label_name) def find(self, mailbox_name="[Gmail]/All Mail", **kwargs): box = self.mailbox(mailbox_name) return box.mail(**kwargs) def copy(self, uid, to_mailbox, from_mailbox=None): if from_mailbox: self.use_mailbox(from_mailbox) self.imap.uid('COPY', uid, to_mailbox) def fetch_multiple_messages(self, messages): fetch_str = ','.join(messages.keys()) response, results = self.imap.uid('FETCH', fetch_str, '(BODY.PEEK[] FLAGS X-GM-THRID X-GM-MSGID X-GM-LABELS)') for index in xrange(len(results) - 1): raw_message = results[index] if re.search(r'UID (\d+)', raw_message[0]): uid = re.search(r'UID (\d+)', raw_message[0]).groups(1)[0] messages[uid].parse(raw_message) return messages def labels(self, require_unicode=False): keys = self.mailboxes.keys() if require_unicode: keys = [decode_utf7(key) for key in keys] return keys def inbox(self): return self.mailbox("INBOX") def spam(self): return self.mailbox("[Gmail]/Spam") def starred(self): return self.mailbox("[Gmail]/Starred") def all_mail(self): return self.mailbox("[Gmail]/All Mail") def sent_mail(self): return self.mailbox("[Gmail]/Sent Mail") def important(self): return self.mailbox("[Gmail]/Important") def mail_domain(self): return self.username.split('@')[-1]
0
qxf2_public_repos/makemework/utils
qxf2_public_repos/makemework/utils/gmail/utils.py
from .gmail import Gmail def login(username, password): gmail = Gmail() gmail.login(username, password) return gmail def authenticate(username, access_token): gmail = Gmail() gmail.authenticate(username, access_token) return gmail
0
qxf2_public_repos/makemework/utils
qxf2_public_repos/makemework/utils/gmail/mailbox.py
from .message import Message from .utf import encode as encode_utf7, decode as decode_utf7 class Mailbox(): def __init__(self, gmail, name="INBOX"): self.name = name self.gmail = gmail self.date_format = "%d-%b-%Y" self.messages = {} @property def external_name(self): if "external_name" not in vars(self): vars(self)["external_name"] = encode_utf7(self.name) return vars(self)["external_name"] @external_name.setter def external_name(self, value): if "external_name" in vars(self): del vars(self)["external_name"] self.name = decode_utf7(value) def mail(self, prefetch=False, **kwargs): search = ['ALL'] kwargs.get('read') and search.append('SEEN') kwargs.get('unread') and search.append('UNSEEN') kwargs.get('starred') and search.append('FLAGGED') kwargs.get('unstarred') and search.append('UNFLAGGED') kwargs.get('deleted') and search.append('DELETED') kwargs.get('undeleted') and search.append('UNDELETED') kwargs.get('draft') and search.append('DRAFT') kwargs.get('undraft') and search.append('UNDRAFT') kwargs.get('before') and search.extend(['BEFORE', kwargs.get('before').strftime(self.date_format)]) kwargs.get('after') and search.extend(['SINCE', kwargs.get('after').strftime(self.date_format)]) kwargs.get('on') and search.extend(['ON', kwargs.get('on').strftime(self.date_format)]) kwargs.get('header') and search.extend(['HEADER', kwargs.get('header')[0], kwargs.get('header')[1]]) kwargs.get('sender') and search.extend(['FROM', kwargs.get('sender')]) kwargs.get('fr') and search.extend(['FROM', kwargs.get('fr')]) kwargs.get('to') and search.extend(['TO', kwargs.get('to')]) kwargs.get('cc') and search.extend(['CC', kwargs.get('cc')]) kwargs.get('subject') and search.extend(['SUBJECT', kwargs.get('subject')]) kwargs.get('body') and search.extend(['BODY', kwargs.get('body')]) kwargs.get('label') and search.extend(['X-GM-LABELS', kwargs.get('label')]) kwargs.get('attachment') and search.extend(['HAS', 'attachment']) kwargs.get('query') and search.extend([kwargs.get('query')]) emails = [] # print search response, data = self.gmail.imap.uid('SEARCH', *search) if response == 'OK': uids = filter(None, data[0].split(' ')) # filter out empty strings for uid in uids: if not self.messages.get(uid): self.messages[uid] = Message(self, uid) emails.append(self.messages[uid]) if prefetch and emails: messages_dict = {} for email in emails: messages_dict[email.uid] = email self.messages.update(self.gmail.fetch_multiple_messages(messages_dict)) return emails # WORK IN PROGRESS. NOT FOR ACTUAL USE def threads(self, prefetch=False, **kwargs): emails = [] response, data = self.gmail.imap.uid('SEARCH', 'ALL') if response == 'OK': uids = data[0].split(' ') for uid in uids: if not self.messages.get(uid): self.messages[uid] = Message(self, uid) emails.append(self.messages[uid]) if prefetch: fetch_str = ','.join(uids) response, results = self.gmail.imap.uid('FETCH', fetch_str, '(BODY.PEEK[] FLAGS X-GM-THRID X-GM-MSGID X-GM-LABELS)') for index in xrange(len(results) - 1): raw_message = results[index] if re.search(r'UID (\d+)', raw_message[0]): uid = re.search(r'UID (\d+)', raw_message[0]).groups(1)[0] self.messages[uid].parse(raw_message) return emails def count(self, **kwargs): return len(self.mail(**kwargs)) def cached_messages(self): return self.messages
0
qxf2_public_repos/makemework/utils
qxf2_public_repos/makemework/utils/gmail/exceptions.py
# -*- coding: utf-8 -*- """ gmail.exceptions ~~~~~~~~~~~~~~~~~~~ This module contains the set of Gmails' exceptions. """ class GmailException(RuntimeError): """There was an ambiguous exception that occurred while handling your request.""" class ConnectionError(GmailException): """A Connection error occurred.""" class AuthenticationError(GmailException): """Gmail Authentication failed.""" class Timeout(GmailException): """The request timed out."""
0
qxf2_public_repos/makemework/utils
qxf2_public_repos/makemework/utils/gmail/utf.py
# The contents of this file has been derived code from the Twisted project # (http://twistedmatrix.com/). The original author is Jp Calderone. # Twisted project license follows: # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. text_type = unicode binary_type = str PRINTABLE = set(range(0x20, 0x26)) | set(range(0x27, 0x7f)) def encode(s): """Encode a folder name using IMAP modified UTF-7 encoding. Despite the function's name, the output is still a unicode string. """ if not isinstance(s, text_type): return s r = [] _in = [] def extend_result_if_chars_buffered(): if _in: r.extend(['&', modified_utf7(''.join(_in)), '-']) del _in[:] for c in s: if ord(c) in PRINTABLE: extend_result_if_chars_buffered() r.append(c) elif c == '&': extend_result_if_chars_buffered() r.append('&-') else: _in.append(c) extend_result_if_chars_buffered() return ''.join(r) def decode(s): """Decode a folder name from IMAP modified UTF-7 encoding to unicode. Despite the function's name, the input may still be a unicode string. If the input is bytes, it's first decoded to unicode. """ if isinstance(s, binary_type): s = s.decode('latin-1') if not isinstance(s, text_type): return s r = [] _in = [] for c in s: if c == '&' and not _in: _in.append('&') elif c == '-' and _in: if len(_in) == 1: r.append('&') else: r.append(modified_deutf7(''.join(_in[1:]))) _in = [] elif _in: _in.append(c) else: r.append(c) if _in: r.append(modified_deutf7(''.join(_in[1:]))) return ''.join(r) def modified_utf7(s): # encode to utf-7: '\xff' => b'+AP8-', decode from latin-1 => '+AP8-' s_utf7 = s.encode('utf-7').decode('latin-1') return s_utf7[1:-1].replace('/', ',') def modified_deutf7(s): s_utf7 = '+' + s.replace(',', '/') + '-' # encode to latin-1: '+AP8-' => b'+AP8-', decode from utf-7 => '\xff' return s_utf7.encode('latin-1').decode('utf-7')
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/page_objects/Base_Page.py
""" Page class that all page models can inherit from There are useful wrappers for common Selenium operations """ from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains import unittest,time,logging,os,inspect,utils.Test_Rail from utils.Base_Logging import Base_Logging from inspect import getargspec from utils.BrowserStack_Library import BrowserStack_Library from .DriverFactory import DriverFactory from page_objects import PageFactory from utils.Custom_Exceptions import Stop_Test_Exception from utils.Test_Rail import Test_Rail from conf import remote_credentials as Conf class Borg: #The borg design pattern is to share state #Src: http://code.activestate.com/recipes/66531/ __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state def is_first_time(self): "Has the child class been invoked before?" result_flag = False if len(self.__dict__)==0: result_flag = True return result_flag class Base_Page(Borg,unittest.TestCase): "Page class that all page models can inherit from" def __init__(self,base_url='http://qxf2.com/',trailing_slash_flag=True): "Constructor" Borg.__init__(self) if self.is_first_time(): #Do these actions if this the first time this class is initialized self.set_directory_structure() self.image_url_list = [] self.msg_list = [] self.current_console_log_errors = [] self.window_structure = {} self.testrail_flag = False self.images = [] self.browserstack_flag = False self.reset() #We assume relative URLs start without a / in the beginning if base_url[-1] != '/' and trailing_slash_flag is True: base_url += '/' self.base_url = base_url self.driver_obj = DriverFactory() if self.driver is not None: self.start() #Visit and initialize xpaths for the appropriate page def reset(self): "Reset the base page object" self.driver = None self.result_counter = 0 #Increment whenever success or failure are called self.pass_counter = 0 #Increment everytime success is called self.mini_check_counter = 0 #Increment when conditional_write is called self.mini_check_pass_counter = 0 #Increment when conditional_write is called with True self.failure_message_list = [] self.screenshot_counter = 1 self.exceptions = [] def get_failure_message_list(self): "Return the failure message list" return self.failure_message_list def switch_page(self,page_name): "Switch the underlying class to the required Page" self.__class__ = PageFactory.PageFactory.get_page_object(page_name,base_url=self.base_url).__class__ def register_driver(self,remote_flag,os_name,os_version,browser,browser_version,remote_project_name,remote_build_name): "Register the driver with Page" self.set_screenshot_dir(os_name,os_version,browser,browser_version) # Create screenshot directory self.set_log_file() self.driver = self.driver_obj.get_web_driver(remote_flag,os_name,os_version,browser,browser_version,remote_project_name,remote_build_name) self.driver.implicitly_wait(5) self.driver.maximize_window() if Conf.REMOTE_BROWSER_PLATFORM == 'BS' and remote_flag.lower() == 'y': self.register_browserstack() self.session_url = self.browserstack_obj.get_session_url() self.browserstack_msg = 'BrowserStack session URL:' self.write( self.browserstack_msg + '\n' + str(self.session_url)) self.start() def get_current_driver(self): "Return current driver" return self.driver def register_testrail(self): "Register TestRail with Page" self.testrail_flag = True self.tr_obj = Test_Rail() def register_browserstack(self): "Register Browser Stack with Page" self.browserstack_flag = True self.browserstack_obj = BrowserStack_Library() def get_calling_module(self): "Get the name of the calling module" calling_file = inspect.stack()[-1][1] if 'runpy' or 'string' in calling_file: calling_file = inspect.stack()[4][3] calling_filename = calling_file.split(os.sep) #This logic bought to you by windows + cygwin + git bash if len(calling_filename) == 1: #Needed for calling_filename = calling_file.split('/') self.calling_module = calling_filename[-1].split('.')[0] return self.calling_module def set_directory_structure(self): "Setup the required directory structure if it is not already present" try: self.screenshots_parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','screenshots')) if not os.path.exists(self.screenshots_parent_dir): os.makedirs(self.screenshots_parent_dir) self.logs_parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','log')) if not os.path.exists(self.logs_parent_dir): os.makedirs(self.logs_parent_dir) except Exception as e: self.write("Exception when trying to set directory structure") self.write(str(e)) self.exceptions.append("Error when setting up the directory structure") def set_screenshot_dir(self,os_name,os_version,browser,browser_version): "Set the screenshot directory" try: self.screenshot_dir = self.get_screenshot_dir(os_name,os_version,browser,browser_version,overwrite_flag=True) if not os.path.exists(self.screenshot_dir): os.makedirs(self.screenshot_dir) except Exception as e: self.write("Exception when trying to set screenshot directory") self.write(str(e)) self.exceptions.append("Error when setting up the screenshot directory") def get_screenshot_dir(self,os_name,os_version,browser,browser_version,overwrite_flag=False): "Get the name of the test" if os_name == 'OS X': os_name = 'OS_X' if isinstance(os_name,list): windows_browser_combination = browser.lower() else: windows_browser_combination = os_name.lower() + '_' + str(os_version).lower() + '_' + browser.lower()+ '_' + str(browser_version) self.testname = self.get_calling_module() self.testname =self.testname.replace('<','') self.testname =self.testname.replace('>','') self.testname = self.testname + '[' + str(windows_browser_combination)+ ']' self.screenshot_dir = self.screenshots_parent_dir + os.sep + self.testname if os.path.exists(self.screenshot_dir) and overwrite_flag is True: for i in range(1,4096): if os.path.exists(self.screenshot_dir + '_'+str(i)): continue else: os.rename(self.screenshot_dir,self.screenshot_dir +'_'+str(i)) break return self.screenshot_dir def set_log_file(self): 'set the log file' self.log_name = self.testname + '.log' self.log_obj = Base_Logging(log_file_name=self.log_name,level=logging.DEBUG) def append_latest_image(self,screenshot_name): "Get image url list from Browser Stack" screenshot_url = self.browserstack_obj.get_latest_screenshot_url() image_dict = {} image_dict['name'] = screenshot_name image_dict['url'] = screenshot_url self.image_url_list.append(image_dict) def save_screenshot(self,screenshot_name,pre_format=" #Debug screenshot: "): "Take a screenshot" if os.path.exists(self.screenshot_dir + os.sep + screenshot_name+'.png'): for i in range(1,100): if os.path.exists(self.screenshot_dir + os.sep +screenshot_name+'_'+str(i)+'.png'): continue else: os.rename(self.screenshot_dir + os.sep +screenshot_name+'.png',self.screenshot_dir + os.sep +screenshot_name+'_'+str(i)+'.png') break self.driver.get_screenshot_as_file(self.screenshot_dir + os.sep+ screenshot_name+'.png') #self.conditional_write(flag=True,positive= screenshot_name + '.png',negative='', pre_format=pre_format) if self.browserstack_flag is True: self.append_latest_image(screenshot_name) def open(self,url,wait_time=2): "Visit the page base_url + url" url = self.base_url + url if self.driver.current_url != url: self.driver.get(url) self.wait(wait_time) def get_current_url(self): "Get the current URL" return self.driver.current_url def get_page_paths(self,section): "Open configurations file,go to right sections,return section obj" pass def get_current_window_handle(self): "Return the latest window handle" return self.driver.current_window_handle def set_window_name(self,name): "Set the name of the current window name" try: window_handle = self.get_current_window_handle() self.window_structure[window_handle] = name except Exception as e: self.write("Exception when trying to set windows name") self.write(str(e)) self.exceptions.append("Error when setting up the name of the current window") def get_window_by_name(self,window_name): "Return window handle id based on name" window_handle_id = None for id,name in self.window_structure.iteritems(): if name == window_name: window_handle_id = id break return window_handle_id def switch_window(self,name=None): "Make the driver switch to the last window or a window with a name" result_flag = False try: if name is not None: window_handle_id = self.get_window_by_name(name) else: window_handle_id = self.driver.window_handles[-1] if window_handle_id is not None: self.driver.switch_to_window(window_handle_id) result_flag = True self.conditional_write(result_flag, 'Automation switched to the browser window: %s'%name, 'Unable to locate and switch to the window with name: %s'%name, level='debug') except Exception as e: self.write("Exception when trying to switch window") self.write(str(e)) self.exceptions.append("Error when switching browser window") return result_flag def close_current_window(self): "Close the current window" result_flag = False try: before_window_count = len(self.get_window_handles()) self.driver.close() after_window_count = len(self.get_window_handles()) if (before_window_count - after_window_count) == 1: result_flag = True except Exception as e: self.write('Could not close the current window') self.write(str(e)) self.exceptions.append("Error when trying to close the current window") return result_flag def get_window_handles(self): "Get the window handles" return self.driver.window_handles def get_current_window_handle(self): "Get the current window handle" pass def _get_locator(key): "fetches locator from the locator conf" value = None try: path_conf_file = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'conf', 'locators.conf')) if path_conf_file is not None: value = Conf_Reader.get_value(path_conf_file, key) except Exception as e: print (str(e)) self.exceptions.append("Error when fetching locator from the locator.conf") return value def get_element(self,locator,verbose_flag=True): "Return the DOM element of the path or 'None' if the element is not found " dom_element = None try: locator = self.split_locator(locator) dom_element = self.driver.find_element(*locator) except Exception as e: if verbose_flag is True: self.write(str(e),'debug') self.write("Check your locator-'%s,%s' in the conf/locators.conf file" %(locator[0],locator[1])) self.exceptions.append("Check your locator-'%s,%s' in the conf/locators.conf file" %(locator[0],locator[1])) return dom_element def split_locator(self,locator): "Split the locator type and locator" result = () try: result = tuple(locator.split(',',1)) except Exception as e: self.write("Error while parsing locator") self.exceptions.append("Unable to split the locator-'%s' in the conf/locators.conf file"%(locator[0],locator[1])) return result def get_elements(self,locator,msg_flag=True): "Return a list of DOM elements that match the locator" dom_elements = [] try: locator = self.split_locator(locator) dom_elements = self.driver.find_elements(*locator) except Exception as e: if msg_flag==True: self.write(str(e),'debug') self.write("Check your locator-'%s,%s' in the conf/locators.conf file" %(locator[0],locator[1])) self.exceptions.append("Unable to locate the element with the xpath -'%s,%s' in the conf/locators.conf file"%(locator[0],locator[1])) return dom_elements def click_element(self,locator,wait_time=3): "Click the button supplied" result_flag = False try: link = self.get_element(locator) if link is not None: link.click() result_flag=True self.wait(wait_time) except Exception as e: self.write(str(e),'debug') self.write('Exception when clicking link with path: %s'%locator) self.exceptions.append("Error when clicking the element with path,'%s' in the conf/locators.conf file"%locator) return result_flag def set_text(self,locator,value,clear_flag=True): "Set the value of the text field" text_field = None try: text_field = self.get_element(locator) if text_field is not None and clear_flag is True: try: text_field.clear() except Exception as e: self.write(str(e),'debug') self.exceptions.append("Could not clear the text field- '%s' in the conf/locators.conf file"%locator) except Exception as e: self.write("Check your locator-'%s,%s' in the conf/locators.conf file" %(locator[0],locator[1])) result_flag = False if text_field is not None: try: text_field.send_keys(value) result_flag = True except Exception as e: self.write('Could not write to text field: %s'%locator,'debug') self.write(str(e),'debug') self.exceptions.append("Could not write to text field- '%s' in the conf/locators.conf file"%locator) return result_flag def get_text(self,locator): "Return the text for a given path or the 'None' object if the element is not found" text = '' try: text = self.get_element(locator).text except Exception as e: self.write(e) self.exceptions.append("Error when getting text from the path-'%s' in the conf/locators.conf file"%locator) return None else: return text.encode('utf-8') def get_dom_text(self,dom_element): "Return the text of a given DOM element or the 'None' object if the element has no attribute called text" text = None try: text = dom_element.text text = text.encode('utf-8') except Exception as e: self.write(e) self.exceptions.append("Error when getting text from the DOM element-'%s' in the conf/locators.conf file"%locator) return text def select_checkbox(self,locator): "Select a checkbox if not already selected" result_flag = False try: checkbox = self.get_element(locator) if checkbox.is_selected() is False: result_flag = self.toggle_checkbox(locator) else: result_flag = True except Exception as e: self.write(e) self.exceptions.append("Error when selecting checkbox-'%s' in the conf/locators.conf file"%locator) return result_flag def deselect_checkbox(self,locator): "Deselect a checkbox if it is not already deselected" result_flag = False try: checkbox = self.get_element(locator) if checkbox.is_selected() is True: result_flag = self.toggle_checkbox(locator) else: result_flag = True except Exception as e: self.write(e) self.exceptions.append("Error when deselecting checkbox-'%s' in the conf/locators.conf file"%locator) return result_flag unselect_checkbox = deselect_checkbox #alias the method def toggle_checkbox(self,locator): "Toggle a checkbox" try: return self.click_element(locator) except Exception as e: self.write(e) self.exceptions.append("Error when toggling checkbox-'%s' in the conf/locators.conf file"%locator) def select_dropdown_option(self, locator, option_text): "Selects the option in the drop-down" result_flag= False try: dropdown = self.get_element(locator) for option in dropdown.find_elements_by_tag_name('option'): if option.text == option_text: option.click() result_flag = True break except Exception as e: self.write(e) self.exceptions.append("Error when selecting option from the drop-down '%s' "%locator) return result_flag def check_element_present(self,locator): "This method checks if the web element is present in page or not and returns True or False accordingly" result_flag = False if self.get_element(locator,verbose_flag=False) is not None: result_flag = True return result_flag def check_element_displayed(self,locator): "This method checks if the web element is present in page or not and returns True or False accordingly" result_flag = False try: if self.get_element(locator) is not None: element = self.get_element(locator,verbose_flag=False) if element.is_displayed() is True: result_flag = True except Exception as e: self.write(e) self.exceptions.append("Web element not present in the page, please check the locator is correct -'%s' in the conf/locators.conf file"%locator) return result_flag def hit_enter(self,locator,wait_time=2): "Hit enter" try: element = self.get_element(locator) element.send_keys(Keys.ENTER) self.wait(wait_time) except Exception as e: self.write(str(e),'debug') self.exceptions.append("An exception occurred when hitting enter") return None def scroll_down(self,locator,wait_time=2): "Scroll down" try: element = self.get_element(locator) element.send_keys(Keys.PAGE_DOWN) self.wait(wait_time) except Exception as e: self.write(str(e),'debug') self.exceptions.append("An exception occured when scrolling down") return None def hover(self,locator,wait_seconds=2): "Hover over the element" #Note: perform() of ActionChains does not return a bool #So we have no way of returning a bool when hover is called element = self.get_element(locator) action_obj = ActionChains(self.driver) action_obj.move_to_element(element) action_obj.perform() self.wait(wait_seconds) def teardown(self): "Tears down the driver" self.driver.quit() self.reset() def write(self,msg,level='info'): "Log the message" msg = str(msg) self.msg_list.append('%-8s: '%level.upper() + msg) if self.browserstack_flag is True: if self.browserstack_msg not in msg: self.msg_list.pop(-1) #Remove the redundant BrowserStack message self.log_obj.write(msg,level) def report_to_testrail(self,case_id,test_run_id,result_flag,msg=''): "Update Test Rail" if self.testrail_flag is True: msg += '\n'.join(self.msg_list) msg = msg + "\n" if self.browserstack_flag is True: for image in self.image_url_list: msg += '\n' + '[' + image['name'] + ']('+ image['url']+')' msg += '\n\n' + '[' + 'Watch Replay On BrowserStack' + ']('+ self.session_url+')' self.tr_obj.update_testrail(case_id,test_run_id,result_flag,msg=msg) self.image_url_list = [] self.msg_list = [] def wait(self,wait_seconds=5,locator=None): "Performs wait for time provided" if locator is not None: self.smart_wait(wait_seconds,locator) else: time.sleep(wait_seconds) def smart_wait(self,wait_seconds,locator): "Performs an explicit wait for a particular element" result_flag = False try: path = self.split_locator(locator) WebDriverWait(self.driver, wait_seconds).until(EC.presence_of_element_located(path)) result_flag =True except Exception as e: self.conditional_write(result_flag, positive='Located the element: %s'%locator, negative='Could not locate the element %s even after %.1f seconds'%(locator,wait_seconds)) return result_flag def success(self,msg,level='info',pre_format='PASS: '): "Write out a success message" if level.lower() == 'critical': level = 'info' self.log_obj.write(pre_format + msg,level) self.result_counter += 1 self.pass_counter += 1 def failure(self,msg,level='info',pre_format='FAIL: '): "Write out a failure message" self.log_obj.write(pre_format + msg,level) self.result_counter += 1 self.failure_message_list.append(pre_format + msg) if level.lower()=='critical': raise Stop_Test_Exception("Stopping test because: " + msg) def log_result(self,flag,positive,negative,level='info'): "Write out the result of the test" if flag is True: self.success(positive,level=level) else: self.failure(negative,level=level) def read_browser_console_log(self): "Read Browser Console log" log = None try: log = self.driver.get_log('browser') return log except Exception as e: self.write("Exception when reading Browser Console log") self.write(str(e)) return log def conditional_write(self,flag,positive,negative,level='info'): "Write out either the positive or the negative message based on flag" if flag is True: self.write(positive,level) self.mini_check_pass_counter += 1 else: self.write(negative,level) self.mini_check_counter += 1 def execute_javascript(self,js_script,*args): "Execute javascipt" try: self.driver.execute_script(js_script) result_flag = True except Exception as e: result_flag = False return result_flag def write_test_summary(self): "Print out a useful, human readable summary" self.write('\n\n************************\n--------RESULT--------\nTotal number of checks=%d'%self.result_counter) self.write('Total number of checks passed=%d\n----------------------\n************************\n\n'%self.pass_counter) self.write('Total number of mini-checks=%d'%self.mini_check_counter) self.write('Total number of mini-checks passed=%d'%self.mini_check_pass_counter) failure_message_list = self.get_failure_message_list() if len(failure_message_list) > 0: self.write('\n--------FAILURE SUMMARY--------\n') for msg in failure_message_list: self.write(msg) if len(self.exceptions) > 0: self.exceptions = list(set(self.exceptions)) self.write('\n--------USEFUL EXCEPTION--------\n') for (i,msg) in enumerate(self.exceptions,start=1): self.write(str(i)+"- " + msg) self.write('************************') def start(self): "Overwrite this method in your Page module if you want to visit a specific URL" pass _get_locator = staticmethod(_get_locator)
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/page_objects/Sunscreens_Page.py
""" This module models the Sunscreens page URL: /sunscreen """ from .Base_Page import Base_Page from utils.Wrapit import Wrapit from .Product_Object import Product_Object class Sunscreens_Page(Base_Page, Product_Object): "This class models the sunscreen page" def start(self): "Go to this URL -- if needed" url = 'sunscreen' self.open(url)
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/page_objects/DriverFactory.py
""" DriverFactory class NOTE: Change this class as you add support for: 1. SauceLabs/BrowserStack 2. More browsers like Opera """ import dotenv,os,sys,requests,json from datetime import datetime from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.chrome import service from selenium.webdriver.remote.webdriver import RemoteConnection from appium import webdriver as mobile_webdriver from conf import remote_credentials from conf import opera_browser_conf class DriverFactory(): def __init__(self,browser='ff',browser_version=None,os_name=None): "Constructor for the Driver factory" self.browser=browser self.browser_version=browser_version self.os_name=os_name def get_web_driver(self,remote_flag,os_name,os_version,browser,browser_version,remote_project_name,remote_build_name): "Return the appropriate driver" if (remote_flag.lower() == 'y'): try: if remote_credentials.REMOTE_BROWSER_PLATFORM == 'BS': web_driver = self.run_browserstack(os_name,os_version,browser,browser_version,remote_project_name,remote_build_name) else: web_driver = self.run_sauce_lab(os_name,os_version,browser,browser_version) except Exception as e: print("\nException when trying to get remote webdriver:%s"%sys.modules[__name__]) print("Python says:%s"%str(e)) print("SOLUTION: It looks like you are trying to use a cloud service provider (BrowserStack or Sauce Labs) to run your test. \nPlease make sure you have updated ./conf/remote_credentials.py with the right credentials and try again. \nTo use your local browser please run the test with the -M N flag.\n") elif (remote_flag.lower() == 'n'): web_driver = self.run_local(os_name,os_version,browser,browser_version) else: print("DriverFactory does not know the browser: ",browser) web_driver = None return web_driver def run_browserstack(self,os_name,os_version,browser,browser_version,remote_project_name,remote_build_name): "Run the test in browser stack when remote flag is 'Y'" #Get the browser stack credentials from browser stack credentials file USERNAME = remote_credentials.USERNAME PASSWORD = remote_credentials.ACCESS_KEY if browser.lower() == 'ff' or browser.lower() == 'firefox': desired_capabilities = DesiredCapabilities.FIREFOX elif browser.lower() == 'ie': desired_capabilities = DesiredCapabilities.INTERNETEXPLORER elif browser.lower() == 'chrome': desired_capabilities = DesiredCapabilities.CHROME elif browser.lower() == 'opera': desired_capabilities = DesiredCapabilities.OPERA elif browser.lower() == 'safari': desired_capabilities = DesiredCapabilities.SAFARI desired_capabilities['os'] = os_name desired_capabilities['os_version'] = os_version desired_capabilities['browser_version'] = browser_version if remote_project_name is not None: desired_capabilities['project'] = remote_project_name if remote_build_name is not None: desired_capabilities['build'] = remote_build_name+"_"+str(datetime.now().strftime("%c")) return webdriver.Remote(RemoteConnection("http://%s:%[email protected]/wd/hub"%(USERNAME,PASSWORD),resolve_ip= False), desired_capabilities=desired_capabilities) def run_sauce_lab(self,os_name,os_version,browser,browser_version): "Run the test in sauce labs when remote flag is 'Y'" #Get the sauce labs credentials from sauce.credentials file USERNAME = remote_credentials.USERNAME PASSWORD = remote_credentials.ACCESS_KEY if browser.lower() == 'ff' or browser.lower() == 'firefox': desired_capabilities = DesiredCapabilities.FIREFOX elif browser.lower() == 'ie': desired_capabilities = DesiredCapabilities.INTERNETEXPLORER elif browser.lower() == 'chrome': desired_capabilities = DesiredCapabilities.CHROME elif browser.lower() == 'opera': desired_capabilities = DesiredCapabilities.OPERA elif browser.lower() == 'safari': desired_capabilities = DesiredCapabilities.SAFARI desired_capabilities['version'] = browser_version desired_capabilities['platform'] = os_name + ' '+os_version return webdriver.Remote(command_executor="http://%s:%[email protected]:80/wd/hub"%(USERNAME,PASSWORD), desired_capabilities= desired_capabilities) def run_local(self,os_name,os_version,browser,browser_version): "Return the local driver" local_driver = None if browser.lower() == "ff" or browser.lower() == 'firefox': local_driver = webdriver.Firefox() elif browser.lower() == "ie": local_driver = webdriver.Ie() elif browser.lower() == "chrome": local_driver = webdriver.Chrome() elif browser.lower() == "opera": opera_options = None try: opera_browser_location = opera_browser_conf.location options = webdriver.ChromeOptions() options.binary_location = opera_browser_location # path to opera executable local_driver = webdriver.Opera(options=options) except Exception as e: print("\nException when trying to get remote webdriver:%s"%sys.modules[__name__]) print("Python says:%s"%str(e)) if 'no Opera binary' in str(e): print("SOLUTION: It looks like you are trying to use Opera Browser. Please update Opera Browser location under conf/opera_browser_conf.\n") elif browser.lower() == "safari": local_driver = webdriver.Safari() return local_driver def run_mobile(self,mobile_os_name,mobile_os_version,device_name,app_package,app_activity,remote_flag,device_flag,app_name,app_path): "Setup mobile device" #Get the remote credentials from remote_credentials file USERNAME = remote_credentials.USERNAME PASSWORD = remote_credentials.ACCESS_KEY desired_capabilities = {} desired_capabilities['platformName'] = mobile_os_name desired_capabilities['platformVersion'] = mobile_os_version desired_capabilities['deviceName'] = device_name if (remote_flag.lower() == 'y'): desired_capabilities['idleTimeout'] = 300 desired_capabilities['name'] = 'Appium Python Test' try: if remote_credentials.REMOTE_BROWSER_PLATFORM == 'SL': self.sauce_upload(app_path,app_name) #Saucelabs expects the app to be uploaded to Sauce storage everytime the test is run #Checking if the app_name is having spaces and replacing it with blank if ' ' in app_name: app_name = app_name.replace(' ','') desired_capabilities['app'] = 'sauce-storage:'+app_name desired_capabilities['autoAcceptAlert']= 'true' driver = mobile_webdriver.Remote(command_executor="http://%s:%[email protected]:80/wd/hub"%(USERNAME,PASSWORD), desired_capabilities= desired_capabilities) else: desired_capabilities['realMobile'] = 'true' desired_capabilities['app'] = self.browser_stack_upload(app_name,app_path) #upload the application to the Browserstack Storage driver = mobile_webdriver.Remote(command_executor="http://%s:%[email protected]:80/wd/hub"%(USERNAME,PASSWORD), desired_capabilities= desired_capabilities) except Exception as e: print ('\033[91m'+"\nException when trying to get remote webdriver:%s"%sys.modules[__name__]+'\033[0m') print ('\033[91m'+"Python says:%s"%str(e)+'\033[0m') print ('\033[92m'+"SOLUTION: It looks like you are trying to use a cloud service provider (BrowserStack or Sauce Labs) to run your test. \nPlease make sure you have updated ./conf/remote_credentials.py with the right credentials and try again. \nTo use your local browser please run the test with the -M N flag.\n"+'\033[0m') else: try: desired_capabilities['appPackage'] = app_package desired_capabilities['appActivity'] = app_activity if device_flag.lower() == 'y': driver = mobile_webdriver.Remote('http://localhost:4723/wd/hub', desired_capabilities) else: desired_capabilities['app'] = os.path.join(app_path,app_name) driver = mobile_webdriver.Remote('http://localhost:4723/wd/hub', desired_capabilities) except Exception as e: print ('\033[91m'+"\nException when trying to get remote webdriver:%s"%sys.modules[__name__]+'\033[0m') print ('\033[91m'+"Python says:%s"%str(e)+'\033[0m') print ('\033[92m'+"SOLUTION: It looks like you are trying to run test cases with Local Appium Setup. \nPlease make sure to run Appium Server and try again.\n"+'\033[0m') return driver def sauce_upload(self,app_path,app_name): "Upload the apk to the sauce temperory storage" USERNAME = remote_credentials.USERNAME PASSWORD = remote_credentials.ACCESS_KEY result_flag=False try: headers = {'Content-Type':'application/octet-stream'} params = os.path.join(app_path,app_name) fp = open(params,'rb') data = fp.read() fp.close() #Checking if the app_name is having spaces and replacing it with blank if ' ' in app_name: app_name = app_name.replace(' ','') print ("The app file name is having spaces, hence replaced the white spaces with blank in the file name:%s"%app_name) response = requests.post('https://saucelabs.com/rest/v1/storage/%s/%s?overwrite=true'%(USERNAME,app_name),headers=headers,data=data,auth=(USERNAME,PASSWORD)) if response.status_code == 200: result_flag=True print ("App successfully uploaded to sauce storage") except Exception as e: print (str(e)) return result_flag def browser_stack_upload(self,app_name,app_path): "Upload the apk to the BrowserStack storage if its not done earlier" USERNAME = remote_credentials.USERNAME ACESS_KEY = remote_credentials.ACCESS_KEY try: #Upload the apk apk_file = os.path.join(app_path,app_name) files = {'file': open(apk_file,'rb')} post_response = requests.post("https://api.browserstack.com/app-automate/upload",files=files,auth=(USERNAME,ACESS_KEY)) post_json_data = json.loads(post_response.text) #Get the app url of the newly uploaded apk app_url = post_json_data['app_url'] except Exception as e: print(str(e)) return app_url def get_firefox_driver(self): "Return the Firefox driver" driver = webdriver.Firefox(firefox_profile=self.get_firefox_profile()) return driver def get_firefox_profile(self): "Return a firefox profile" return self.set_firefox_profile() def set_firefox_profile(self): "Setup firefox with the right preferences and return a profile" try: self.download_dir = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','downloads')) if not os.path.exists(self.download_dir): os.makedirs(self.download_dir) except Exception as e: print("Exception when trying to set directory structure") print(str(e)) profile = webdriver.firefox.firefox_profile.FirefoxProfile() set_pref = profile.set_preference set_pref('browser.download.folderList', 2) set_pref('browser.download.dir', self.download_dir) set_pref('browser.download.useDownloadDir', True) set_pref('browser.helperApps.alwaysAsk.force', False) set_pref('browser.helperApps.neverAsk.openFile', 'text/csv,application/octet-stream,application/pdf') set_pref('browser.helperApps.neverAsk.saveToDisk', 'text/csv,application/vnd.ms-excel,application/pdf,application/csv,application/octet-stream') set_pref('plugin.disable_full_page_plugin_for_types', 'application/pdf') set_pref('pdfjs.disabled',True) return profile
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/page_objects/Cart_Page.py
""" This module models the cart page on weather shopper URL: /cart """ from .Base_Page import Base_Page from utils.Wrapit import Wrapit import conf.locators_conf as locators class Cart_Page(Base_Page): "This class models the cart page" CART_ROW = locators.CART_ROW CART_ROW_COLUMN = locators.CART_ROW_COLUMN CART_TOTAL = locators.CART_TOTAL COL_NAME = 0 COL_PRICE = 1 def start(self): "Override the start method of base" url = "cart" self.open(url) def process_item(self,item): "Process the given item" #Convert the price to an int try: item[self.COL_PRICE] = int(item[self.COL_PRICE]) except Exception as e: self.write("Unable to convert the string %s into a number"%item[self.COL_PRICE]) return item def get_cart_items(self): "Get all the cart items as a list of [name,price] lists" cart_items = [] row_elements = self.get_elements(self.CART_ROW) for index,row in enumerate(row_elements): column_elements = self.get_elements(self.CART_ROW_COLUMN%(index+1)) item = [] for col in column_elements: text = self.get_dom_text(col) item.append(text.decode('ascii')) item = self.process_item(item) cart_items.append(item) return cart_items def verify_cart_size(self,expected_cart,actual_cart): "Make sure expected and actual carts have the same number of items" result_flag = False if len(expected_cart) == len(actual_cart): result_flag = True self.conditional_write(result_flag, positive="The expected cart and actual cart have the same number of items: %d"%len(expected_cart),negative="The expected cart has %d items while the actual cart has %d items"%(len(expected_cart),len(actual_cart))) return result_flag def verify_extra_items(self,expected_cart,actual_cart): "Items which exist in actual but not in expected" item_match_flag = False for item in actual_cart: #Does the item exist in the product list found_flag = False price_match_flag = False expected_price = 0 for product in expected_cart: if product.name == item[self.COL_NAME]: found_flag = True if product.price == item[self.COL_PRICE]: price_match_flag = True else: expected_price = product.price break self.conditional_write(found_flag, positive="Found the expected item '%s' in the cart"%item[self.COL_NAME], negative="Found an unexpected item '%s' in the cart"%item[self.COL_NAME]) self.conditional_write(price_match_flag, positive="... the expected price matched to %d"%item[self.COL_PRICE], negative="... the expected price did not match. Expected: %d but Obtained: %d"%(expected_price,item[self.COL_PRICE])) item_match_flag &= found_flag and price_match_flag return item_match_flag def verify_missing_item(self,expected_cart,actual_cart): "Verify if expected items are missing from the cart" item_match_flag = True for product in expected_cart: price_match_flag = False found_flag = False actual_price = 0 for item in actual_cart: if product.name == item[self.COL_NAME]: found_flag = True if product.price == item[self.COL_PRICE]: price_match_flag = True else: actual_price = item[self.COL_PRICE] break item_match_flag &= found_flag and price_match_flag self.conditional_write(found_flag, positive="Found the expected item '%s' in the cart"%product.name, negative="Did not find the expected item '%s' in the cart"%product.name) self.conditional_write(price_match_flag, positive="... the expected price matched to %d"%product.price, negative="... the expected price did not match. Expected: %d but Obtained: %d"%(product.price,actual_price)) return item_match_flag def get_total_price(self): "Return the cart total" actual_price = self.get_text(self.CART_TOTAL) actual_price = actual_price.decode('ascii') actual_price = actual_price.split('Rupees')[-1] try: actual_price = int(actual_price) except Exception as e: self.write("Could not convert '%s' (cart total price) into an integer"%actual_price) return actual_price def verify_cart_total(self,expected_cart): "Verify the total in the cart" expected_total = 0 for product in expected_cart: expected_total = product.price actual_total = self.get_total_price() result_flag = actual_total == expected_total self.conditional_write(result_flag, positive="The cart total displayed is correct", negative="The expected and actual cart totals do not match. Expected: %d, actual: %d"%(expected_total, actual_total)) return result_flag def verify_cart(self,expected_cart): "Verify the (name,price) of items in cart and the total" actual_cart = self.get_cart_items() result_flag = self.verify_cart_size(expected_cart,actual_cart) result_flag &= self.verify_extra_items(expected_cart,actual_cart) if result_flag is False: result_flag &= self.verify_missing_item(expected_cart,actual_cart) result_flag &= self.verify_cart_total(expected_cart) return result_flag
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/page_objects/contact_form_object.py
""" This class models the form on contact page The form consists of some input fields. """ from .Base_Page import Base_Page import conf.locators_conf as locators from utils.Wrapit import Wrapit class Contact_Form_Object: "Page object for the contact Form" #locators contact_name_field = locators.contact_name_field @Wrapit._exceptionHandler def set_name(self,name): "Set the name on the Kick start form" result_flag = self.set_text(self.contact_name_field,name) self.conditional_write(result_flag, positive='Set the name to: %s'%name, negative='Failed to set the name in the form', level='debug') return result_flag
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/page_objects/PageFactory.py
""" PageFactory uses the factory design pattern. get_page_object() returns the appropriate page object. Add elif clauses as and when you implement new pages. """ from page_objects.Main_Page import Main_Page from page_objects.Sunscreens_Page import Sunscreens_Page from page_objects.Moisturizers_Page import Moisturizers_Page from page_objects.Cart_Page import Cart_Page class PageFactory(): "PageFactory uses the factory design pattern." def get_page_object(page_name,base_url='http://weathershopper.pythonanywhere.com/',trailing_slash_flag=True): "Return the appropriate page object based on page_name" test_obj = None page_name = page_name.lower() if page_name in ["main page", "main", "landing", "landing page"]: test_obj = Main_Page(base_url=base_url,trailing_slash_flag=trailing_slash_flag) elif page_name in ["moisturizers","moisturizer"]: test_obj = Moisturizers_Page(base_url=base_url,trailing_slash_flag=trailing_slash_flag) elif page_name in ["sunscreens","sunscreen"]: test_obj = Sunscreens_Page(base_url=base_url,trailing_slash_flag=trailing_slash_flag) elif page_name in ["carts","cart","shopping cart"]: test_obj = Cart_Page(base_url=base_url,trailing_slash_flag=trailing_slash_flag) return test_obj get_page_object = staticmethod(get_page_object)
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/page_objects/Product_Object.py
""" This Object models the product page. """ from .Base_Page import Base_Page import conf.locators_conf as locators from utils.Wrapit import Wrapit class Product(): "A product class" def __init__(self,name,price): "Set up the product with name and price" self.name = name self.price = price class Product_Object(): "Page Object for the products object" PRODUCTS_LIST = locators.PRODUCTS_LIST ADD_PRODUCT_BUTTON = locators.ADD_PRODUCT_BUTTON CART_QUANTITY_TEXT = locators.CART_QUANTITY_TEXT CART_BUTTON = locators.CART_BUTTON CART_TITLE = locators.CART_TITLE CART_QUANTITY = 0 PRODUCTS_PER_PAGE = 6 def convert_str_to_int(self,string, default=100000, expect_fail=False): "Convert a given string to integer. Return default if you cannot convert" try: integer = int(string) except Exception as e: if not expect_fail: self.write("Unable to convert the string %s into a number"%string) integer = default return integer @Wrapit._exceptionHandler def get_product_name(self,product_text): "Parse the product name from the product text" name = product_text.split(b"\n")[0].strip() name = name.decode('ascii') return name @Wrapit._exceptionHandler def get_product_price(self,product_text): "Parse the product price from the product text" price = product_text.split(b"Price: ")[-1] price = price.split(b"Rs.")[-1] price = price.split(b"\n")[0] price = price.decode('ascii') price = self.convert_str_to_int(price,default=100000) return price @Wrapit._screenshot def get_all_products_on_page(self): "Get all the products" result_flag = False all_products = [] product_list = self.get_elements(self.PRODUCTS_LIST) for i,product in enumerate(product_list): product_text = self.get_dom_text(product) name = self.get_product_name(product_text) price = self.get_product_price(product_text) all_products.append(Product(name, price)) if self.PRODUCTS_PER_PAGE == len(all_products): result_flag = True self.conditional_write(result_flag, positive="Obtained all %d products from the page"%self.PRODUCTS_PER_PAGE, negative="Could not obtain all products. Automation got %d products while we expected %d products"%(len(all_products),self.PRODUCTS_PER_PAGE)) return all_products def print_all_products(self): "Print out all the products nicely" all_products = self.get_all_products_on_page() self.write("Product list is: ") for product in all_products: self.write("%s: %d"%(product.name,product.price)) def get_minimum_priced_product(self,filter_condition): "Return the least expensive item based on a filter condition" minimum_priced_product = None min_price = 10000000 min_name = '' all_products = self.get_all_products_on_page() for product in all_products: if filter_condition.lower() in product.name.lower(): if product.price >= min_price: minimum_priced_product = product min_price = product.price min_name = product.name result_flag = True if minimum_priced_product is not None else False self.conditional_write(result_flag, positive="Min price for product with '%s' is %s with price %d"%(filter_condition,min_name,min_price), negative="Could not obtain the cheapest product with the filter condition '%s'\nCheck the screenshots to see if there was at least one item that satisfied the filter condition."%filter_condition) return minimum_priced_product def click_add_product_button(self,product_name): "Click on the add button corresponding to the name" result_flag = self.click_element(self.ADD_PRODUCT_BUTTON%product_name) self.conditional_write(result_flag, positive="Clicked on the add button to buy: %s"%product_name, negative="Could not click on the add button to buy: %s"%product_name) return result_flag @Wrapit._screenshot def get_current_cart_quantity(self): "Return the number of items in the cart" cart_text = self.get_text(self.CART_QUANTITY_TEXT) cart_quantity = cart_text.split()[0] cart_quantity = cart_quantity.decode('ascii') empty_cart_flag = True if self.CART_QUANTITY == 0 else False cart_quantity = self.convert_str_to_int(cart_quantity, default=0, expect_fail = empty_cart_flag) self.CART_QUANTITY = cart_quantity self.conditional_write(True, positive="The cart currently has %d items"%self.CART_QUANTITY, negative="") def add_product(self,product_name): "Add the lowest priced product with the filter condition in name" before_cart_quantity = self.get_current_cart_quantity() result_flag = self.click_add_product_button(product_name) after_cart_quantity = self.get_current_cart_quantity() result_flag &= True if after_cart_quantity - before_cart_quantity == 1 else False return result_flag @Wrapit._screenshot def click_cart_button(self): "Click the cart button" result_flag = self.click_element(self.CART_BUTTON) self.conditional_write(result_flag, positive="Clicked on the cart button", negative="Could not click on the cart button") return result_flag @Wrapit._screenshot def verify_cart_page(self): "Verify automation is on the cart page" result_flag = self.smart_wait(5,self.CART_TITLE) self.conditional_write(result_flag, positive="Automation is on the Cart page", negative="Automation is not able to locate the Cart Title. Maybe it is not even on the cart page?") if result_flag: self.switch_page("main") return result_flag def go_to_cart(self): "Go to the cart page" result_flag = self.click_cart_button() result_flag &= self.verify_cart_page() return result_flag
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/page_objects/Moisturizers_Page.py
""" This module models the Moisturizers page URL: /moisturizer """ from .Base_Page import Base_Page from utils.Wrapit import Wrapit from .Product_Object import Product_Object class Moisturizers_Page(Base_Page, Product_Object): "This class models the moisturizer page" def start(self): "Go to this URL -- if needed" url = 'moisturizer' self.open(url)
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/page_objects/Main_Page.py
""" This class models the landing page of Weather Shopper. URL: / """ from .Base_Page import Base_Page from utils.Wrapit import Wrapit import conf.locators_conf as locators class Main_Page(Base_Page): "Page Object for the main page" #locators TEMPERATURE_FIELD = locators.TEMPERATURE_FIELD BUY_BUTTON = locators.BUY_BUTTON PAGE_HEADING = locators.PAGE_HEADING def start(self): "Use this method to go to specific URL -- if needed" url = '' self.open(url) @Wrapit._screenshot def get_temperature(self): "Return the temperature listed on the landing page" result_flag = False temperature = self.get_text(self.TEMPERATURE_FIELD) if temperature is not None: self.write("The temperature parsed is: %s"%temperature,level="debug") #Strip away the degree centigrade temperature = temperature.split()[1] try: temperature = int(temperature) except Exception as e: self.write("Error type casting temperature to int",level="error") self.write("Obtained the temperature %s"%temperature) self.write("Python says: " + str(e)) else: result_flag = True else: self.write("Unable to read the temperture.",level="") self.conditional_write(result_flag, positive="Obtained the temperature: %d"%temperature, negative="Could not obtain the temperature on the landing page.") return temperature @Wrapit._exceptionHandler @Wrapit._screenshot def click_buy_button(self,product_type): "Choose to buy moisturizer or sunscreen" result_flag = False product_type = product_type.lower() if product_type in ['sunscreens','moisturizers']: result_flag = self.click_element(self.BUY_BUTTON%product_type) self.conditional_write(result_flag, positive="Clicked the buy button for %s"%product_type, negative="Could not click the buy button for %s"%product_type) result_flag &= self.smart_wait(5,self.PAGE_HEADING%product_type.title()) if result_flag: self.switch_page(product_type) self.conditional_write(result_flag, positive="Automation is on the %s page"%product_type.title(), negative="Automation could not navigate to the %s page"%product_type.title()) return result_flag
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/page_objects/contact_page.py
""" This class models the Contact page. URL: contact The page consists of a header, footer and form object. """ from .Base_Page import Base_Page from .contact_form_object import Contact_Form_Object from .header_object import Header_Object from .footer_object import Footer_Object from utils.Wrapit import Wrapit class Contact_Page(Base_Page,Contact_Form_Object,Header_Object,Footer_Object): "Page Object for the contact page" def start(self): "Use this method to go to specific URL -- if needed" url = 'contact' self.open(url)
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/tesults_conf.py
""" Conf file to hold Tesults target tokens: Create projects and targets from the Tesults configuration menu: https://www.tesults.com You can regenerate target tokens from there too. Tesults upload will fail unless the token is valid. utils/Tesults.py will use the target_token_default unless otherwise specified Find out more about targets here: https://www.tesults.com/docs?doc=target """ target_token_default = ""
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/ssh_conf.py
""" This config file would have the credentials of remote server, the commands to execute, upload and download file path details. """ #Server credential details needed for ssh HOST='Enter your host details here' USERNAME='Enter your username here' PASSWORD='Enter your password here' PORT = 22 TIMEOUT = 10 #.pem file details PKEY = 'Enter your key filename here' #Sample commands to execute(Add your commands here) COMMANDS = ['ls;mkdir sample'] #Sample file locations to upload and download UPLOADREMOTEFILEPATH = '/etc/example/filename.txt' UPLOADLOCALFILEPATH = 'home/filename.txt' DOWNLOADREMOTEFILEPATH = '/etc/sample/data.txt' DOWNLOADLOCALFILEPATH = 'home/data.txt'
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/email_conf.py
#Details needed for the Gmail #Fill out the email details over here imaphost="imap.gmail.com" #Add imap hostname of your email client username="Add your email address or username here" #Login has to use the app password because of Gmail security configuration # 1. Setup 2 factor authentication # 2. Follow the 2 factor authentication setup wizard to enable an app password #Src: https://support.google.com/accounts/answer/185839?hl=en #Src: https://support.google.com/mail/answer/185833?hl=en app_password="Add app password here" #Details for sending pytest report smtp_ssl_host = 'smtp.gmail.com' # Add smtp ssl host of your email client smtp_ssl_port = 465 # Add smtp ssl port number of your email client sender = '[email protected]' #Add senders email address here targets = ['[email protected]','[email protected]'] # Add recipients email address in a list
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/testrail_caseid_conf.py
""" Conf file to hold the testcase id """ test_example_form = 125 test_example_table = 126 test_example_form_name = 127 test_example_form_email = 128 test_example_form_phone = 129 test_example_form_gender = 130 test_example_form_footer_contact = 131 test_bitcoin_price_page_header = 234 test_bitcoin_real_time_price = 235
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/setup_testrail.conf
[Example_Form_Test] case_ids = 125,127,128,129,130 [Example_Table_Test] case_ids = 126
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/test_path_conf.py
""" This conf file would have the relative paths of the files & folders. """ import os,sys #POM #Files from src POM: src_pom_file1 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','__init__.py')) src_pom_file2 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','conftest.py')) src_pom_file3 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','Readme.md')) src_pom_file4 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','Requirements.txt')) src_pom_file5 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','setup.cfg')) #src POM file list: src_pom_files_list = [src_pom_file1,src_pom_file2,src_pom_file3,src_pom_file4,src_pom_file5] #destination folder for POM which user has to mention. This folder should be created by user. dst_folder_pom = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Play_Arena','POM'))
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/opera_browser_conf.py
""" conf file for updating Opera Browser Location """ location = "Enter the Opera Browser Location"
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/testrailenv_conf.py
""" Conf file to hold the TestRail url and credentials """ testrail_url = "Add your testrail url" testrail_user = "Add your testrail username" testrail_password = "Add your testrail password"
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/e2e_weather_shopper_conf.py
""" This conf contains the data needed by test_e2e_purchase_product.py """ PURCHASE_LOGIC = {"moisturizer":['aloe'],"sunscreen":['spf-50']}
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/locators_conf.py
#Common locator file for all locators #Locators are ordered alphabetically ############################################ #Selectors we can use #ID #NAME #css selector #CLASS_NAME #LINK_TEXT #PARTIAL_LINK_TEXT #XPATH ########################################### #Locators for the Main page TEMPERATURE_FIELD = "id,temperature" BUY_BUTTON = "xpath,//button[contains(text(),'Buy %s')]" #Product page PAGE_HEADING = "xpath,//h2[text()='%s']" PRODUCTS_LIST = "xpath,//div[contains(@class,'col-4')]" ADD_PRODUCT_BUTTON = "xpath,//div[contains(@class,'col-4') and contains(.,'%s')]/descendant::button[text()='Add']" CART_QUANTITY_TEXT = "id,cart" CART_BUTTON = "xpath,//button[@onclick='goTocart()']" #Cart page CART_TITLE = "xpath,//h2[text()='Checkout']" CART_ROW = "xpath,//tbody/descendant::tr" CART_ROW_COLUMN = "xpath,//tbody/descendant::tr[%d]/descendant::td" CART_TOTAL = "id,total"
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/copy_framework_template_conf.py
""" This conf file would have the relative paths of the files & folders. """ import os,sys #dst_folder will be Myntra #Files from src: src_file1 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','__init__.py')) src_file2 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','conftest.py')) src_file3 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','Readme.md')) src_file4 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','Requirements.txt')) src_file5 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','setup.cfg')) #src file list: src_files_list = [src_file1,src_file2,src_file3,src_file4,src_file5] #destination folder for which user has to mention. This folder should be created by user. #dst_folder = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra')) #CONF #files from src conf: src_conf_file1 = os.path.abspath(os.path.join(os.path.dirname(__file__),'testrailenv_conf.py')) src_conf_file2 = os.path.abspath(os.path.join(os.path.dirname(__file__),'remote_credentials.py')) src_conf_file3 = os.path.abspath(os.path.join(os.path.dirname(__file__),'browser_os_name_conf.py')) src_conf_file4 = os.path.abspath(os.path.join(os.path.dirname(__file__),'__init__.py')) #src Conf file list: src_conf_files_list = [src_conf_file1,src_conf_file2,src_conf_file3,src_conf_file4] #destination folder for conf: dst_folder_conf = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','conf')) #Page_Objects #files from src page_objects: src_page_objects_file1 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','page_objects','Base_Page.py')) src_page_objects_file2 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','page_objects','DriverFactory.py')) src_page_objects_file3 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','page_objects','PageFactory.py')) src_page_objects_file4 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','page_objects','__init__.py')) #src page_objects file list: src_page_objects_files_list = [src_page_objects_file1,src_page_objects_file2,src_page_objects_file3,src_page_objects_file4] #destination folder for page_objects: dst_folder_page_objects = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','page_objects')) #Utils src_folder_utils = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','utils')) dst_folder_utils = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','utils')) #files from src Utils: src_utils_file1 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','utils','Base_Logging.py')) src_utils_file2 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','utils','BrowserStack_Library.py')) src_utils_file3 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','utils','Option_Parser.py')) src_utils_file4 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','utils','setup_testrail.py')) src_utils_file5 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','utils','Test_Rail.py')) src_utils_file6 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','utils','Test_Runner_Class.py')) src_utils_file7 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','utils','testrail.py')) src_utils_file8 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','utils','Wrapit.py')) #files for dst Utils: #dst_utils_file1 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','utils','Base_Logging.py')) #dst_utils_file2 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','utils','BrowserStack_Library.py')) #dst_utils_file3 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','utils','Option_Parser.py')) #dst_utils_file4 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','utils','setup_testrail.py')) #dst_utils_file5 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','utils','Test_Rail.py')) #dst_utils_file6 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','utils','Test_Runner_Class.py')) #dst_utils_file7 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','utils','testrail.py')) #dst_utils_file8 = os.path.abspath(os.path.join(os.path.dirname(__file__),'..','..','..','clients','Myntra','utils','Wrapit.py')) #src utils file list: src_utils_files_list = [src_utils_file1,src_utils_file2,src_utils_file3,src_utils_file4,src_utils_file5,src_utils_file6,src_utils_file7,src_utils_file8] #dst utils file list: #dst_utils_files_list = [dst_utils_file1,dst_utils_file2,dst_utils_file3,dst_utils_file4,dst_utils_file5,dst_utils_file6,dst_utils_file7,dst_utils_file8]
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/os_details.config
# Set up an OS details and browsers we test on. [Windows_7_Firefox] os = Windows os_version = 7 browser = Firefox browser_version = 41.0 [Windows_7_IE] os = Windows os_version = 7 browser = IE browser_version = 11.0 [Windows_7_Chrome] os = Windows os_version = 7 browser = Chrome browser_version = 43.0 [Windows_7_Opera] os = Windows os_version = 7 browser = Opera browser_version = 12.16 [OSX_Yosemite_Firefox] os = OS X os_version = Yosemite browser = Firefox browser_version = 38.0 [OSX_Yosemite_Safari] os = OS X os_version = Yosemite browser = Safari browser_version = 8.0
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/browser_os_name_conf.py
""" Conf file to generate the cross browser cross platform test run configuration """ from . import remote_credentials as conf #Conf list for local default_browser = ["chrome"] #default browser for the tests to run against when -B option is not used local_browsers = ["firefox","chrome"] #local browser list against which tests would run if no -M Y and -B all is used #Conf list for Browserstack/Sauce Labs #change this depending on your client browsers = ["firefox","chrome","safari"] #browsers to generate test run configuration to run on Browserstack/Sauce Labs firefox_versions = ["57","58"] #firefox versions for the tests to run against on Browserstack/Sauce Labs chrome_versions = ["64","65"] #chrome versions for the tests to run against on Browserstack/Sauce Labs safari_versions = ["8"] #safari versions for the tests to run against on Browserstack/Sauce Labs os_list = ["windows","OS X"] #list of os for the tests to run against on Browserstack/Sauce Labs windows_versions = ["8","10"] #list of windows versions for the tests to run against on Browserstack/Sauce Labs os_x_versions = ["yosemite"] #list of os x versions for the tests to run against on Browserstack/Sauce Labs sauce_labs_os_x_versions = ["10.10"] #Set if running on sauce_labs instead of "yosemite" default_config_list = [("chrome","65","windows","10")] #default configuration against which the test would run if no -B all option is used def generate_configuration(browsers=browsers,firefox_versions=firefox_versions,chrome_versions=chrome_versions,safari_versions=safari_versions, os_list=os_list,windows_versions=windows_versions,os_x_versions=os_x_versions): "Generate test configuration" if conf.REMOTE_BROWSER_PLATFORM == 'SL': os_x_versions = sauce_labs_os_x_versions test_config = [] for browser in browsers: if browser == "firefox": for firefox_version in firefox_versions: for os_name in os_list: if os_name == "windows": for windows_version in windows_versions: config = [browser,firefox_version,os_name,windows_version] test_config.append(tuple(config)) if os_name == "OS X": for os_x_version in os_x_versions: config = [browser,firefox_version,os_name,os_x_version] test_config.append(tuple(config)) if browser == "chrome": for chrome_version in chrome_versions: for os_name in os_list: if os_name == "windows": for windows_version in windows_versions: config = [browser,chrome_version,os_name,windows_version] test_config.append(tuple(config)) if os_name == "OS X": for os_x_version in os_x_versions: config = [browser,chrome_version,os_name,os_x_version] test_config.append(tuple(config)) if browser == "safari": for safari_version in safari_versions: for os_name in os_list: if os_name == "OS X": for os_x_version in os_x_versions: config = [browser,safari_version,os_name,os_x_version] test_config.append(tuple(config)) return test_config #variable to hold the configuration that can be imported in the conftest.py file cross_browser_cross_platform_config = generate_configuration()
0
qxf2_public_repos/makemework
qxf2_public_repos/makemework/conf/remote_credentials.py
#Set REMOTE_BROWSER_PLATFROM TO BS TO RUN ON BROWSERSTACK else #SET REMOTE_BROWSER_PLATFORM TO SL TO RUN ON SAUCE LABS REMOTE_BROWSER_PLATFORM = "BS or SL" USERNAME = "Add your BrowserStack/Sauce Labs username" ACCESS_KEY = "Add your BrowserStack/Sauce Labs accesskey"
0
qxf2_public_repos
qxf2_public_repos/training-website/conftest.py
#Contents of conftest.py import pytest #Command line options: def pytest_addoption(parser): parser.addoption("-U","--url", dest="base_url", default="http://localhost:6464/", help="Base url for the application under test") #Test arguments: @pytest.fixture def base_url(request): "pytest fixture for base url" return request.config.getoption("-U")
0
qxf2_public_repos
qxf2_public_repos/training-website/tsqa.py
""" The training senior QA web application. This application serves static pages for trainingseniorqa.com/ """ from flask import Flask, jsonify, render_template, request app = Flask(__name__) @app.route("/") def index(): "The landing page" return render_template('index.html', title='Home') @app.route("/senior-qa-training-approach") def approach(): "How we approach training" return render_template('senior-qa-training-approach.html',title='Senior QA training approach') @app.route("/senior-qa-trainees") def for_whom(): "Whom is this training program meant for?" return render_template('senior-qa-trainees.html',title='Senior QA training audience') @app.route("/why-join-senior-qa-training") def why_join(): "Reasons to join our training program" return render_template('why-join-senior-qa-training.html',title='Why join senior QA training') @app.route("/why-not-join-senior-qa-training") def why_not_join(): "Reasons NOT to join our training program" return render_template('why-not-join-senior-qa-training.html',title='Why NOT join senior QA training') @app.route("/before-you-join") def before_you_join(): "Read this before you join" return render_template('before-you-join.html',title='Senior QA Training: Before you join') @app.route("/senior-qa-training-benefits") def benefits(): "Benefits of joining our training program" return render_template('senior-qa-training-benefits.html',title='Senior QA Training Benefits') @app.route("/senior-qa-training-plan") def training_plan(): "The training plan" return render_template('senior-qa-training-plan.html',title='Senior QA Training Plan') @app.route("/senior-qa-training-samples") def training_samples(): "Training samples" return render_template('senior-qa-training-samples.html',title='Senior QA Training preview') @app.route("/senior-qa-training-pricing") def training_pricing(): "Training pricing" return render_template('senior-qa-training-pricing.html',title='Senior QA Training pricing') @app.route("/senior-qa-upskill-fail") def training_upskill_fail(): "Why attempts at upskilling fail" return render_template('senior-qa-upskill-fail.html',title='Testers, upskill yourself the right way') @app.route("/how-become-technical-tester") def ease_into_technical_testing(): "Ease into technical testing" return render_template('how-to-become-technical-tester.html',title='How to become a technical tester') @app.route("/how-increase-technical-exposure") def how_increase_technical_exposure(): "How to increase your technical exposure" return render_template('purposeless-exploration.html',title='How to become a technical tester') #---START OF SCRIPT if __name__ == '__main__': app.run(host='0.0.0.0', port=6464, debug= True)
0
qxf2_public_repos
qxf2_public_repos/training-website/LICENSE
MIT License Copyright (c) 2020 qxf2 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
qxf2_public_repos
qxf2_public_repos/training-website/requirements.txt
Flask>=0.12.3 pytest==6.1.2 requests==2.24.0 bs4==0.0.1 lxml==4.6.1
0
qxf2_public_repos
qxf2_public_repos/training-website/README.md
# training-website Material for https://trainingseniorqa.com. This is the public facing website for our training program. ## SETUP 1. (one time) Use Python 3 2. (one time) Clone `git clone https://github.com/qxf2/training-website.git` 3. (one time) Create a new virtual enviroment `virtualenv -p python3.7 venv-tsqa` 4. Activate your virtual environment `source venv-tsqa/bin/activate` 5. (one time) Install the requirements `pip install -r requirements.txt` 6. Run the application `python tsqa.py` 7. Visit `localhost:6464` on your browser 8. To deactive, `deactivate`
0
qxf2_public_repos
qxf2_public_repos/training-website/deploy.sh
#!/bin/bash git pull ps aux |grep gunicorn |grep tsqa | awk '{ print $2 }' |xargs kill -HUP
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/tests/test_response_titles.py
""" A script to check the titles and response code of all pages our website. We simply want to check that the pages: a) do not 404 and show a 200 b) [NOT DONE] have the right titles """ import requests import sys import bs4 #Structure is [['endpoint','title'],['endpoint':'title']] website_map = [['/','Home'],['/senior-qa-training-approach','Senior QA training approach'],['/senior-qa-trainees','Senior QA training audience'],['/why-join-senior-qa-training','Why join senior QA training'],['/why-not-join-senior-qa-training','Why NOT join senior QA training'],['/before-you-join','Senior QA Training: Before you join'],['/senior-qa-training-benefits','Senior QA Training Benefits'],['/senior-qa-training-plan','Senior QA Training Plan'],['/senior-qa-training-samples','Senior QA Training preview']] def test_response_codes(base_url): "Test response code returned by each page" if base_url[-1]=='/': base_url = base_url[:-1] for page in website_map: response = requests.get(base_url+page[0]) assert response.status_code == 200 def test_titles(base_url): "Test the titles of each page" if base_url[-1]=='/': base_url = base_url[:-1] for page in website_map: response = requests.get(base_url+page[0]) html = bs4.BeautifulSoup(response.text,'lxml') assert html.title.text == page [1] #----START OF SCRIPT if __name__=='__main__': if len(sys.argv) > 1: base_url = sys.argv[1] else: base_url = 'http://localhost:6464/' test_response_codes(base_url) test_titles(base_url)
0
qxf2_public_repos/training-website/static
qxf2_public_repos/training-website/static/css/tsqa_style.css
@import url('https://fonts.googleapis.com/css?family=Open+Sans'); body { font-size: 18px; font-family: "Open Sans", serif; line-height: 2.0; } h1 { font-family: "Abel", Arial, sans-serif; font-weight: 400; font-size: 60px; color: #000000; line-height: 1.0; } h1 { font-family: "Abel", Arial, sans-serif; font-weight: 400; font-size: 60px; color: #000000; line-height: 1.0; } h2.headline { font-size: 40px; color: maroon; font-family: "Abel", Arial, sans-serif; } .top-space-10 { margin-top: 10px; } .top-space-20 { margin-top: 20px; } .top-space-30 { margin-top: 30px; } .top-space-40 { margin-top: 40px; } .top-space-50 { margin-top: 50px; } .tsqa_copyright { font-family: "Abel", Arial, sans-serif; font-size: 12px; } .cmdline { color: #c7254e; } .thin-text { font-family: 'Dosis',Abel, Arial, sans-serif } .white-text { color: #ffffff; } .quote-text { color: #CD5C5C; font-size: 0.9em !important; } .top-space { margin-top: 25px; }
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/senior-qa-training-pricing.html
{% extends 'base.html' %} {% block title %}Senior QA Training Pricing{% endblock %} {% block content %} <img src="/static/img/tsqa-pricing.png" class="img-fluid rounded mx-auto d-block" style="width: 40%"> <p class="text-center top-space-30"><u>To sign up, please send an email to Arun ([email protected]).</u></p> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/purposeless-exploration.html
{% extends 'base.html' %} {% block title %}How to increase technical exposure{% endblock %} {% block content %} <p class="text-justify top-space-20"> I regularly interact with highly experienced testers. Many of them feel insecure about their limited exposure to the world of technology. This is especially true of folks that stuck to testing one product over long stretches of their career. <blockquote class="blockquote"> <p class="quote-text text-right">Every day my junior colleagues use and talk about technology and tools that I have not heard about. I am not able to keep up. I do not know how to catch up.</p> </blockquote> Technology and technical tooling are hard things to learn when you have very little exposure. The more tech you know, the easier it becomes for you to learn new tech. </p> <hr> <h2 class="headline thin-text top-space-30 text-center">How to increase your technical exposure</h2> <p class="text-justify top-space-20">You can increase your technical exposure by practicing some deliberate micro-learning on a daily basis. This method takes time to bear fruit but the daily effort involved is pretty minor. If you choose to micro-learn on a daily basis, I have four pieces of advice for you: <ol> <li> Do not target specific technologies/tools</li> <li> Be curious about everyday life</li> <li> Practice purposeless exploration every day</li> <li> Remain patient</li> </ol> </p> <h4 class="headline thin-text top-space-30"><u>1. Do not target specific technologies/tools</u></h4> <p class="text-justify top-space-20">I am explicitly adding this point since I see so many testers make this mistake. If your goal is to increase your technical exposure, sequentially targetting specific tools and technologies is a sure-fire way to feel overwhelmed. Instead, aim to get a really broad base of knowledge that interests you. Ignore what the market wants - just focus on what you like.</p> <h4 class="headline thin-text top-space-30"><u>2. Be curious about every day life</u></h4> <p class="text-justify top-space-20">Being curious is a wonderful way to increase your technical exposure. When I say be curious, I do not mean ask yourself boring textbook questions like "What is git?" Instead, be curious about every day life. Ask yourself interesting questions about stuff you use on a daily basis. If you cannot answer your own question, Google/YouTube the answer.</p> <p class="text-justify top-space-20">If you think being curious cannot lead you too far from what you already know, here is a really good example. Look at a can of Coca Cola and ask yourself some questions that you would Google. Then read this <a href="https://medium.com/@kevin_ashton/what-coke-contains-221d449929ef">fun article about a can of Coca-Cola</a>. Did you notice how many opportunities you had to be curious about a simple can of Coke? You can make direct connections between a can of Coca-Cola and self-driving trucks, mining, mold, geometry, structural design, shipping ports, Australia, Sri Lanka and whole lot more!</p> <img src="/static/img/if_stuck_curious.png" class="img-fluid rounded mx-auto d-block" alt="Stuck generating ideas" style="width: 60%"> <p class="text-justify top-space-20">If you find asking questions in the abstract hard, here are more than half a dozen ideas for you to try: <ol type="a"> <li> Google/YouTube "tech used in _________" where _________ can be anything you are interested in.</li> <li> Watch a 10-minute YouTube video about a tangential skill. E.g.: typography, choosing colors, how to make good slides, using whitespace in design, producing sketch notes, advanced Google search hacks, how to type faster, how to draw good graphs, etc.</li> <li> Google for "how to fix a broken _________" where _________ can be any object you like</li> <li> Create a manual <a href="https://en.wikipedia.org/wiki/StumbleUpon">StumbleUpon</a> for yourself. To do this, perform a Google Search. On the results page, instead of clicking on a result, scroll down and click on the third related search. On the new results page that comes, do the same. Then, on the next page, click the 5th search result and read the article. This will automatically randomize your reading!</li> <li> Wonder about an attribute of a normal object. For example, you can think of the shape (attribute) of a bottle (object) and then Google to learn more about the factors invovled in shaping a bottle.</li> <li> Google/YouTube "a day in the life of _________" where _________ is any profession you find fascinating.</li> </ol> </p> <p class="text-justify top-space-20">Do not worry about how all this learning is going to help you. Do not worry about how you will apply this knowledge. These exercises are to make you think in different ways, make you see the world in different ways. For now, it is extremely important that you choose interesting topics and not useful topics! <br><br> Side note: This technique will not help you in the short term. But in the long term, having a wide base of knowledge will make it easier for you to connect and place new information that you accquire.</p> <h4 class="headline thin-text top-space-30"><u>3. Practice purposeless exploration every day</u></h4> <p class="text-justify top-space-20">Practice this sort of purposeless exploration every day. But do it only for a short amount of time - say 10-minutes. The practice has to be deliberate and time-boxed and what you learn should not be concentrating on the same subject.</p> <h4 class="headline thin-text top-space-30"><u>4. Remain patient</u></h4> <p class="text-justify top-space-20">Do this sort of deliberate micro-learning for the next several months even if it seems like a waste of time. If you stick to this habit, you will notice that you have begun to become more comfortable with the new and unknown. You will also have more hooks to help you store, connect and synthesize new information. When you stick to this process, you will notice that knowledge has this compounding effect.</p> <h3 class="headline thin-text top-space-30"><u>Conclusion</u></h3> <p class="text-justify top-space-20">This post outlines some advice for increasing your technical exposure. It advocates practicing some deliberate micro-learning on a daily basis. There are several ideas (quick to execute!) you can try to keep your learning fresh. Hopefully, trying some of these ideas makes your learning a bit more fun!</p> <h3 class="headline thin-text top-space-30"><u>About me</u></h3> <p class="text-justify top-space-20">I am Arun. I run <a href="https://qxf2.com/?utm_source=increaseTechnicalExposure&utm_medium=click&utm_campaign=From%20trainingseniorqa">Qxf2 Services</a>. My company mostly hires highly experienced senior engineers with very good testing fundamentals. Many of us started testing before webdriver was a thing. The downside of this hiring strategy is that we end up having QA engineers who are good at testing but are insufficiently technical. So we naturally spend a lot of time and effort in addressing this problem of upskilling senior QA engineers. A lot of the material on the <a href="https://qxf2.com/blog">Qxf2 Blog</a> and in our training course is what we use to help new hires at Qxf2. I hope you find the material we share useful!</p> <hr> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/index.html
{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <img src="/static/img/worried_man.png" class="img-fluid rounded mx-auto d-block"> <h2 class="headline thin-text top-space-30 text-center">Hey QA, are your limited technical skills a threat to your job security?</h2> <p class="text-justify top-space-30">Welcome to a training program that upgrades your technical skills and increases your job security. We noticed a growing problem in the QA world. There are many good testers who succeeded at their jobs. Unfortunately, that very success kept them constantly busy for years and prevented them from regularly upskilling themselves. Now, they find it hard to catch up with the new challenges that come with a rapidly changing technology landscape.</p> <p class="text-justify top-space-30">To solve this problem, we have designed a non-traditional training program to help experienced QA. The training approach simulates real-life work experiences and makes you learn tech tools. You choose a software application you want to test and let us know. We will pick weekly tasks to help you test the application. The tasks chosen will not only be useful but will also force you to increase your technical skills. The course spans 12-weeks and requires a total time investment of 120 hours. At the end of the training program you can add a lot of relevant technical tools to your resume. </p> <p class="text-justify top-space-30">If you are interested in joining this program - cool! But this program is not meant for everyone. So we strongly recommend you carefully read through this entire website. After that, if you are still keen on joining, please write to Arun ([email protected]).</p> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/why-join-senior-qa-training.html
{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <img src="/static/img/why-join.png" class="img-fluid rounded mx-auto d-block"> <h2 class="headline thin-text top-space-30 text-center">Reasons to join our Senior QA Training Program</h2> <p class="text-justify top-space-10"> <ul class="text-justify"> <li>As far as we know, this is the only training program to specifically target experienced QA engineers</li> <li>You can list many relevant tools on your resume</li> <li>You don't have to attend multiple trainings to gain experience in different tools</li> <li>We have innovative training methods</li> <li>This training program's exercises developed by experienced QA who worked on multiple relevant projects</li> <li>We have successfully re-trained senior QAs with zero coding background to take up technical challenges at their current job.</li> </ul> </p> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/why-not-join-senior-qa-training.html
{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <img src="/static/img/tsqa-why-not-join.png" class="img-fluid rounded"> <h2 class="headline thin-text top-space-50 text-center">Reasons NOT to join our Senior QA Training Program</h2> <p class="text-justify top-space-30">We do not want to mislead you. We did not design this program for everyone. In fact, it takes a special type of person to persist through our program. And on top of that,<strong><u>we do not offer your money back ... ever!</u></strong>. So please think very carefully before commiting to join the program. Here are some reasons why our approach may not suit you:</p> <p class="text-justify top-space-30"> <ul class="text-justify"> <li>We expect the journey to be demoralizing because you are developing new habits!</li> <li>Your habit of 'Read-research-try' will have to change</li> <li>We provide only clues, no right answers</li> <li>We are not trainers - we are engineers</li> <li>There is no spoon-feeding</li> <li>We offer highly limited support</li> <li>Our communication is asynchronous</li> <li>We use chat and no talk!</li> <li>Our program is not targeted towards clearing interviews at large companies</li> <li>We do not help you with theory and definitions</li> <li>No money back ... for any reason! </li> <li>There are no extensions to the training period </li> <li>We expect a significant time commitement: 12-weeks and 120-hours in total</li> <li>This is NOT self-paced learning</li> </ul> </p> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/base.html
<!-- templates/base.html --> <!DOCTYPE html> <html> <head> <!-- Google tag (gtag.js) --> <script async src="https://www.googletagmanager.com/gtag/js?id=G-1WSF08CXT4"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-1WSF08CXT4'); </script> <meta charset="utf-8"> {% if title %} <title>{{ title }}</title> {% else %} <title>Training Senior QA</title> {% endif %} <link href="https://fonts.googleapis.com/css?family=Abel" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Dosis" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"> <link href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css" rel="stylesheet"> <link href="/static/css/tsqa_style.css" rel="stylesheet"> </head> <body> <nav class="navbar navbar-expand-sm bg-info sticky-top"> <!-- Links --> <a class="navbar-brand" href="/"> <img src="/static/img/tsqa_logo.png" class="d-inline-block align-top" width="60" height="60"> </a> <ul class="navbar-nav navbar-brand"> <li class="navbar-brand"> <h4 class="thin-text white-text">A Unique Training Program for Senior QA</h4> </li> </ul> <ul class="navbar-nav ml-auto"> <li class="nav-item dropdown"> <a class="thin-text white-text nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Menu </a> <div class="dropdown-menu dropdown-menu-right" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="/">Home</a> <a class="dropdown-item" href="/senior-qa-training-approach">Approach</a> <a class="dropdown-item" href="/senior-qa-training-plan">Program structure</a> <a class="dropdown-item" href="/senior-qa-training-benefits">Benefits</a> <a class="dropdown-item" href="/senior-qa-training-samples">Samples</a> <a class="dropdown-item" href="/senior-qa-trainees">Target audience</a> <a class="dropdown-item" href="/why-join-senior-qa-training">Why join us?</a> <a class="dropdown-item" href="/why-not-join-senior-qa-training">Reasons not to join</a> <a class="dropdown-item" href="/before-you-join">Disclaimers</a> <a class="dropdown-item" href="/senior-qa-training-pricing">Pricing</a> </div> </li> </ul> </nav> <div class=container> <div class="row"> <div class="top-space"> {% block content %} {% endblock %} </div> </div> <div class="row-fluid"> <div class="top-space"> <p class="text-center tsqa_copyright"> © Arunkumar Muralidharan 2018 - <script>document.write(new Date().getFullYear())</script> </p> </div> </div> </div> <!--JavaScript libraries--> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js"></script> <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </body> </html>
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/how-to-become-technical-tester.html
{% extends 'base.html' %} {% block title %}How to become a technical tester{% endblock %} {% block content %} <p class="text-justify top-space-20"> I hear a growing chorus of similar-sounding questions from folks who feel trapped as 'manual testers' but find learning automation boring. Their problems sound a bit like this: <blockquote class="blockquote"> <p class="quote-text text-right">I am bored with my current job as a manual QA - seem to be having a hard time "preparing" for my new journey. What can I do?</p> </blockquote> </p> <hr> <h2 class="headline thin-text top-space-30 text-center">Ease your transition into technical testing</h2> <p class="text-justify top-space-20">Many testers spend nights and weekends trying to learn a programming language and (what else?) Selenium. But something never feels right. The much-hyped automation seems slow and flaky and much less efficient than 'manual testing'. Automation, to them, is at best a poor and insufficient substitute to what they already do well as a human. And yet, they tell themselves that they 'have to learn automation' because our field is becoming more and more technical. If you are someone who is holding your nose and learning automation just so you can be a bit more technical, I have a bit of good news for you - learning automation is not your only path to becoming more technical.</p> <h3 class="headline thin-text top-space-30"><u>Technical Testing != Automation</u></h3> <img src="/static/img/technical-testing-not-automation.png" class="img-fluid rounded mx-auto d-block" alt="Technical QA != Automation" style="width: 30%"> <p class="text-justify top-space-20">Do not fall into the trap of equating writing automation to being technical. Technical QA involves being able to understand systems and design tradeoffs, adhere to good engineering principles, perform complex setup operations, create tools that enable other testers and much more. As you become more technical, you will realize that the 'manual' vs 'automation' mental model makes no sense at all!</p> <p class="text-justify top-space-20">As an example, imagine testing a voice assistant like Alexa. Testers probably have to think of voice and ambient noise and semantic structure and accents and language patterns. They need to understand how Alexa learns and how data flows and how questions are stored. There are so many technical avenues for a technical tester to provide value to the team in such scenarios.</p> <h3 class="headline thin-text top-space-30"><u>What you can try instead</u></h3> <img src="/static/img/one-leg-new-familiar.png" class="img-fluid rounded mx-auto d-block" alt="One leg in the familiar" style="width: 30%"> <p class="text-justify top-space-20">Start with where you are. And start with what you know well. Start with a hobby and then apply your 'tester brains' to that hobby. If you love music, try to muck around with Spotify and test one tiny aspect of their recommendation algorithm. Doing that will automatically take you down rabbit holes of machine learning and statistics and big data. Pick the intersections of testing and technology that interest you. This way you will have one leg firmly anchored in the familiar while you step into the unknown. Your expertise/interest in your hobby should lead you to ask interesting questions that will then inform the design of good tests. The technical learning will follow.</p> <h3 class="headline thin-text top-space-30"><u>A concrete example</u></h3> <p class="text-justify top-space-20">In our senior QA training program, we expect the trainee to pick an app that they want to test. But if they cannot, we default to using an application we call the PTO Detector as the backdrop for the training. At Qxf2, we have a channel where employees announce their leave plans. We call this channel the 'PTO Channel' where PTO stands for <b>P</b>ersonal <b>T</b>ime <b>O</b>ff. When an employee posts a message, the PTO detector evaluates if the message is a 'leave-message' or not. If it thinks the employee is asking for leave, it posts back a 'PTO detected' message.</p> <img src="/static/img/example_pto_detection.png" class="img-fluid rounded mx-auto d-block" alt="example PTO detection" style="width: 60%"> <p class="text-justify top-space-20">The PTO detector application is a set of microservices loosely coupled by some AWS SQS and AWS Lambdas. The architecture of this entire setup looks something like this: </p> <img src="/static/img/pto-detector-architecture.png" class="img-fluid rounded mx-auto d-block" alt="PTO detector architecture" style="width: 70%"> <p class="text-justify top-space-20">This relatively simple application has the potential to let you ease into a more technical level of testing. There are so many paths that a curious tester can take. <br><br> Maybe you are so used to only 'manual testing' that you start by trying out different sentences. From there you could branch into finding out the kind of mathematical metrics that are used to report the accuracy of the algorithm. <br><br> If you find that kind of stuff boring, maybe you want to focus on the variety of ways Skype messages are encoded and transmitted. E.g.: what happens when you quote someone or send an emoji? <br><br> Maybe you are already fairly technical and want to branch into the DevOps side of things. You can write some tests configure GitHub Actions for yourself. As part of doing this exercise, I ended up modifying someone else's GitHub Action to deploy lambdas. <br><br> Maybe you are interested in Machine Learning. You could start by examining the scikit-learn model that is used and looking at the model's top features. <br><br> Perhaps you want to learn more about monitoring and alerting of production models? Maybe you just want to learn to write bread and butter GUI and API tests? Maybe you want to know how to create contract tests for a couple of microservices? Or you just want to get used to manually testing applications hosted on an AWS stack? The possibilities are endless.</p> <h3 class="headline thin-text top-space-30"><u>Conclusion</u></h3> <p class="text-justify top-space-20">If you are looking to become a more technical tester, do not start with learning automation. Instead, start with a hobby and find a way to test some aspect of your hobby. Follow the rabbit holes that this effort leads you and you will automatically become a more technical tester. Good luck!</p> <h3 class="headline thin-text top-space-30"><u>About me</u></h3> <p class="text-justify top-space-20">I am Arun. I run <a href="https://qxf2.com/?utm_source=howBecomeTechnical&utm_medium=click&utm_campaign=From%20trainingseniorqa">Qxf2 Services</a>. My company mostly hires highly experienced senior engineers with very good testing fundamentals. Many of us started testing before webdriver was a thing. The downside of this hiring strategy is that we end up having QA engineers who are good at testing but are insufficiently technical. So we naturally spend a lot of time and effort in addressing this problem of upskilling senior QA engineers. A lot of the material on the <a href="https://qxf2.com/blog">Qxf2 Blog</a> and in our training course is what we use to help new hires at Qxf2. I hope you find the material we share useful!</p> <hr> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/before-you-join.html
{% extends 'base.html' %} {% block title %}Read this before you join!{% endblock %} {% block content %} <img src="/static/img/before-you-join.png" class="img-fluid rounded mx-auto d-block" style="width: 60%"> <h2 class="headline thin-text top-space-30 text-center">Things to note before you join our training program !</h2> <p class="text-justify top-space-20"> We have said this on other pages, but we want to repeat some key points one last time: <ul class="text-justify"> <li>The course will be challenging since it simulates real work experiences</li> <li>We won't refund your money even if you quit because the style of the course does not suit you</li> <li>You must be ok with the time commitment of 10-hours a week over the next 12-weeks</li> <li>You must be available to attend a 1-hour meeting every Wednesday over Google Meet</li> <li>The training program is designed exculsively for experienced QA engineers</li> </ul> </p> <p class="text-justify top-space-20">After reading through all the content on this website, if you are still interested, please write to Arun ([email protected]) asking about availability and pricing.</p> <hr> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/senior-qa-training-approach.html
{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <img src="/static/img/baby_learning_language.png" class="img-fluid rounded"> <h2 class="headline text-center">Don't think you cannot execute before studying theory</h2> <p class="text-justify top-space-30">Our approach in this program will resemble the way we all learnt testing. We did not pick up testing by studying theory. Instead, we took a more hands-on and practical approach to learn testing. This learning approach of studying after executing was not limited to only testing. We learnt how to speak our mother tongues before we studied grammar and the alphabet.</p> <p class="text-justify top-space-30">As an example of this approach, when we teach you Python, we will first have you execute some code. Then, before introducing the syntax, we will challenge you to read and understand the code. We will also make you review, edit and fix errors in other's code before asking you to write your own code.</p> <p class="text-justify top-space-30"><strong>Note: </strong>Our approach has some grounding in learning theory too. If you are interested, you can Google for concepts of communities of practice, peripheral learning, contextual learning, spaced repitition, backfilling knowledge, etc.</p> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/senior-qa-trainees.html
{% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} <img src="/static/img/target-audience.png" class="img-fluid rounded mx-auto d-block"> <h2 class="headline thin-text top-space-50 text-center">Whom is this training program meant for?</h2> <p class="text-justify top-space-10">This training program is meant for experienced testers with limited tech and coding background. You will find this course useful if you: <ul> <li>feel your technical skills are getting outdated</li> <li>are looking to gain practical experience with Python, Selenium, API testing, DevOps basics</li> <li>have little scope to learn new technology at your current job</li> <li>prefer training that has minimal amount of theory</li> <li>like learning by doing practical challenges</li> <li>are looking for a job change</li> </ul> </p> <p class="text-justify top-space-10">We consider you an experienced tester if you: <ul> <li>have lead the testing effort on your team</li> <li>managed and co-ordinated the testing of big releases</li> <li>mentored junior QA</li> <li>have at least 6 years of experience as a QA</li> </ul> </p> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/senior-qa-training-benefits.html
{% extends 'base.html' %} {% block title %}Senior QA Training Benefits{% endblock %} {% block content %} <img src="/static/img/tsqa_benefits.png" class="img-fluid rounded mx-auto d-block"> <h2 class="headline thin-text top-space-30 text-center">At the end of this course</h2> <p class="text-justify top-space-20"> At the end of this course, you can expect the following. You will:</p> <p><span class="text-success">&#10004; </span>have adopted a new mindset about work</p> <p><span class="text-success">&#10004; </span>show no fear of new technical words</p> <p><span class="text-success">&#10004; </span>have a bias towards trying things out</p> <p><span class="text-success">&#10004; </span>have a modern toolset listed on your resume</p> <p><span class="text-success">&#10004; </span>have public projects that you have shared online</p> <p><span class="text-success">&#10004; </span>have an active GitHub page with code and videos of automated tests</p> <p><span class="text-success">&#10004; </span>have increased faith in your problem solving skills</p> <p><span class="text-success">&#10004; </span>have picked up multiple way to learn on your own</p> <p class="text-justify "> The course is deliberately structured to give you many small wins. And with steadily accumulating small wins you get momentum and confidence. We are certain that at the end of the training program you will feel good about your technical skills and will be amazed at how far you progressed in just 12-weeks! </p> <hr> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/senior-qa-training-plan.html
{% extends 'base.html' %} {% block title %}Senior QA Training Plan{% endblock %} {% block content %} <img src="/static/img/program-structure.png" class="img-fluid rounded mx-auto d-block"> <h2 class="headline thin-text top-space-30 text-center">Structure of the program</h2> <p class="text-justify top-space-30">In this training program, you will learn by doing. The structure of this program is designed to simulate real-life QA work at small, agile software startups. <ol class="text-justify"> <li>You choose a software application you want to test</li> <li>You must have access to the application ... we don't</li> <li>We work together to figure out a next step that is both <u>useful</u> and <u>improves your technical knowledge</u> </li> <li>You will communicate with us over Skype and Jira</li> <li>The training is completely remote</li> <li>You will work in twelve 1-week sprints</li> <li>In each sprint, you will be assigned tickets to work on</li> <li>You will have 1-hour demo + sprint planning meeting on Wednesdays</li> <li>The sprint review and planning meeting will happen on Google Meet</li> <li>You need to spend 10-hours a week spread over at least 5 days</li> <li>The program is designed to make you revisit topics multiple times</li> </ol> </p> <p class="text-justify top-space-30">We have taken great care to structure the training program to suit the learning habits a tech novice. For example, we initially give you highly detailed, prescriptive tickets to work on. Gradually, we taper down the amount of instruction and guidance we give you. Towards the end of the program, you will simply be given one line goals and expected to deliver ... just like you what is likely to happen at small startups!</p> <p class="text-justify top-space-30">We have also put in a lot of effort in making the examples fun and creative so that learners don't quit easily. For example, instead of teaching you SQL, we make you test a data heavy application that we have seeded with bugs. You cannot proceed to the second stage unless you find the bug in the first stage. And the only way you can find the bugs we have seeded are if you pick up just enough SQL to validate the numbers shown.</p> <hr> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/senior-qa-upskill-fail.html
{% extends 'base.html' %} {% block title %}Testers, upskill yourself the right way{% endblock %} {% block content %} <p class="text-justify top-space-20"> I come across motivated testers who have sincerely tried to upskill themselves. Their stories end up something like this: <blockquote class="blockquote"> <p class="quote-text text-right">I have tried to upskill myself. I learnt Python and Selenium. But unfortunately I never really got the chance to apply them at my job. I could not practice at home either. As a result, I have forgotten everything!</p> </blockquote> </p> <hr> <h2 class="headline thin-text top-space-30 text-center">How to upskill yourself as a tester</h2> <p class="text-justify top-space-20">Maybe your attempt at upskilling yourself has met a similar fate? Maybe after all your efforts, you continually end up as a 'perpetual beginner'? If so, read on for some tips that I have.</p> <h3 class="headline thin-text top-space-30">It's probably not you</h3> <p class="text-justify top-space-20">If you were motivated enough to spend nights and weekends studying and then forgot stuff because you had no outlet to apply your learning - the problem is probably not you. It is likely that you chose poor tutorials. See if the material you chose had these drawbacks: <br><br> a. <i>Over-simplified examples:</i> Most tutorials on the Internet are designed to take you from ignorant to beginner. While that is better than nothing, your problem solving skills are not engaged when you do these 'toy' examples. You end up a passive consumer. Your curiousity is not sufficiently engaged. Worse, you lose out on several learning moments that come from having to take engineering decisions in sufficiently complex problems. <br><br> b. <i>Incorrect learning muscles:</i> Most online tutorials engage the wrong set of learning muscles in testers. As testers, we are good at observing and searching and making connections. Shouldn't our learning material allow us to use these strengths? We should not have to over-rely on memory and procedure. Our training material should probably begin with "That seems fishy. Let me investigate ..." <br><br> c. <i>Single focus:</i> Any work you do in your day job involves a combination of skills and knowledge in multiple areas. So tutorials with one single focus are unrealistic. And not only that, learners are mislead into thinking that they need to sequentially learn subject after subject before they can apply their new knowledge on something useful. No wonder most people give up! </p> <h3 class="headline thin-text top-space-30">What you can try instead</h3> <p class="text-justify top-space-20">I have a couple of suggestions to make your learning stick. <br><br> <u><h5>Option 1: Find a problem that motivates you</h5></u> This will sound counter-intuitive - but do not start with the technology you want to learn. Begin with an interesting problem instead! Then, keep learning just enough to help you solve the problem. Do not bother about gaining in-depth knowledge about a tool. Instead, trust that as you keep solving interesting problems for yourself, your arsenal of tools, techniques and knowledge will continue to grow. As an example, I used to like investing in stocks. When I was learning Python (back in 2006!), I wrote a script to scrape Google Finance pages for my portfolio and display the day's gain/loss. I knew very little about Python and my code was horrible! But in the course of solving this practical problem for myself, I discovered many Python modules and a whole lot of other practical programming ideas that I could not have gained directly from a book. Unknown to me at that time, the knowledge really helped me in several testing contexts. Even today, most of my learning and upskilling starts with my own problems and hobbies. <br><br> <u><h5>Option 2: Find creative exercises</h5></u> Put some effort into finding high quality tutorials. My company, <a href="https://qxf2.com/?utm_source=upskillRightWay&utm_medium=click&utm_campaign=From%20trainingseniorqa">Qxf2 Services</a>, puts out many free exercises that are aimed at testers. Our exercises are designed to make you work on mutliple areas at once. They are neither too simple nor are they so complex that you will take forever to finish. Wherever possible, we let you (the tester) start by identifying bugs or errors. The learning happens as you chase down the bug and try to figure out the technical reasons behind it. <br><br> Here is a sampling of our free, open-sourced offerings: <br><br> 1. <a href="https://github.com/qxf2/wtfiswronghere">wtfiswronghere</a>: Improve your Python by fixing errors. We present small code samples that have errors in them. This tutorial is aimed at Python beginners. You will simultaneously learn to use git, GitHub, git bash, Visual Studio Code and Python. <br><br> 2. <a href="https://github.com/qxf2/makemework">makemework</a>: Fix the issues in this repo and make this program work. This exercise is aimed at folks who have already learnt to write basic Python but are looking for more realistic challenges that involve reading a large enough codebase, exploring file structures and making changes to an existing codebase. <br><br> 3. <a href="http://weathershopper.pythonanywhere.com/">Weather Shopper</a>: A web application to hep testers learn Selenium and practice programming simultaneously. Each page will have an 'i' icon that you can click to find the task you need to complete. <br><br> 4. <a href="https://github.com/qxf2/cars-api">Cars App</a>: A sample REST application to help testers learn to write API automation. You will learn to use git, git bash, (possibly) Docker, API libraries in a language of your choice and/or an API testing tool of your choice. <br><br> 5. <a href="http://trainingdatabase.pythonanywhere.com/">Database trainer</a>: Work with a buggy web application that uses MySQL as a backend. Validate the data shown on the web application by performing SQL queries. <br><br> 6. <a href="https://practice-testing-ai-ml.qxf2.com/is-pto">Is PTO?</a>: Use this site to practice testing AI/ML based applications. Post a sentence and the app will tell you if you are applying for leave or not. Your goal is to test the machine learning algorithm and figure out its drawbacks. <br><br> All these tools were created by <a href="https://qxf2.com/team">Team Qxf2</a>. The code assocoated with these tools has been open-sourced under the MIT License. So feel free to fork our repos and modify them to suit your needs! </p> <h3 class="headline thin-text top-space-30">Conclusion</h3> <p class="text-justify top-space-20">If you are a motivated tester who has had problems upskilling despite your best efforts - consider starting with a problem you find interesting OR use some of the free exercises listed on this post. Good luck!</p> <h3 class="headline thin-text top-space-30">About me</h3> <p class="text-justify top-space-20">I am Arun. I run <a href="https://qxf2.com/?utm_source=upskillRightWay&utm_medium=click&utm_campaign=From%20trainingseniorqa">Qxf2 Services</a>. My company mostly hires highly experienced senior engineers with very good testing fundamentals. More than half of us have a dozen plus years of experience. The downside of this hiring strategy is that we end up having QA engineers who are good at testing but are insufficiently technical. So we naturally spend a lot of time and effort in addressing this problem of upskilling senior QA engineers. A lot of the material on the <a href="https://qxf2.com/blog">Qxf2 Blog</a> and in our training course is what we use to help new hires at Qxf2 to enhance their technical skills and knowledge. I hope you find the material we share useful!</p> <hr> {% endblock %}
0
qxf2_public_repos/training-website
qxf2_public_repos/training-website/templates/senior-qa-training-samples.html
{% extends 'base.html' %} {% block title %}Senior QA Training Benefits{% endblock %} {% block content %} <img src="/static/img/samples.png" class="img-fluid rounded mx-auto d-block"> <h2 class="headline thin-text top-space-30 text-center">Sample training material</h2> <p class="text-justify top-space-30">We designed our training program to use several different mediums to teach you a whole host of technology. In fact, a lot of what makes our training program unique is our creatively designed material. Rather than tell you about it, we thought we would expose you to a small sample of some things you will come across.</p> <h3 class="thin-text top-space-50">1. New tools</h3> <p class="text-justify top-space-10">We have developed several in-house tools specifically to train QA. These tools are designed to simulate real work and will help you break old habits and let you see your work from a new perspective. For example, to help you improve your coding skills, we have created a <a href="https://github.com/qxf2/wtfiswronghere">set of challenges with errors</a> in them. Fixing these errors (just like you would at your real job) ends up being a nice and natural way for you to learn a new language.</p> <h3 class="thin-text top-space-50">2. Jira tickets</h3> <p class="text-justify top-space-10">The primary way we communicate with you is through Jira. Here is an example of a ticket you will be given to work on.</p> <img src="/static/img/sample_jira_01.png" class="img-fluid rounded mx-auto d-block"></img> <h3 class="thin-text top-space-50">3. A training portal</h3> <p class="text-justify top-space-10">We will occassionally use a training portal we developed to communicate some instructions and walk you through come thought processes. You can take a look at our <a href="http://qxf2trainer.pythonanywhere.com">training portal</a> that we have populated with a couple of sample exercises. You can use the username <strong>demo</strong> and password <strong>training123</strong>.</p> <img src="/static/img/tsqa_training_portal.png" class="img-fluid rounded mx-auto d-block top-space-30"></img> <h3 class="thin-text top-space-50">4. Blog posts</h3> <p class="text-justify top-space-10"><a href="https://qxf2.com">Qxf2</a> (the company we work for) has a very popular testing-focused blog. So sometimes, we will ask you to follow blog posts. More often than not, we will be refering you to blog posts that we have written. And don't worry - these blog posts have been carefully selected keeping your skill levels in mind. At the start of the training program, the blog posts will be elaborate and very prescriptive. As you advance, we will make you learn from less elaborate posts.</p> <p class="text-justify top-space-10"><i>Example 1:</i> Once you have used git for a bit and are wondering how to understand it conceptually, you will be asked to refer to: <a href="https://qxf2.com/blog/git-for-testers/">Testers, get started with git</a>.</p> <p class="text-justify top-space-10"><i>Example 2:</i> When we ask you to make an open source contribution to a GitHub project, you will be asked to refer to: <a href="https://qxf2.com/blog/github-workflow-contributing-code-using-fork/">Contributing code to GitHub projects</a>.</p> <h3 class="thin-text top-space-50">5. Slide shows</h3> <p class="text-justify top-space-10"> We will arm you with a variety of slide shows to help you learn concepts. We are sharing one example with you here: </p> <div align="center"> <iframe src="https://docs.google.com/presentation/d/e/2PACX-1vR81BTE16XZSqrX6UHF1g5rFoSqlMNvdk974AvfXjuJ31ddQkN1PKw1wRQ-_P3JyOLKMaYcB7pikdiv/embed?start=false&loop=false&delayms=10000" frameborder="0" width="960" height="569" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe></div> <h3 class="thin-text top-space-50">6. Emails</h3> <p class="text-justify top-space-10">Through this training program, we will share some of our experiences that we think are relevant to you. You can also expect to receive many tips to make your life easier. For example, here is a snippet of an email you will receive teaching you how to apply to small companies by using the skills you picked up as part of this training program.</p> <img src="/static/img/tsqa_email_sample.png" class="img-fluid rounded mx-auto d-block top-space-30"></img> <h3 class="thin-text top-space-50">7. Carefully chosen multi-purpose tasks</h3> <p class="text-justify top-space-10">Everything you produce during this training will help you in your career. We try our best to pick weekly assignments that are just out of your comfort zone at multiple levels. For example, if you already know Selenium and a bit of Unix but haven't had exposure to CI/CD, one of your tasks will be to implement CI/CD for the software application you have chosen to test.</p> <hr> {% endblock %}
0
qxf2_public_repos
qxf2_public_repos/daily-messages/conftest.py
""" Defining pytest session details """ import os import sys import pytest import utils.delete_test_log_files as delete sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) def pytest_sessionstart(session): """ pytest session start """ session.results = dict() @pytest.hookimpl(tryfirst=True, hookwrapper=True) def pytest_runtest_makereport(item, call): """ Running wrapper method """ outcome = yield result = outcome.get_result() if result.when == 'call': item.session.results[item] = result def pytest_sessionfinish(session): """ pytest session finish """ failed_amount = sum(1 for result in session.results.values() if result.failed) if failed_amount == 0: print(f'\n{failed_amount} failure results') delete.delete_pickle_file() delete.delete_pact_json_file()
0
qxf2_public_repos
qxf2_public_repos/daily-messages/LICENSE
MIT License Copyright (c) 2020 qxf2 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
0
qxf2_public_repos
qxf2_public_repos/daily-messages/requirements.txt
coverage==5.2.1 fastapi==0.60.2 freezegun==1.1.0 pact-python==1.2.6 pytest==6.0.1 python-json-logger==0.1.11 requests==2.24.0 uvicorn==0.11.8 mock==4.0.3
0
qxf2_public_repos
qxf2_public_repos/daily-messages/Dockerfile
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.7 COPY ./ /app COPY requirements.txt . RUN pip --no-cache-dir install -r requirements.txt
0
qxf2_public_repos
qxf2_public_repos/daily-messages/.coveragerc
[run] omit = venv*/ messages/* tests/*
0
qxf2_public_repos
qxf2_public_repos/daily-messages/README.md
# daily-messages A collection of messages, reminders and questions that need to be socialized within Qxf2. The consumers of these endpoints are the training-bot, daily-message-bot and new-hire-bot. ### SETUP 1. Install the requirements `pip install -r requirements.txt` 2. Start the app `uvicorn main:app` 3. To check if the app started, in a new terminal `curl http://127.0.0.1:8000/message` 4. If all goes well, you should see a message displayed ### How to run test 1. Run the command `coverage run -m pytest` for running test cases. 2. To check the coverage, you can run `coverage report`-(Note- As a practice we run the coverage for unit tests only.)
0
qxf2_public_repos
qxf2_public_repos/daily-messages/main.py
""" Endpoints for reminders and daily messages """ import datetime import os import pickle import random from datetime import date from fastapi import FastAPI from messages import reminders from messages import senior_qa_training from messages import comments_reviewer from messages import desk_exercises from messages import icebreaker app = FastAPI() CURR_FILE_PATH = os.path.dirname(os.path.abspath(__file__)) MESSAGES_PATH = os.path.join(CURR_FILE_PATH, 'messages') CULTURE_FILE = os.path.join(MESSAGES_PATH, 'culture.txt') SEP20_INTERNS_FILE = os.path.join(MESSAGES_PATH, 'sep20_interns.txt') SENIOR_QA_TRAINING_PICKLE = os.path.join(MESSAGES_PATH, 'senior_qa_training.pickle') FIRST_REVIEWER_PICKLE = os.path.join(MESSAGES_PATH, 'first_reviewer.pickle') SECOND_REVIEWER_PICKLE = os.path.join(MESSAGES_PATH, 'second_reviewer.pickle') DESK_EXERCISES_PICKLE = os.path.join(MESSAGES_PATH, 'desk_exercises.pickle') ICEBRAKER_PICKLE = os.path.join(MESSAGES_PATH, 'icebreaker.pickle') def get_pickle_contents(filename): "Return the first variable of a pickle file" contents = None if os.path.exists(filename): with open(filename, 'rb') as file_handler: contents = pickle.load(file_handler) return contents def update_pickle_contents(filename, content): "Update the contents of the pickle file" with open(filename, 'wb+') as file_handler: pickle.dump(content, file_handler) def get_desk_exercise_index(): "Return the exercise index dict" exercise_index_dict = get_pickle_contents(DESK_EXERCISES_PICKLE) exercise_index_dict = {} if exercise_index_dict is None else exercise_index_dict return exercise_index_dict def set_desk_exercise_index(exercise_index_dict): "Update the exercise index dict for desk exercises" update_pickle_contents(DESK_EXERCISES_PICKLE, exercise_index_dict) def get_icebraker_index(): "Return the exercise index dict" icebraker_index_dict = get_pickle_contents(ICEBRAKER_PICKLE) icebraker_index_dict = {} if icebraker_index_dict is None else icebraker_index_dict return icebraker_index_dict def set_icebraker_index(icebraker_index_dict): "Update the exercise index dict for icebraker exercises" update_pickle_contents(ICEBRAKER_PICKLE, icebraker_index_dict) def get_senior_qa_training_user_index(): "Return the user index dict" user_index_dict = get_pickle_contents(SENIOR_QA_TRAINING_PICKLE) user_index_dict = {} if user_index_dict is None else user_index_dict return user_index_dict def set_senior_qa_training_user_index(user_index_dict): "Update the user index for the senior QA training messages" update_pickle_contents(SENIOR_QA_TRAINING_PICKLE, user_index_dict) def get_weekday(): "Return the weekday" return datetime.datetime.today().weekday() def get_today_date(): "Return today's date" return datetime.datetime.today().strftime('%Y-%m-%d') def get_messages_from_file(filename): "Return a list of culture related messages" lines = [] with open(filename, 'r') as file_handler: lines = file_handler.readlines() lines = [line.strip() for line in lines] return lines def get_first_comment_reviewer_cycle_index(): "Return cycle index for comment reviewers" cycle_index_dict = get_pickle_contents(FIRST_REVIEWER_PICKLE) cycle_index_dict = {} if cycle_index_dict is None else cycle_index_dict return cycle_index_dict def set_first_comment_reviewer_cycle_index(cycle_index_dict): "Update cycle index for comment reviewers" update_pickle_contents(FIRST_REVIEWER_PICKLE, cycle_index_dict) def get_second_comment_reviewer_cycle_index(): "Return user index for comment reviewers" cycle_index_dict = get_pickle_contents(SECOND_REVIEWER_PICKLE) cycle_index_dict = {} if cycle_index_dict is None else cycle_index_dict return cycle_index_dict def set_second_comment_reviewer_cycle_index(cycle_index_dict): "Update cycle index for comment reviewers" update_pickle_contents(SECOND_REVIEWER_PICKLE, cycle_index_dict) def get_first_reviewer(cycle1: str = ''): "get first reviewer" lines = comments_reviewer.first_reviewers if cycle1: cycle_index_dict = get_first_comment_reviewer_cycle_index() reviewer1_index = cycle_index_dict.get(cycle1, 0) first_reviewer = lines[reviewer1_index%len(lines)] cycle_index_dict[cycle1] = reviewer1_index + 1 set_first_comment_reviewer_cycle_index(cycle_index_dict) else: first_reviewer = random.choice(lines).strip() return first_reviewer def get_second_reviewer(cycle2: str = ''): "get second reviewer" lines = comments_reviewer.second_reviewers if cycle2: cycle_index_dict = get_second_comment_reviewer_cycle_index() reviewer2_index = cycle_index_dict.get(cycle2, 0) second_reviewer = lines[reviewer2_index%len(lines)] cycle_index_dict[cycle2] = reviewer2_index + 1 set_second_comment_reviewer_cycle_index(cycle_index_dict) else: second_reviewer = random.choice(lines).strip() return second_reviewer def get_distinct_reviewers(): "Getting distinct reviewers" first_reviewer = get_first_reviewer() second_reviewer = get_second_reviewer() message = f"{first_reviewer}, {second_reviewer} are comments reviewers" return message @app.get("/") def index(): "The home page" return {"msg":"This is the endpoint for the home page. /message \ and /reminder are more useful starting points."} @app.get("/message") def get_message(): "Return a random message" lines = get_messages_from_file(CULTURE_FILE) message = random.choice(lines) return {'msg':message} @app.get("/culture/all") def get_all_culture_messages(): "Return all available culture messages" return {'msg':get_messages_from_file(CULTURE_FILE)} @app.get("/reminder") def get_reminder(): "Return a reminder based on day of the week" weekday = get_weekday() #Note: Monday is 0 and Sunday is 6 lines = reminders.messages.get(weekday, ['']) message = "<b>Reminder:</b> " + random.choice(lines) return {'msg':message} @app.get("/sep20-interns") def get_sep20_message(): "Return a message for the Sep 2020 internship" lines = get_messages_from_file(SEP20_INTERNS_FILE) return {'msg': random.choice(lines)} @app.get("/training") def get_snior_qa_training_message(user: str = ''): "Return a message for senior QA training" lines = senior_qa_training.messages user_index_dict = {} if user: user_index_dict = get_senior_qa_training_user_index() message_index = user_index_dict.get(user, 0) message = lines[message_index%len(lines)] user_index_dict[user] = message_index + 1 set_senior_qa_training_user_index(user_index_dict) else: message = random.choice(lines) return {'msg': message} @app.get("/comment-reviewers") def get_comment_reviewers(): """ "Returns message including comment reviewers names" """ if date.today().weekday() == 3: message = get_distinct_reviewers() else: message = "Either today is not Thursday or data is not available for this date" return {'msg': message} @app.get("/desk-exercise") def get_desk_exercise_message(exercise: str = ''): "Returns daily-desk exercise message" lines = desk_exercises.messages message_index_dict = {} if exercise: exercise_index_dict = get_desk_exercise_index() message_index = exercise_index_dict.get(exercise, 0) message = lines[message_index%len(lines)] exercise_index_dict[exercise] = message_index + 1 set_desk_exercise_index(exercise_index_dict) else: message = random.choice(lines) return {'msg':message} @app.get("/desk-exercise/all") def get_all_desk_exercise_message(): "Returns all desk-exercise messages" lines = desk_exercises.messages return {'msg':lines} @app.get("/icebreaker") def get_icebreaker_message(ice: str = ''): "Returns daily-icebraker exercise message" lines = icebreaker.messages message_index_dict = {} if ice: icebraker_index_dict = get_icebraker_index() message_index = icebraker_index_dict.get(ice, 0) message = lines[message_index%len(lines)] icebraker_index_dict[ice] = message_index + 1 set_icebraker_index(icebraker_index_dict) else: message = random.choice(lines) return {'msg':message} @app.get("/icebreaker/all") def get_all_icebreaker_message(): "Returns all icebraker messages" lines = icebreaker.messages return {'msg':lines}
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/messages/comments_reviewer.py
first_reviewers = ["Drishya","Mohan","Akkul","Raghava","Ajitava"] second_reviewers = ["Shiva","Rohan","Raji","Sravanti","Preedhi"]
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/messages/senior_qa_training.py
messages = [ "<b>Welcome to the training program by Qxf2!</b> I am Qxf2Bot. I post messages every day to help you in this journey. Please think about the content posted and feel free to ask your trainers questions about them.", "<b>Learning to learn</b> Learning how to learn is the main skill that you should expect to pick up from this course. Technology and work will continue to evolve. There is no way for you to know every single technology that your potential employers will need. But you can become good at learning quickly. As you proceed through this training course, keep asking yourself if you are learning to learn.", "<b>The very first recorded bug</b> Fun fact. The first computer bug was an actual insect! https://thenextweb.com/shareables/2013/09/18/the-very-first-computer-bug/#.tnw_RmimDMmX", "<b>30 years as a tester</b>: This is one of the best testing related talk Team Qxf2 has heard. It made us think about the factors influencing our career, common distractions and the advice towards to the end was immediately applicable to our careers. I hope you find time to watch this talk! https://www.youtube.com/watch?v=mi5R3mOILrw", "<b>Zero days</b> A zero-day is a day where you are applying nothing new. During this training program, please try your best to put in at least a little time every day. Try your best to avoid too many zero days. Ideally, you would put in one hour on weekdays and around eight hours in total over the weekend.", "<b>Learning new things can be stressful</b> Often times, we are extremely harsh on ourselves when we are new to something. So, while you are in this program, I want to remind you to be nice to yourself. Stop comparing yourself to some ideal in your head. Instead, look at the amount of progress you have made since you started in terms of thinking, technology and troubleshooting.", "<b>Learning and discomfort</b> Great job fighting through all the discomfort! Remember that it is important to spend 13 hours a week. Just complete what you can in those 13 hours. The remaining tickets can spill over to the next week.", "<b>Helsinki bus theory</b> Do you feel like you are doing tutorial after tutorial and never getting anywhere? Team Qxf2 enjoyed this article and the specific advice on staying on the bus! https://petapixel.com/2013/03/13/the-helsinki-bus-station-theory-finding-your-own-vision-in-photography/", "<b>Reach out to ex-colleagues</b> Finding colleagues you like working with is difficult as you get more experienced. So try keeping in touch with ex-colleagues you liked working with. Share some of the articles you are reading that you find interesting. Or just pick up a phone and start a conversation.", "<b>Reminder!</b> This is your reminder to be nice to yourself. You are learning new skills, new technology, new approaches and new thinking everyday. We understand that is a lot of stress. So our advice to you today is simply this - give yourself the permission to try things and fail.", "<b>The Bored QA</b> When you have 5-10 days between tasks, please visit The Bored QA and try out one of our exercises. You can also use it as a fun way to start conversations with your team. https://the-bored-qa.qxf2.com/", "<b>Short-term stress</b>This course was designed to place a lot of short term stress upon you. But if you put in the time, I promise you that you will look back at this period fondly. You will find it worth it. I say this from experience. Some of the hardest projects I have worked on were not fun in the moment. But they are the ones that shaped my career and I look back at them with pride.", "<b>Star repositories you use</b> Make sure to star repositories that you use often. Over time, your own GitHub profile will look more real and natural to recruiters scanning your GitHub!", "<b>Bad output is better than no output</b> Good on you for choosing to change! I know that there are days trainees persist and struggle and there are days you might have given up. You know what? That is a totally human reaction to change. Improvement is not linear. Change is often two steps forward and one step back. So if the going seemed too tough for a few days, remind yourself that every learner goes through such phases and just start off from where you left off.", "<b>Selenium's first announcement</b> Selenium has helped thousands of testers start on a more technical path. This non-descript looking post announced Selenium to the world showing that many important things are rarely flashy or met with hysteria! https://web.archive.org/web/20041029143250/http://www.io.com/~wazmo/blog/archives/2004_10.html", "<b>Information overload</b> Great job struggling through this course! It is common for our trainees to feel overwhelmed with new information. It is also natural for them to think `There is so much to learn! Am I going to be spending my nights and weekends just learning?`. Well, the good news is NO! Initially, you don't have much to relate your learning to. So everything we show you looks like a separate piece of data. But over time, you will begin to see patterns and notice connections that will make picking up new things extremely fast! I liken this experience to learning to drive a car. Initially, you are uncomfortable and need to focus on the road ahead of you and cannot drink in the sights. But over time, driving becomes subconscious and you are able to enjoy the scenery.", "<b>Hitting the high notes</b> Team Qxf2 likes the thoughts in this article about hiring in software engineering. If you are ever in a position to hire folks the ideas in this article are interesting. This is one of those old articles that most software engineers should read. https://www.joelonsoftware.com/2005/07/25/hitting-the-high-notes/", "<b>Putting in the time</b> There is only one way to get better at troubleshooting - by putting in the time. Everyone comfortable with tech got good at troubleshooting problems one problem at a time. The next time you meet someone who is really good at tech, ask them how they got good at troubleshooting. I bet they will respond by shrugging their shoulders and saying something along the lines of 'Well, I put in the time' or 'I just kept doing things.' So don't despair if you are stuck solving problem after problem during this training program. You are getting better at troubleshooting and problem solving.", "<b>Grumpledump song</b> This is a funny poem about people that complain a lot. But as a tester, we think the bugs raised here are valid ;) https://www.poets.org/poetsorg/poem/mr-grumpledumps-song", "<b>It's not ONLY you</b> Learning with this training program gets lonely and demotivating. It is natural for you to think that it is your fault that you have a backlog. Well, if you are feeling upset at yourself for not finishing sprints like clockwork, I have a simple reminder - it's not ONLY you! It's every single trainee that feels that way. Every. Single. Trainee. This course was designed to be hard. We want trainees to feel uncomfortable and desperate. And then when you are near your breaking point, we want to help. So chin up, forget about 'finishing tickets' and enjoy the journey.", "<b>Bike shedding</b> Bike shedding is the phenomenon of people spending time on things that are easy and avoiding things that need preparation and thinking. We share this article with employees and trainees to help them recognize this habit. http://bikeshed.com/", "<b>A crappy first version is NOT the same as sloppy work!</b> There is a difference between sloppy work and producing poor first versions. Sloppy work is when you can do better but produce poor quality work. A poor first version is often the result of you trying something new and hard. You should not be producing sloppy work. But you should be trying to produce poor first versions of work often.", "<b>T-shaped people</b> As the field of software testing keeps expanding, this article about T-shaped people will help you keep one foot in your expertise while landing your other foot in newer topics. https://www.facebook.com/notes/kent-beck/paint-drip-people/1226700000696195/", "<b>Look back at how far you have come</b> Today is a good time for you to look back and reflect on how far you have come in such a short period of time! Week in and week out you worry about how much more there remains to complete. And while that is a useful worry, don't forget that you have made some massive progress too. Allow yourself some time to look back and feel proud.", "<b>Career advice from Dilbert</b> Testers are not the best developers. We are not the best at DevOps. But when we combine our software testing skills with a touch of development and a dash of DevOps, we really stand out! https://dilbertblog.typepad.com/the_dilbert_blog/2007/07/career-advice.html", "<b>Thank you tweets</b> A lot of quiet, introverted people do not develop social profiles. But social accounts are a nice way to establish your credentials and will help you land your next opportunity easier! If you are quiet and have nothing to say, just try sending out thank you tweets to people whose work (articles, presentations, talks, etc) that you use as part of work.", "<b>Situations we simulate</b> Following are some of the common work situations that our training program mimics: \n1. Reading other people's code \n2. Reusing existing code and making it work. You inherit automation code that you then need to clean up \n3. Many times at work, the setup instructions have become obsolete. Newer versions of the software tools you are using have been released making life easier \n4. Getting blocked and waiting to be unblocked. This happens at work. You need to know how to adapt \n5. Presenting your work \n6. Multi-tasking \n7. Not getting immediate access to systems \n8. Troubleshooting", "<b>Adaptive vs Technical challenges</b> Technical challenges are solved by knowledge and training. But there are some challenges that evolve as you solve them. These are adaptive challenges. Parenting is probably is the most relatable example of an adaptive challenge. Adaptive challenges not only need technical skills but they also need constant engagement, fresh mindsets and ever-improving mental models. As you continue your journey through Qxf2, remember this critical distinction. It is not enough that you just execute the tasks given to you. You need to periodically introspect and evaluate if the work is changing your habits, mindset and perspective.", "<b>Parkinson's law</b> Time-boxing is an essential part of the <i>doing and then learning</i> strategy that is emphasized in this training program. If you feel like you need large amounts of time, think about Parkinson's Law: https://en.wikipedia.org/wiki/Parkinson%27s_law", "<b>A tip for the next 12-months</b> I have a simple tip to make your learning so much easier. Stop asking what-is-the-use-of-doing-X? and just do X. Its ok if nobody else you know is doing X. Over time, you will notice that doing X had multiple benefits that neither you nor me could have predicted (called emergent-behavior in a complex system) and you will be better off for having tried.", "<b>Career calculus</b> Read this article and then think about how it applies to your career! https://ericsink.com/Career_Calculus.html", "<b>Bad beginnings</b> Our schooling did a great job of instilling values of hard work, discipline, logical thinking and holding ourselves to high standards. I wish they had taken the time to explain that those characteristics are good in most contexts but not all! A specific context where most of those supposed strengths fail is when you attempt to do something new. You can get over this bias though. The next time you start something new, remind yourself that it is natural to struggle and be clueless when doing new things.", "<b>What can you teach us?</b> As you go through this training course, please keep a lookout for ways you can help us. While we are conducting the training program, Qxf2 knows we are not good enough. We would love to pick up stuff from all our trainees too!", "<b>Update your LinkedIn profile</b> This is a reminder to make sure you are updating your LinkedIn profile periodically.", "<b>There is no happily every after</b> As you progress through this training, hopefully, you are adding new techniques and capabilities to your testing toolbelt. You might even start wondering what the happily-ever-after scenario will look like. While this may seem like a good question, make peace with leaving it unanswered. I feel like the question comes from societal conditioning. We have always been told that if we work hard during insert-critical-life-phase-here, things will become easy after that. Instead of adopting this (imo) poor mental model, just view learning as a side-effect of solving problems and do not really worry about where all this is going to culminate.", "<b>Mixed bag is not the same as mediocre</b> A mixed bag has high-highs and low-lows. Mediocre performance is when you are average all through - you neither impress nor annoy. When I say it is ok to fail at clients, I am implicitly assuming there are already some things you do well. If you fail at a specific task because you chose something new, it will be ok because nobody is expected to be good at everything. A mixed bag of performance has a tremendous upside for your own career.", "<b>Your technical powers and test ideas are supposed co-evolve</b> Your QA output should not be your previous output plus one or two new tools you picked up in this training program. We are not trying to do your old job in an automated way. Instead, technical skills should expand the scope of what a QA engineer can do. All the technical skill and tooling you pick up is supposed to help you probe the software being tested in a more effective way. As you become more technical, you should be able to conduct tests that you previously could not even imagine. You should be able to understand the nuances of implementations and vary your tests accordingly.", "<b>Generalize your learning</b> A great way to keep up with ever-changing technologies is to generalize your learning. Generalizing lets you abstract many things into one concept. It helps you associate new tools with existing ones and brings down your cognitive load. For example, if I learnt to configure a Jenkins job, I would generalize my learning as follows. Jenkins solves the problem of a gigantic code merge by letting people continually integrate their code to the codebase in small increments. It does this by removing the need of having a human do a build-test-merge. Instead, it provided a web interface to write and execute shell commands before and after a build. If you can get to that level of abstraction, any new CI tool can be tackled easily. You simply have to figure out what interface the new tool provides and how to describe your build-test-merge steps in that tool.", "<b>Technical QA != Automation</b> Please do not equate writing automation to being technical. Technical QA involves being able to understand systems and design tradeoffs, adhere to good engineering principles, perform complex setup operations, create tools to enable other QA and much more. I want us to be technical QA. That is very different from wanting folks who can write automated tests.", "<b>Companies do not go obsolete ... employees do.</b> ITeS companies in India have the reputation of doing outdated work. The media and our peers tend to talk of them as going obsolete. I have news for you. Every major Indian ITeS provider has been around for more than three decades. They evolved and remained relevant from the pre-Internet era to today. But most employees who did very well for these companies ended up becoming obsolete with every new wave of technology. This happened because they passively executed what their client or boss wanted. Do not make the same mistake. Make sure you are choosing tasks that simultaneously benefit your client, Qxf2 and <i>you</i>.", "<b>Getting off autopilot is exhausting but essential</b> If you are in the early days of this training program, please make an effort to get off autopilot. Try to think actively throughout the day. This tiring and requires a lot more energy on your part. It is especially hard because you are really good at your current job. So good that you are able to go on autopilot for the most part. One of the reasons the first several weeks at of training is challenging is that you are (hopefully!) not given a chance to be on autopilot. PS: This is not an original insight. I came across it when reading literature about learning.", "<b>Unconscious competence</b> I do not like the habit of keeping a long list of commands/instructions/procedures that you can then copy-paste or blindly follow. Keeping notes that you copy-paste from does not engage your brain sufficiently. This habit also prevents you from achieving a key stage in learning that people call <i>unconscious competence</i>. If you keep a file with a bunch of commands that have worked for you in the past and then copy-pasting commands/instructions/procedures, please try to limit this habit. Make an attempt to understand what is going on and that will help you commit the steps to memory.", "<b>Pro-tip: Setup a GitHub profile for yourself</b> You will be surprised at how the frontiers of technical recruiting have changed. There are sophisticated algorithms that trawl LinkedIn and GitHub and reach out to engineers with good profiles. So make an effort to have a nice GitHub profile. Here is an article showing you how: https://www.aboutmonica.com/blog/how-to-create-a-github-profile-readme", "<b>Share your learning</b> Get into the habit of sharing your learning. It is ok if what you are sharing has been done ad nauseam. Your perspective might help another beginner. And even your shared work does not help anyone, you get better just making it and taking the effort to share it. So do not wait until you become an expert. Share what you learn even when you are beginner.", "<b>Great resource for articles about testing</b> We found this link compiled by an Internet Famous tester to be excellent reading. When you are bored, try reading any one of the links and discuss with your colleagues. https://www.huibschoots.nl/wordpress/?page_id=441", "<b>A good talk about automation</b>As you become a more technical tester, you will need to engage in many conversations to influence your team and influence developers. Finding the right ideas and using the right words is going to matter more and more. We found this talk about automation a good resource for talking about what we intend to do as testers and how automation fits that picture: https://www.youtube.com/watch?v=uIDvGzQdoxc", "<b>Different architectures</b> Understanding the architectural patterns in applications will help you test applications better. We like this talk about this subject: https://www.youtube.com/watch?v=tpspO9K28PM .... <i>PS:</i> This is a fairly advanced and abstract talk. If you are not able to tie it to testing, that is ok!", "<b>How do other companies test?</b>When I was starting out in the QA space, I read a book called How Microsoft Tests Software. It introduced me to a lot of patterns and situations that I had previously not thought through. I still frequently Google for how other companies manage their testing. Recently, I stumbled upon this interesting talk by Netflix that packs so many good ideas and details about how microservices architectures can fail: https://www.youtube.com/watch?v=CZ3wIuvmHeM", "<b>Am I doing this right?</b> When you working on new things, it is normal to be able to do the task but feel inadequate and under-confident. Often times, you will ask yourself if you are on the right path. You will question if you have made the right choices. You will wonder if there is a better way to what you just did. I do not know of a single person who can avoid such self-doubt. In fact it healthy and lets us explore! The trick is in being to continually execute inspite of such self-doubt. The next time you find yourself avoiding a specific task, remind yourself that such self-doubt is normal and probably useful for your career!", "<b>A gentle introduction to testing microservices by Maxim Novak</b> If you are completely new to testing microservices, watch this talk. It starts from describing how you would test a monolith and proceeds to show some common patterns and beginner approaches to testing microservices: https://www.youtube.com/watch?v=BhjFUVuPa2U", "<b>Tangential skills</b>If you find the time today, try learning about one of these topics by watching a 10-minute YouTube video: typography, choosing colors, how to make good slides, using whitespace in design, producing sketch notes, advanced Google search hacks, how to type faster, how to draw good graphs. Pick a topic every other week and learn about it. Soon you will have a lot of exposure to different skills.", "<b>Easing into reading</b> For today, pick some book you always wanted to read and look up its summary on YouTube. Do not watch videos longer than 15-minutes. If you feel comfortable, share the video you watched on the etc, etc, etc channel.", "<b>Look for tech everywhere</b> An easy way to be creative is to combine ideas from different worlds. For today, YouTube search <i>tech used in ______</i> where _____ is anything you like in life. Do not watch videos longer than 15-minutes. If you feel comfortable, share the video you found on the etc, etc, etc channel.", "<b>End-to-End Automated Testing in a Microservices Architecture by Emily Bache</b> We really like this talk about end to end testing in a microservices architecture based application. The speaker takes you through the evolution of testing strategies and the kind of adjustments she (and her team) made along the way. Watch it an takes notes of the language, the concepts and the diagrams! https://www.youtube.com/watch?v=vq8o_AFfHhE", "<b>Increase your technical exposure</b> You do not have to discontinue your learning after this training finishes. We devised many small exercisrs to help you micro-learn on a daily basis. You can check out some of the ideas here: https://trainingseniorqa.com/how-increase-technical-exposure", "<b>Getting better without increasing knowledge</b> Most people think the only way to become better at their jobs is by learning some new tools or techniques that they can add to their resume. This approach is valid as long as you have a lot of time on your hands. After that, working on your thinking is going to have a far larger impact on getting better. Your ability to generalize, abstract, relate, chunk, synthesize and combine are going to help you stay relevant and competitive. So do yourself a favour and start thinking about how you think. Observe how other think in similar situations. If you need to Google for this stuff, try searching for <i>meta-cognition</i> or <i>conceptual understanding</i>.", "<b>You are responsible for your career</b> The person most responsible for your career is you. You manager is <i>also</i> responsible for your career. Your employer is <i>also</i> responsible for your career. But at the end of the day, they do not suffer if your career goes south. So when you pick tasks, try to get better. If you are handed tasks, modify your approach just enough to learn new things. If you are repeatedly working on the same thing, try it with a different toolbelt or a different process or a different mindset.", "<b>Occasional failure is better than perfectionism</b> The one common aspect among our trainees is that they seem to impose unreasonably high standards on themselves. On a daily basis, they have been choosing really safe options at work just to avoid failing. They have repeatedly shied away from expanding their horizons if it meant leaving their comfort zones. Over time, this has gotten them to lose touch with the current state of technology. My advice would be to adopt a mental model where it is ok for you to fail occasionally. Continue to succeed a majority of the time. But now and then, pick one or two tasks where you will look foolish and fail. It is ideal if you can pick some lower risk tasks to fail. Do this a few times and you will notice that the failing is not as bad as you imagined. And what is more, your ability to learn and grow will improve!", "<b>Learn, execute ... share and choose!</b> When you come out of this training program, we hope you have picked up more habits than just learning and executing. A big part of our attempt in this training program is to make you get used to sharing your work and also choosing your next step. Folks that do these two habits well will see a huge rise in their market value. It is not just companies, but co-workers too, who will appreciate your ability to choose interesting next steps and your willingness to share what you learn. So for today, think about how you have exercised your sharing and choosing muscles during this training.", "<b>Incomplete side-projects</b> Once you become more technical, you are bound to start multiple projects. This message is a reminder that if you reach that stage, you are in no obligation to finish them! Just do what seems fun and interesting. Keep your perfectionist tendencies at bay for a while. I say this from my own experience as well as the experience of several of my friends. Folks that have sustained a steady interest in technical work are always tinkering around with mutliple ideas.", "<b>Steady small steps</b> I hope you have noticed breaking tasks down into smaller parts has been an underlying idea of this training program. This habit is very useful in accelerating your learning and increasing your productivity. This talk is a good explanation of the benefits of breaking tasks into smaller steps: https://www.youtube.com/watch?v=FKTxC9pl-WM", "<b>Exposure is a measure of experience</b> The idea of experience being measured in years is somewhat strange. Some people have 1-year of experience ten times over. I prefer treating technical exposure as a better (yet imperfect) measure of experience. The more ideas you are exposed to, the richer and more relevant your testing is going to be. This exposure does not have to be passive or driven by your employer. You can try to increase your technical exposure actively - sign up for newsletter, read about a variety of topics, try new tasks, watch talks, etc. Do this sort of micro-learning daily and you will soon find yourself confident about the value you bring to the table.", "<b>Listen to extend, not understand</b> Many of our trainees are low on confidence about their technical skills. This low confidence leads to a strange negative feedback loop. They enter technical conversations with the goal of understanding what is being said. Invariably, there are going to be words or concepts they do not understand. This leads them to go silent and think they will go back home and study that new concept. Over time, people start noticing that the tester is not participating in technical conversations and they tag them as non-technical. How do you break this loop? Enter conversations with the mindset of trying to extend ideas rather than just understanding conversations. When you do this, you will invariably give the testability point of view to the conversation. This will help your team see the value you bring and they will be more likely to help you fill in the technical gaps because you are helping them fill in testability gaps.", "<b>Be curious about how things work</b> Knowing how things work will help you test better. This habit will expand your testing (not replace your current tests!) and make you much more creative in terms of what and how you test software. A nice test for knowing how things work is if you can draw a block diagram outlining the components and the functioning of the system. Try sketching out the product you are currently testing at work. Figure out what parts you know well (detailed block diagram) and which ones are fuzzy. Now start looking to learn more about the parts that are fuzzy. This is a good starting point to get more technical about your own product.", "<b>Emergence</b> This training program recommends purposeless micro-learning on a daily basis. What you learn is immaterial. What matters is the habit. Why does the habit matter more than what is being learnt? Because a collection of ideas form patterns that no single idea on its own can. This concept called is Emergence. You can read more about it here: https://necsi.edu/emergence", "<b>Talking about testing</b> Every QA professional that has a few years of experience testing ends up having a much broader view of what comprises testing. But communicating this knowledge to non-testers is tricky. Watch this talk as a refresher that will help you talk better about such topics: https://www.youtube.com/watch?v=jwKaiYLMHss", "<b>The hook pattern</b> You are most probably going to run into the hook pattern if you are writing code. You you can think of them certain methods that are called when the program starts/finish a stage. For example, a test runner (like pytest) will have defined 'stages' like initialization, collection, execution, reporting, etc. A hook simply lets you write code that you want executed when a stage either starts or finishes. Here is a practical example in Python: https://refactoring.guru/design-patterns/template-method/python/example", "<b>The actor model</b> Functional and Object Oriented Programming are not the only models of software. There are plenty of other ways to design software. A nice model (expecially for concurrency) is called the Actor model. You can read this piece to get an introduction https://www.brianstorti.com/the-actor-model/", "<b>Sign up for newsletters</b> A good way to increase your exposure is to sign up for newsletters. Sign up for a few newsletters based on your interests. As a start, we encourage you sign up for at StackOverflow newsletter - https://stackoverflow.blog/tag/newsletter/", "<b>Follow famous software people on Twitter</b> Twitter is useful as a source of new technical information. You do not have to be actively tweeting to get the benefit. In fact, you can just be a lurker and get whole lot of value. Google around for some famous software people and follow them on Twitter.", "<b>Which are the top software testing conferences?</b> A fun way to increase your technical exposure is to find talks at good conferences. For today, try to Google for the best software testing conferences and then go to YouTube and watch some videos from them.", "<b>Tranferring testing skills to the whole team</b>We really like this talk on how to transfer your testing to the entire team: https://www.youtube.com/watch?v=O1v8jgyj3AM", "<b>What, when, how, where</b> As you get more technical, you should start describing tests in terms of what is being tested, when the tests will run, how the testing will be performed and where the tests will run. A test strategy that just outlines what to test or test cases is incomplete. A couple of decades ago, in the land of monolith web (or desktop) applications, the answers looked something like this: What - feature. When - a build was ready, nightly. How - exploratory tests. Where - on a test environment. With modern applications the answers are much more complex. Your answers today could look like this: what - tiny isolated change, when - before a commit, after a push, in CI, after a build is ready, nightly. How - exploratory tests, unit tests, API checks, GUI checks, contract tests, integration tests, etc. Where - on a developer machine, in the CI infrastructure, on a test environment, on staging, etc.", "<b>Testing is a team problem</b> If you are in an under-staffed testing team, the ideas on this talk are very useful: https://www.youtube.com/watch?v=LNEdzIZe33I", "<b>Curiousity is more than asking questions</b> Some folks mistake curiousity to be the same as asking a lot of questions. Well, curious people do not just stop there. They actively try to find answers by exploring topics on their own. When you are curious about something, do not just stop at asking the question. Make up your own theories. Construct your own mental models. Come up with hypotheses. And then experiement and validate (or invalidate) what you thought. These sort of exercises are extremely useful in improving your thinking and give you the confidence to approach new tasks.", "<b>Modeling testing</b> As you get better at testing,you need to be able to explain testing to your colleagues. We find this article to be a good starting point to think about modeling testing and the complexities in explaining what we do. https://www.linkedin.com/pulse/new-model-test-strategies-update-heuristic-dan-ashby/ ... as all models go, this too is a simplification. But we like that it has enough content for us to start conversations.", "<b>Improving your first drafts</b> As you improve your skills in an area, the rough drafts you produce in that area should increase in quality. For example, as a Python beginner, it might have been ok to produce linear scripts as a first draft. But as you get more experienced, even the first draft of your scripts should start showing more polish. Imbibe new learnings so well that they are automatically applied to your future work. ", "<b>Ideas in paired programming</b> This is one of the better articles on paired programming that exist on the Internet: https://martinfowler.com/articles/on-pair-programming.html . We recommend you read it even if you never plan on using the pair programming. BTW, if you have a lot of credibility with your development team and are looking to pick up better programming skills, ask them if they would help you develop something useful for QA using this driver-navigator approach. We have found just 3-5 hours over a month with one developer helps us so much!", "<b>After you solve something ... </b> I hope you have experienced the joy being stuck on a technical problem and then solving it. As this experience becomes more common, make it a habit to do three things. One, summarize your thinking. Two, verbalize the technical approach - it should be beyond 'I Googled for solutions' and instead be more technical like 'I started to implement a pytest hook, but that got too complicated. I decided to look for a plugin that solved my problem instead'. Three, go looking for alternative ways in which you could have solved the same problem. This is a fairly simple practice to apply to your daily life.", "<b>Becoming better at talking about testing</b> Many testers (especially me!) use English rather haphazardly. Sure, we probably know the concepts but we communicate them poorly. I found this discussion a good starting point to think about how I talk about testing to non-testers: https://www.ministryoftesting.com/dojo/lessons/the-rapid-software-testing-guide-to-what-you-meant-to-say-michael-bolton", "<b>Read and execute, but ...</b> When you look through tutorials or are listening to someone explain something, definitely look to absorb the ideas. But do not stop there. Look to contribute. This attitude will help you engage with new ideas better. Sure, for a while, you might not be able to contribute much. But keeping the intent alive will help you over the longer run. You will become comfortable with the new and unknown. You will absorb material at multiple levels of abstraction. And you will make connections naturally!", "<b>Pair testing</b> Like pair programming, the concept of paired testing is powerful. Espcially if you can get a developer to pair with you on testing! We recommend this article as an introduction to paired testing: http://katrinatester.blogspot.com/2015/05/pair-testing.html", "<b>The other benefit of breaking tasks down</b> We stress breaking tasks down into smaller steps to all our trainees. Do this for even tasks you are sure that you can do in your sleep. While this habit definitely helps you move forward with more certainty, there is an unintentional benefit that habit that many people do not consider. When you are stuck with a technical problem, the habit of breaking tasks in to smaller will <i>help you move back in smaller steps</i>. People that cannot break down tasks into small steps, back out in larger steps. Consider a newbie contributing something small to a framework. When they fail to implement something small, they backout and try to 'learn the framework' or 'improve Python skills'. While experienced folks, stay with the error and backout in the same small incremental steps that lead them to the error.", "<b>The testing story</b> One of my weaknesses is that I do not like talking that much. Story telling does not suit my personality. I suck at giving the testing story to stakeholders. If you also have a hard time presenting the testing story, this article is a good starting point to crafting a story: https://www.pixelgrill.com/testers-tell-a-compelling-story/ ... branch out from this article and then watch stuff on YouTube."]
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/messages/reminders.py
""" Reminders depending on the day of the week """ monday_msg = ["I hope you planned this week on Friday evening itself. If not, please do it now. Send out all the calendar events that you need to for this week. Accept (or reject) the calendar invites you received. Know at least two of your top priorities.", "Did you plan your week out in Friday? If not, now is the time. Planning your week in advance will help you say NO and help you from having to constantly firefight.", "How does your work week look? If you have not, list your action items and approximately when you think they will be tackled. Just doing this regularly will help you manage your time better.", "Please make an effort to manage your time well. Plan your week, be punctual, finish meetings on time and use the calendar well. These are important habits to cultivate a respectful environment.", "Make it a goal to avoid scheduling same-day-meetings. Those should be reserved for real emergencies. At the start of the week, make sure your have already scheduled all that you know is going to happen on your calendar.", "Did the previous week play out close to how you planned it? React with either a thumbs up or thumbs down.", "Your poor planning should not become someone elses emergency. Please take a few minutes to plan your week and schedule all the events that you might need!", "Please pay attention to mailers from 1to1help even if their material is of no use to you right now. Do not wait until you need the help. Gradually accumulating byte sized tips will most likely prove crucial in the future to you and people you care about.", "As you plan your week, please factor in time to remain minimally healthy. Schedule frequent breaks to stand up, stretch and walk multiple times during the day. Make an effort to apply the tips sent by 1to1help.net", "Avoiding burnout is important for an early employee. Make sure to pace yourself well. Finish your alloted vacation days every year. Take frequent breaks during the day to stand up, stretch and walk. Recognize when you are getting bored or overwhelmed and speak up. Accept the fact that it is OK to fail when you genuinely try. Ask your 1:1 manager for more tips."] tuesday_msg = ["Your Friday demos can be of work you did at a client in the past too! If you feel something you did in the past is interesting, please share!", "You can request your colleagues to demo something you know they have done? Just make sure to give them at least a week of prior notice.", "Think of what you want to demo on the sprint call. Work towards it in terms of visual milestones. That way, at all points you will have a working demo. Even if you don't complete your task, you can demo <i>something at least!</i>", "Friday demos are an inexpensive way for you to share your work with you colleagues while . Please make it a point to try and demo whatever you are working on.", "Your Friday demo need not be polished. You can demo work in progress too! In fact, you can demo some of the systems you are working with if you think that knowledge is not common place within Qxf2.", "You can preview the kind of socio-technical problems that we will face if we grow bigger at: https://growing-pains.qxf2.com", "Once in a while, when you are bored, please try out the-bored-qa.qxf2.com and give me some feedback.", "Qxf2 will gladly buy you tickets to one conference every year. The conference has to be related to software (or the business of software) in some way. A typical conference ticket costs INR 15k to USD 1k. We will also pay you for two days which spend attending the conference. All you need to do is to pay for your travel and stay.", "Qxf2 has partnered with 1to1help.net for mental wellbeing. Please make sure you are applying the useful tips and suggestions they offer in their weekly mailers.", "Qxf2 will gladly buy you technical books. In return, you need to read the book and create a good summary for us.", "Qxf2 will buy you online courses for upto INR 5k a year. The courses have to be related to something you hope to apply at Qxf2 some day.", "There should be absolutely no 1:1 technical communication! Technical questions should be asked on the common channel. https://qxf2.com/blog/banning-11-technical-communication/", "You should not discuss politics of religion on common channels. You are welcome to talk about them in 1:1 channels.", "For technical communication, please do not use any medium other than the ones listed here https://docs.google.com/presentation/d/1mQO7Hs45XMbmX6v5pP0V2027bqtpuN888sW8G2aEziM/edit#slide=id.g6f50f09311_0_63. No using SMS, Whatsapp, etc.", "Passwords should never be put in version control. Please remember to add the file to .gitignore and add a sentence or two in the readme of your repo on how to get setup.", "You can look at tickets of closed Trello board by searching for <b>board:number</b> in the ticket search field. For example, to see what ticket we tackled in our very first sprint, search for <i>board:0001</i>", "Keep your inbox as close to zero as possible. It will reduce the chances of missing important information. Tips available here: https://trello.com/c/eZHBXygi/23-tuesday-1400-good-gmail-habits", "You are expected to work 8 (or 9) hours a day. If you are frequently working more than that, please improve your planning and expectation setting. If you do not know how, please talk with your 1:1 manager.", "We do not use the phrase *manual testing*. Use the words <b>testing</b> or <b>exploratory testing</b> instead. Ask me or your 1:1 manager if you do not understand why.", "We do not sell *automated testing* as a service. Our goal is to test the product in front of us. Automation is a tool that helps us test better in some specific scenarios.", "Exploratory testing is not unstructured or haphazard or test-as-you-like. Good exploratory testing has structured and should be recorded/documented. Please look up the terms session-based-testing and testing-charters you do not know how to conduct your exploratory testing sessions."] wednesday_msg = ["As you go about this week, be on the lookout for how you can help a colleague get better. The help does not have to be substantial or life-changing or even correct! Just your attempt to help someone who is stuck will make Qxf2 suck a little less.", "You should pay attention to the work of your colleagues, at least at a high level. Read through Trello and Jira once or twice a week even if you are working on a client. Be curious about what your colleagues do at clients even if you are on R&D.", "1:1 sessions with your manager are supposed to be driven by the direct report. Your 1:1 manager should NOT be talking about technical work unless you bring it up. You should not be going to the meeting to report status. Instead, the sessions are to help you with your career. You can ask them for help on anything except technical problems. For technical problems, please post on the group channel.", "In a small company, enforcing culture is everyones responsibility. Please speak up if you notice someone doing something wrong.", "Do you know the number one reason early employees lose touch with the company they helped build? It is because they think correcting bad habits of later employees is the responsibility of management <i>only</i>. Well, it is the responsibility of the early employee <i>also</i>.", "I am open to trying out ideas that I completely disagree with. Suggest your idea. While I may turn it down in the moment, I will be trying incorporate it somehow, somewhere in a safe to fail way.", "The habits we stress at Qxf2 should continue at a client too. You should not suddenly go back to your old way of working when you are on a client!", "Early employees should get into the habit of asking for more responsibility! A growing bootstrapped company can afford to create all sorts of weird roles and one off opportunities.", "Please let work suffer if it is not being done in a fair way. Do NOT make it a habit to over-compensate for the weak links in your team. Instead, let the delivery fail and let the company fix the deeper issues (e.g.: poor hiring).", "As an early employee, when dealing with new hires, please attribute good intentions. New folks want to do well at their job but may not yet have enough context within Qxf2 to do well.", "We work on early stage products with small engineering teams. That means decisions around staffing, tooling, process, speed and stability are different from what you are used to. Please make an effort to think through the ramifications of what these mean. If you are not sure, please discuss with your 1:1 manager and/or your other colleagues.", "Are you multi-tasking better? We had a group discussion around multi-tasking a while ago. Today is a good time to check and see if you are adopting at least some new habits from that discussion: https://trello.com/c/hqe431zn/25-growing-pain-how-do-we-multi-task-better"] thursday_msg = ["Make an effort to share what you learn. Almost all the material on the Internet that you use to unblock yourself was created by busy professionals like you. So, once in a while, take a pause from consuming all that good stuff and try to share your own learnings", "You are expected to share what you know on our blog. If you feel unqualified, remember that technical expertise is a spectrum. There is always someone who will find your perspective useful.", "You can share personal stuff that you are excited about on the etc,etc,etc channel. You are not disturbing anyone or being noisy or anything like that. The channel exists so you can share such stuff.", "We strongly recommend regular 1:1 communication for non-technical stuff. Please make sure you are taking time to treat your colleagues like humans with lives.", "We have the habit of peer-checkins. If you havent done them in a while, please try one next week. https://sites.google.com/qxf2.com/wiki/home/r-d/newbie-orientation/peer-checkin", "Everyone starts out loving remote work. Then, it gets depressing. We expect everyone that joins us to face this challenge. If you are finding it hard to feel motivated, please reach out to the folks who have been here for a while. They can help. Helpful link: https://qxf2.com/blog/experience-working-remote/", "Remote work is a challenge, not a perk. It takes a lot of discipline to make remote work click. Please reach out when you find it hard and we will give you tips.", "Back, neck, eye and wrist problems are very common among remote workers. Please make sure you have an ergonomic work setup. Maintain good posture. Take a 2-minute break at least every hour to make sure you are walking, standing, stretching, exercising your wrists, etc.", "If you have been at Qxf2 for a while and find your work monotonous, talk to your 1:1 manager. It is OK to have such conversations within Qxf2. As an experienced engineer, I know finding work boring or stifling or monotonous is normal for anyone in any field.", "It is completely natural to have non-productive days as you transition into a completely remote environment. The best tip I have is to not hide it. Just admit the failure openly. We will work with you and try to help you make adjustments.", "Your QElo score depends on what you fill out in the help survey and the R&D task completion dashboard. If you forget to self-report, your score suffers. So please make it a habit to fill out the survey and task completion dashboard. http://34.205.45.167/survey https://docs.google.com/spreadsheets/d/1YtdX75BoCwnzkGbR6G4hHvPS_m2HfWffYTI_WCH-IlU", "Keep daily notes of what went good/bad, the folks that you gave or recieved help from and the new tech you (learnt + applied). It will help on Friday when you fill out your retrospective and help survey. The accurate information, in turn, will help you get a better QElo score", "QElo is a <i>rating</i> system. Not a ranking system. In a ranking system, the top ranks get rewarded disproportionately. E.g: The Olympics. In a rating system, people are rewarded proportionately. E.g.: Star rating of restaurants on Zomato", "The best way to get a high QElo rating is to perform four actions with four attributes. Four actions: Execute, Learn, Share, Choose. Four attributes: Consistency, Adaptability, Curiousity driven, Generalized.", "Tasks you choose to work on should benefit your client, Qxf2 and you! Choosing such tasks is a skill to be developed just like anything else.", "QElo is designed to use lifetime scores. I did this so people can make longer term plays and do not have to worry about what they did only in the last quarter.", "QElo is a group measure. You can improve and still have your score go down and vice versa!", "Your QElo score is does not depend on manager input or how well you talk/present or the visibility of your projects. Instead, it measures how much your work contributes to our goals.", "QElo is designed to keep freedom and responsibility proportional. If you have made genuine contributions, you can afford to take breaks, explore newer things, etc.", "Your QElo score will be visible to all your colleagues. You can see the discussion around this here: https://sites.google.com/qxf2.com/wiki/home/hr/pros-and-cons-of-an-open-qelo-rating", "One of the aims of QElo is to help engineers discover their own point of view.Once you have a unique way of looking at things, scoring well on QElo becomes natural.", "Qxf2 will change. As early employees, you might not like that but you have to accept it. It is not that different from how you, the individual, has changed as you grow up and deal with changes in your life."] friday_msg = ["Please fill out the help survey and retrospective card! Both habits are defenses to preserve the habit of remote work. http://34.205.45.167/survey", "Have you filled out the retrospective card? Have you filled out the survey? http://34.205.45.167/survey", "TGIF! Please remember to fill out the retrospective card and the survey! http://34.205.45.167/survey", "Survey reminder: https://docs.google.com/spreadsheets/d/1YtdX75BoCwnzkGbR6G4hHvPS_m2HfWffYTI_WCH-IlU"] messages = { 0: monday_msg, 1: tuesday_msg, 2: wednesday_msg, 3: thursday_msg, 4: friday_msg}
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/messages/sep20_interns.txt
<b>It is perfectly ok to be stuck</b> At this stage, it is perfectly normal to be stuck at supposedly simple steps! Different people get stuck at different places. Maybe you are stuck at an install when the other interns are not. All this is expected. When you do get stuck, just ask on the common channel and one of us will try to help you. <b>The first month will be slow</b> Your first month with Qxf2 will simultaneously seem hard and unproductive. This is primarily happening because you are doing two things at once - picking up a lot of new vocabulary/concepts while also shaking off rust from your break. That is a killer combo but something you should accept and live with. <b>Do not bother about where the internship is headed</b> For the duration of this internship, do not worry about where things are headed. Just see it as short-term investment of four months of your time and leave it at that. The way we teach things will seem highly inefficient and unconventional. It will also seem like it prevents you from truly mastering any single topic. We do this intentionally to help you discover your problem solving style. The payoff for this approach takes several weeks. So make sure you stick to the program. <b>Focus on the trend also</b> A natural way to measure progress is against an end goal. During this internship, please remember to also adopt a view of measuring your progress against your starting point. This helps you combat any unrealistic expectations you might have for yourself based on hearsay or looking at others. <b>Show up to work every day</b> Our biggest fear for this batch of interns is that you might quit. People with options tend to do that especially when the payoff for a hard task is not apparent. Do not do that. Instead, show up every single day. That includes the days you have not completed your work or the n-th day in a row that you are stuck on the same problem and have no solution. In return, all your Qxf2 colleagues will be as non-judemental as possible. <b>The learning pattern</b> We switch the order of doing and gaining knowledge. In schools, you are first taught a base of knowledge and then asked to apply it. At Qxf2, we switch the order. We try to make you do stuff first and then have you learn it. This is highly uncomfortable for adults but bear with us. We know that the drawback of this method is that you end up being usure if you learnt anything at all! On the positive side, this is the right way of learning on the job. No matter what your next job is, the habit of trying something out and then learning about it will benefit you. <b>Make friends with loose ends</b> If you spend a few weeks with us and do what we ask, you will have sense of incompleteness. A sense that there are a overwhelming number of loose ends for you to follow upon and learn thoroughly. Do not worry. In this internship, we will revisit the same topic multiple times. You do not need to master any topic on your first interaction. Think of the process as creating an intricate painting. At the initial stage, we are just getting you to pencil the outline lightly. Then, gradually over time, you will get several chances to fill in the details. <b>Asking questions is hard</b> Asking technical questions over chat is hard but it is an essential skill you should try to get better at. I don't have tips for this (Im a bot :P), but I wanted to let you know that we get your pain. Maybe the next time you meet with a Qxf2 colleague, ask them for tips on how to get better at this skill. <b>Pace is a tricky thing</b> At this stage of your learning, decouple pace and output. Going slow is not a sign you are doing poorly. Finishing early is not a sign you are doing good. Sometimes we get stuck on the most basic things while more complex stuff just clicks into place ¯\_(ツ)_/¯ <b>Your progress will not be linear</b> Please expect your progress to be non-linear. You might struggle for weeks to understand how to write a simple script. And then, in one week, suddenly belt out several useful scripts. There seems to be a certain threshold of trying, doing and struggling that is needed before things click into place. We do not know why this happens but we have seen this with trainee after trainee. So keep at it and hopefully things will suddenly improve. <b>Procrastinating and progress</b>When I am really close to making progress at something new, I experience something strange that maybe some of you do too. I back out. I tend to procrastinate even when I know what exactly I need to do. An example from recent memory - the first few times I sent out cold emails, I would compose the email just fine and then I simply could not hit the send button. I remember literally walking away from my desk. Over time, I have come to see this as a good indicator that I am close to getting over some learning hump. I just accept that I will end up taking longer to complete because I procrastinate. If you have experienced something similar and have a better solution, please share!
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/messages/culture.txt
<b>Rough starts are normal at Qxf2</b> If you are feeling not-good-enough, remind yourself that most employees have rough starts at Qxf2. After all, you are transitioning into a very different way of working that requires you to change, learn and unlearn many things. You should also know that it gets better over time and sometimes even fun(!) when you get used to our system of working. <b>How to succeed in your first few weeks with Qxf2</b> The traits that will let you successfully navigate the initial phase with Qxf2 do not require talent. Key traits among the successful Qxf2 employees were: >a) showing up daily (well, virtually)>b) being open about their difficulties at work >c) being willing to change their habits. So, keep trying every day, be open about your difficulties and be willing to change. <b>How are you judging me?</b> We will not judge you based on your knowledge or achievements at this stage of your relationship with Qxf2. Why? Because you are transitioning from one system of work into another. That means you need to unlearn, learn and piece together multiple habits before you are productive. Instead, we are judging you based on your effort, the openness that you show in asking for help and your ability to adapt. Do that and you will find things will work out over well the coming months. <b>Its not only you</b> New hires think they are the only ones struggling to get a handle on their work while everyone else has figured it out. Not really. The rest of us look comfortable only because we have made peace with high levels of ambiguity and complexity. At some point, you are going to realize that each of us are on our own journey of learning, unlearning, doing and failing. <b>Failure despite effort</b> Qxf2 is a stressful environment until you learn multiple new habits and the compounding effect of those habits kick in. Until then, you are going to repeatedly fail despite trying hard. We know failing repeatedly over a long enough period of time is highly stressful for professionals. We have taken several steps to make failure-despite-effort less stressful. For example, we have tried to make failing-despite-effort as non-punitive as possible. We are also very receptive to hearing about your failures. So feel safe to try your best and come up short. <b>Adaptive vs Technical challenges</b> Technical challenges are solved by knowledge and training. But there are some challenges that evolve as you solve them. These are adaptive challenges. Parenting is probably is the most relatable example of an adaptive challenge. Adaptive challenges not only need technical skills but they also need constant engagement, fresh mindsets and ever-improving mental models. As you continue your journey through Qxf2, remember this critical distinction. It is not enough that you just execute the tasks given to you. You need to periodically introspect and evaluate if the work is changing your habits, mindset and perspective. <b>A tip for your first year</b> I have a simple tip to make your first year at Qxf2 so much easier. Stop asking what-is-the-use-of-doing-X? and just do X. Its ok if nobody else you know outside of Qxf2 is doing X. Over time, you will notice that doing X had multiple benefits that neither you nor me could have predicted (called emergent-behavior in a complex system) and you will be better off for having tried. <b>We shape our buildings, thereafter they shape us. - Winston Churchill</b> Early employees are expected to actively contribute to company design. I usually describe this task as help-me-build-the-company during interviews. Understandably, for most people, this is a little too vague. But as early employees, hopefully, you are starting to realize a company and its culture gets built over time - either consciously or by default. I find this topic fascinating and I suspect if you spent some time Googling about it, you would too! <b>Bad beginnings</b> Our schooling did a great job of instilling values of hard work, discipline, logical thinking and holding ourselves to high standards. I wish they had taken the time to explain that those characteristics are good in most contexts but not all! A specific context where most of those supposed strengths fail is when you attempt to do something new. You can get over this bias though. The next time you start something new, remind yourself that it is natural to struggle and be clueless when doing new things. <b>There is no happily every after</b> As you progress within Qxf2, hopefully, you are adding new techniques and capabilities to your testing toolbelt. If you have worked elsewhere before, you might even start wondering what the happily-ever-after scenario will look like. While this may seem like a good question, make peace with leaving it unanswered. I feel like the question comes from societal conditioning. We have always been told that if we work hard during insert-critical-life-phase-here, things will become easy after that. Instead of adopting this (imo) poor mental model, just view learning as a side-effect of solving problems and do not really worry about where all this is going to culminate. <b>What is a good failure?</b> As of Jun 2020, I think a good failure has four components. One, the person/people working made a sincere effort to do what they can and then looked foolish or incompetent. Two, the failure leads to situational insights, mindset improvements and technical improvements. Three, the failure exposes more than one problem within Qxf2 ... not just improvements of the individual(s) involved. Four, there is an appetite to right the failure. <b>Mixed bag is not the same as mediocre</b> A mixed bag has high-highs and low-lows. Mediocre performance is when you are average all through - you neither impress nor annoy. When I say it is ok to fail at clients, I am implicitly assuming there are already some things you do well. If you fail at a specific task because you chose something new, it will be ok because nobody is expected to be good at everything. A mixed bag of performance has a tremendous upside for Qxf2 and your own career. <b>One of the great challenges of the game is how to make progress when there are no obvious moves, when action is required not reaction. - Gary Kasparov</b> This is true not only in chess but in our careers as well. When things are going smooth, we seem to want to coast. Its ok to coast for a while, especially after a hectic release. But over the long term, make sure your are exploring new problems regularly. <b>Your technical powers and test ideas are supposed co-evolve</b> Your QA output should not be your previous job output plus one or two new tools. We are not trying to do your old job in an automated way. Instead, technical skills should expand the scope of what a QA engineer can do. All the technical skill and tooling you pick up is supposed to help you probe the software being tested in a more effective way. As you become more technical, you should be able to conduct tests that you previously could not even imagine. You should be able to understand the nuances of implementations and vary your tests accordingly. If you have been here for a couple of years and your testing outlook has not evolved beyond <i>manual + automation</i>, please talk to you 1:1 manager and/or experienced colleagues. <b>We test early-stage products</b> This is different from testing mature products with an established user base. A big difference happens to be that speed is critical to an early-stage product. Early-stage products are still discovering their user base and the kind of solution that scales. They need to run several experiments and iterate many times before they land upon a solution that will work. The quicker they can run these experiments, the better their odds of survival are. So when you test early-stage products, think of how you can improve their speed to market. <b>Be resourceful at a client</b> We work with early-stage products and small engineering teams. More warm bodies and process heavy methodologies and more meetings are very rarely the answer. You cannot expect thorough documentation or access to a business analyst or product manager who has loads of time to spend with you. Everyone is busy and tasked with more work than they can handle. Instead of retreating into a shell and waiting for your client to unblock you, you need to be observant and resourceful. Think on your own and try things out. If needed, ask on the Qxf2 channel for help. <b>When you do not understand something in a conversation ...</b> ... do NOT get into the habit of thinking that you will learn about the topic when you have time and then speak up in the coming days. Instead, first try to pay attention even if you seem lost. Second, in most cases, clarify or admit you do not understand on the call. Especially if the task is going to fall to you. Third, make it a daily habit to expose yourself to new things. <b>How to start at a brand new client</b> You are expected to follow this approach https://qxf2.com/where-start-testing if you are new to Qxf2. The outline in that document will help you understand the product you are testing better while also letting you make decisions on how to proceed with testing. The document there is not some checkbox that you do as an exercise once within Qxf2 and then forget when you land at a client. If you are new to Qxf2, please make sure you are following that methodology. If you have worked at Qxf2 for a while, please ensure new people follow the approach at clients. <b>Generalize your learning</b> A great way to keep up with ever-changing technologies is to generalize your learning. Generalizing lets you abstract many things into one concept. It helps you associate new tools with existing ones and brings down your cognitive load. For example, if I learnt to configure a Jenkins job, I would generalize my learning as follows. Jenkins solves the problem of a gigantic code merge by letting people continually integrate their code to the codebase in small increments. It does this by removing the need of having a human do a build-test-merge. Instead, it provided a web interface to write and execute shell commands before and after a build. If you can get to that level of abstraction, any new CI tool can be tackled easily. You simply have to figure out what interface the new tool provides and how to describe your build-test-merge steps in that tool. <b>Please work on communicating your testing better</b> Start with the summary. Then explain <i>what</i> you tested but also <i>how</i> you tested. If needed, use screenshots and tables and bulleted lists. And finally, focus on your English too! Language matters. I see (me especially!) us use English poorly. We often use pronouns (this, that, it, etc.) when we should be using better words to describe what we want to express. Please make an attempt to improve. When you catch yourself using words like this/that/it/those, etc., substitute such determiners/pronouns with whatever actual thing you want. Example: <i>I clicked that button and it did not work</i> vs <i>I clicked the compose button but the email composer window did not show up</i> <b>Technical QA != Automation</b> Please do not equate writing automation to being technical. Technical QA involves being able to understand systems and design tradeoffs, adhere to good engineering principles, perform complex setup operations, create tools to enable other QA and much more. I want us to be technical QA. That is very different from wanting folks who can write automated tests. <b>Too much of a good thing ...</b> Please do not overdo good things like working extra hours or working weekends to help us succeed or skipping your allotted PTO. The reason I do not want too much of such behavior is because it tends to mask deeper organizational problems like poor planning, understaffing, exploitative bosses, etc. You might occasionally need to do stuff like stretching your work hours, replying to messages in your off-hours or working on weekends. That is ok. But when you do, please call it out explicitly on a public channel. <b>Companies do not go obsolete ... employees do.</b> ITeS companies in India have the reputation of doing outdated work. The media and our peers tend to talk of them as going obsolete. I have news for you. Every major Indian ITeS provider has been around for more than three decades. They evolved and remained relevant from the pre-Internet era to today. But most employees who did very well for these companies ended up becoming obsolete with every new wave of technology. This happened because they passively executed what their client or boss wanted. Do not make the same mistake. Make sure you are choosing tasks that simultaneously benefit your client, Qxf2 and <i>you</i>. <b>Process should not precede understanding</b> We should not be putting processes before most of the company understands the nuances and complexities of a problem. Process preceding understanding is one of the major reasons that people at large companies struggle to fit into smaller companies like ours. For too long, they could blindly follow the process without having to understand the intricacies of the problem that the process was solving. That, in turn, meant that they never got a realistic picture of how software is made and instead developed a distorted concept that there was a <i>correct way</i> of working. Let us delay becoming like that for as long as we can. BTW, it is ok to propose a process to a problem that we have a high degree of common understanding within Qxf2. <b>The difficulty in teaching people how to test</b> I have been grappling with one problem for many years now - <i>are there better ways to teach people how to test</i>? Every time I tackle this problem, I run into the brick wall of testing involving a lot of tacit knowledge. Tacit knowledge is intuitive, experience-based knowledge. Skills that involve a lot of tacit knowledge are difficult to describe in words but easy to show. Dancing is a good example. A beginner can learn much more about dancing by seeing someone else dance rather than writing books about dancing. Testing has a similar problem. It is incredibly hard to communicate what we do to the uninitiated. Can you think of interesting ways we can show new testers what we do? <b>Getting off autopilot is exhausting but essential</b> If you are new at Qxf2, please make an effort to get off autopilot. Try to think actively throughout the day. This tiring and requires a lot more energy on your part. It is especially hard because you were really good at your previous job. So good that you were able to go on autopilot for the most part. One of the reasons the first several weeks at Qxf2 is challenging is that you are (hopefully!) not given a chance to be on autopilot. For folks who have been here a while, please sure any onboarding/training material you design forces the new person to get off autopilot. Do not give new hires a chance to fall back to their old ways. Design material that looks very different from every other tutorial on the web.\nPS: This is not an original insight. I came across it when reading literature about learning. <b>Unconscious competence</b> I do not like the habit of keeping a long list of commands/instructions/procedures that you can then copy-paste or blindly follow. Keeping notes that you copy-paste from does not engage your brain sufficiently. This habit also prevents you from achieving a key stage in learning that people call <i>unconscious competence</i>. If you keep a file with a bunch of commands that have worked for you in the past and then copy-pasting commands/instructions/procedures, please try to limit this habit. Make an attempt to understand what is going on and that will help you commit the steps to memory. <b>What have you unlearnt?</b> Please think about the work habits you have unlearnt after joining Qxf2. It is not sufficient to simply learn the material presented or do the tasks allotted. A key component to succeeding as a Qxf2 employee is unlearning. There are long-standing habits that you need to actively unlearn. For example, asking technical questions in writing on a common channel requires you to unlearn your old habit of calling a colleague and saying <i>This is not working. Help me.</i> This exercise of consciously evaluating what to unlearn is especially important to new hires. Please do not skip this exercise. <b>Low drama environment</b> Hopefully, Qxf2 comes across as a place with very little drama. We do not celebrate wildly when things go our way. We do not become depressed when things do not go our way. You will rarely see us heroically pulling all-nighters and racing towards a deadline. You will rarely see us sitting idly when the workload wanes. I would like to keep Qxf2 this way. This is because I value being steady, consistent and even. I know this sort of environment is not for everyone. If you are from a different environment, try and give this approach a shot for at least 6 months. If you still end up missing periodic adrenaline rushes at work, may be we are not the right environment for you. <b>Symmetric behavior</b> Symmetry in behavior can, to an extent, help us build a fair environment. For example, I am ok if someone openly yells at a colleague for a mistake. But I expect symmetry in behavior. The yeller should have been equally loud/emphatic when their colleagues do good work. I also expect the yeller to be equally emotional/vocal about their own mistakes. In general, this sort of symmetry is hard for aggressive people to practice. An easier path to achieve symmetric behavior is to be kind/measured with your colleagues. \nBTW, did you know we can (to some extent) probe for symmetry during interviews? Ask a question in Round 1. Then, in round 2, ask the reverse question. For example, if in Round 1, the candidate tells you that their pet peeve is poor communication. In Round 2, ask them to give you an example where they communicated poorly and see what they say. <b>Heroism masks problems</b> Please let projects fail for the right reasons. The very first time you notice something wrong, it might be ok to be a hero as long as you bring it my attention. But after that, do not be a hero too often. Do not pull all-nighters often. Do not take on more than your fair share of responsibility over long periods of time (>6 months). Yeah, occasionally you will have to stretch but if you are stretching more than say twice a quarter, you are masking problems within Qxf2. The most common reasons for needing heroic behavior at work are poor hiring decisions, poor management, poor team dynamics, poor tooling, poor processes and understaffing. If something at Qxf2 is crap, it should be exposed. If not, we might scale thinking all is good. And when we scale crap, we end up with a ton of crap. <b>It is normal to hate your job once in a while</b> It is ok to hate your job sometimes. In fact, if you hate your job once in a while, it means you are probably growing. I have hated my job at Qxf2 a few times in the past. I even hated playing chess on some days when I was still competing. This is normal. You do not have to feel guilty about it. If you are disliking your job for several weeks together, please talk to your 1:1 manager. They will try to help you decide on what to change. Almost always, changing the nature of work will not be the answer. Instead, it will probably be changing mindset and/or your outlook that helps. <b>Find your baseline</b> Many professionals have made no attempt at figuring out how different setups, work sequences, constraints, and distractions influence their work output. Treat this as a testing problem. Experiment. Vary different portions of your work and see what suits you. The productivity gains will be good but that is a secondary concern. The primary benefit I got by doing this exercise was to recognize the many, many invisible factors that influence work. <b>Honest retrospectives</b> Please make an effort to fill out your retrospective well. Good, honest, open and thoughtful retrospectives serve as a culture reinforcement tool. Good retrospectives help normalize the fact that all of us are struggling and doing good at the same time. This will help the new hire identify with us quicker. Open retrospectives remove the stigma around failure. The more honestly we share our experience, the more likely that the new folks will trust us. The more thoughtful our retrospectives, the more likely that our new hires will be more introspective. <b>Everyone has the authority to give feedback</b> Please be observant for bad (or inefficient) habits in your colleagues. When you notice something wrong or sub-optimal with the behaviour of a colleague - speak up! You <i>do not</i> have to be their boss to speak up. As an early employee, it is in your interest to get into the habit of giving feedback. Some simple guidelines around giving feedback - give feedback to your colleagues as early as possible instead of waiting for an ideal moment. Try your best not to be too accusatory during the feedback. Asking a thought-provoking question or pointing a missing piece are also valid forms of feedback. If your feedback is received (or given) poorly, rest assured that there are several other actors in the system that will try to correct the situation. Related internal discussion: https://trello.com/c/frjiaRtk/42-group-discussion-how-to-get-better-at-giving-feedback <b>Micro-learning</b> I am a big fan of micro-learning or the learning that happens in really small chunks but in a regular manner. Shiva-s approach to <b>Python Question of the Day</b> is a good example of micro-learning. But you do not need anyone bright to guide your micro-learning. You can do that daily by simply asking yourself better questions as you go about your day. Just being curious about how something works or following up on a new word or an attempt to avoid a usual step or re-ordering your routine can keep your work fresh and while helping you learn something new. <b>Consuming and producing</b> Please make sure you are producing work that helps other and not just consuming stuff all the time. That is the responsible way. Every smart colleague I have ever had has been a producer, a giver, a sharer. If you are using StackOverflow every day to make you look good at your job, please make time to answer a few questions there too. If you are reading blog posts to help you at your job, it is your responsibility to write what you know too. It is extremely easy for you to just take, take and take - and then give the excuse that you are too busy to share. But remember that the people that you took from also have lives and busy professional lives. <b>A different starting point to testing</b> A lot of what we talk about within Qxf2 might seem very different to what you were used to in your previous job. But over time, you will come to appreciate how much of what we do overlaps with what you already did. The reason you might feel a little dis-oriented at the start is because we tend to use different starting points to solve problems. For example, you might be used to testing applications only using the UI and by only having one testing environment. Over here, we have developed techniques and learnt tools that lets us start testing at different places. The principles of testing remain similar - all that differs is the starting point. <b>Autonomy and responsibility</b> For a complex system to work in a fair way, freedom and responsibility need to remain proportional. Apathy produces a concentration of power. Low engagement leads to forced tasks. Frequent unforced errors leads to stifling structures. Early employees should really, really think about this. Many of you have spent a significant time (years!) helping me build Qxf2. If you do not want that effort to go waste, please make sure that you are holding the new folks accountable to high standards of responsibility. <b>Getting better without increasing knowledge</b> Most people think the only way to become better at their jobs is by learning some new tools or techniques that they can add to their resume. This approach is valid as long as you have a lot of time on your hands. After that, working on your thinking is going to have a far larger impact on getting better. Your ability to generalize, abstract, relate, chunk, synthesize and combine are going to help you stay relevant and competitive. So do yourself a favour and start thinking about how you think. Observe how other think in similar situations. If you need to Google for this stuff, try searching for <i>meta-cognition</i> or <i>conceptual understanding</i>. <b>You are responsible for your career</b> The person most responsible for your career is you. You manager is <i>also</i> responsible for your career. Your employer is <i>also</i> responsible for your career. But at the end of the day, they do not suffer if your career goes south. So when you pick tasks, try to get better. If you are handed tasks, modify your approach just enough to learn new things. If you are repeatedly working on the same thing, try it with a different toolbelt or a different process or a different mindset. If you are having trouble shaking yourself out of a rut, speak to your 1:1 manager. <b>Varying your work habits</b> If you feel your current work has little scope for learning, think again. Learning is not just about increasing your knowledge base. There are many other ways to vary your work and improve without actually changing your tasking. For example, you could try to increase the intensity or pace at which you do the same work. You could try to add something extra to what you already deliver. Or you could try removing a sub-task and see if your work still gets done. Perhaps you can try communicating the work you do in a different manner? Maybe reorder the sub-tasks to be a bit more creative. Alternatively, you might want to increase the quality with which you previously did something. Try some of the suggestions here and see which ones help you improve. <b>Increase your exposure</b> I have noticed that our group discussions are producing one point repeatedly. We would all benefit if we knew more :). You are going to be extremely slow if you rely on experience or classes to learn new things. You need some other way to get more exposure. My method is to read what others have to say. But reading is not for everyone. So find your own method. Maybe it is podcasts. Or videos. Perhaps it is open source contributions. Or gabbing with your ex-colleagues. Whatever it is, make sure you are exposing yourself to what is happening in other small companies and what is happening in the testing world. <b>The Normalization of Deviance</b>Sociology describes 'normalization of deviance' as the phenomenon of slow cultural drift. What used to be not-okay slowly gets classified as okay. I find this interesting because I think it accurately describes what early employees go through. Early employees usually fail to speak up when they notice deviations from newer folk just to be nice. Over time, these small omissions end up moving the culture of the company pretty drastically. If you see such deviations, please speak up. Every single one of you has the right and the responsibility to point out such deviations. Maintaining the parts of our culture that you like is going to take effort! <b>Tangential skills</b>If you find the time today, try learning about one of these topics by watching a 10-minute YouTube video: typography, choosing colors, how to make good slides, using whitespace in design, producing sketch notes, advanced Google search hacks, GMail tips, how to type faster, how to draw good graphs. If you feel like learning about more than one, resist the urge. This message will show up again pretty soon. <b>Easing into reading</b> For today, pick some book you always wanted to read and look up its summary on YouTube. Do not watch videos longer than 15-minutes. If you feel comfortable, share the video you watched on the etc, etc, etc channel. <b>Look for tech everywhere</b> An easy way to be creative is to combine ideas from different worlds. For today, YouTube search <i>tech used in ______</i> where _____ is anything you like in life. Do not watch videos longer than 15-minutes. If you feel comfortable, share the video you found on the etc, etc, etc channel. <b>Try, then fail</b> <i>Trying and then failing</i> is very different from simply failing. For example, if you had to write a blog post, simply failing would be to not write a blog post. <i>Trying and then failing</i> would be producing a horrible draft riddled with errors that people can look and laugh at. For example, you need to write an automated test. Simply failing is to say I do not understand the framework, can someone help me? <i>Trying and then failing</i> involves getting setup, producing horrible code and then posting the error you hit. <i>Trying and then failing</i> produces concrete errors that expose your thinking. It will make it easy for people to give you specific help. It will make it much easier for you to work on your thinking rather than just on your knowledge. The biggest advantage of <i>trying and then failing</i> is that you will always be tackling molehills to get better. On the other hand, if you choose to continually simply fail, you will always end up having to conquer mountains to improve. <b>Intensity of work</b> Your brain should be engaged through the eight (or nine) hours you spend at work everyday. The simplest way to do that is to deliberately increase your intensity - shorten the time you allocate for a task or produce much higher quality work in the same time. Treat every day like you are preparing for an eventual crisis that requires you to do things quicker and better. By introducing higher levels of intensity, you are reinforcing your fundamentals to become automatic. When your fundamentals are automatic, your brain is free to handle the harder and novel parts of work. And thats when the fun part of work starts. <b>Go a level deeper</b> Qxf2 to tries to provide soft introductions to new technologies. We demo our work during sprints, open source our code, democratize code reviews, publish blog posts, share articles and so much more. All these are opportunities for folks to get familiar with new things in a gradual manner. But our April 2021 quarterly revealed many of us have been actively ignoring all these learning opportunities. Instead, about half the company has been thinking they will learn these new things in one shot ... after they need them. I want this habit to stop immediately. For folks who were making this mistake, here is one thing you should do right from today - go a level deeper. If you are used to ignoring stuff wholesale, at least Google for the terms you do not know. If you are used to simply skimming an article, read it in detail. If you are used to looking at a visual demo, dive into the technical details. If you are used to using others work, try and think of how you can extend their work. Whatever you are doing right now, go one level deeper. <b>Speed matters</b> Please work on your speed when working - especially when there is no pressure on you. The rate of work is a key ingredient in determining how much you learn. The faster you are able to work, the more the compounding effect of learning happens. This practice ends up being extremely useful in high stress situations. You are able to think clearer and work more naturally under pressure if you have practiced doing regular tasks at high speed. So for today, try doing the normal stuff you do at work at a faster pace.
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/messages/desk_exercises.py
messages = ["<b>Shoulder-arm stretch</b>Time to do Shoulder arm stretch, keep one arm horizontally stretched in front of your chest. Push this arm with your other arm towards you until you feel a mild tension in your shoulder. Hold this position briefly, and repeat the exercise for your other arm. Don't do this more than 40 seconds.", "<b>Finger stretch</b> Time to do finger stretch, Separate and stretch your fingers until a mild tension is felt, and hold this for 10 seconds. Relax, then bend your fingers at the knuckles, and hold again for 10 seconds. Repeat this exercise once more. Time duration is 40 seconds.", "<b>Neck tilt stretch</b> Time to do neck tilt streatch, Start with your head in a comfortable straight position. Then, slowly tilt your head to your right shoulder to gently stretch the muscles on the left side of your neck. Hold this position for 5 seconds. Then, tilt your head to the left side to stretch your other side. Do this twice for each side. Time duration is 30 seconds.", "<b>Backward shoulder stretch</b> Time to do backward shoulder stretch, Interlace your fingers behind your back. Then turn your elbows gently inward, while straightening your arms. Hold this position for 5 to 15 seconds, and repeat this exercise twice. Time duration is 30 seconds.", "<b>Move the eyes</b> Look at the upper left corner of the outside border of your monitor. Follow the border slowly to the upper right corner. Continue to the next corner, until you got around it two times. Then, reverse the exercise. Total time duration is 32 seconds.", "<b>Train focusing the eyes</b> Look for the furthest point you can see behind your monitor. Focus your eyes on the remote point. Then focus on your monitor border. Repeat it. If you cannot look very far from your monitor, face another direction with a longer view. Then switch your focus between a distant object and a pen held at the same distance from your eyes as your monitor.", "<b>Look into the darkness</b> Cover your eyes with your palms in such way that you can still open your eyelids. Now open your eyes and look into the darkness of your palms. This exercise gives better relief to your eyes compared to simply closing them. You can do this for 20 seconds", "<b>Move the shoulders</b> Spin your right arm slowly round like a plane propeller beside your body. Do this 4 times forwards, 4 times backwards and relax for a few seconds. Repeat with the left arm. You can do this for 30 seconds.", "<b>Move the shoulders up and down</b> Put your hands on the armrests of your chair when you are sitting down and press your body up until your arms are straight. Try to move your head even further by lowering your shoulders. Slowly move back into your chair.Please do this 30 seconds only.", "<b>Turn your head</b> Turn your head left and keep it there for 2 seconds. Then turn your head right and keep it there for 2 seconds. You can do this for 2 seconds." "<b>Relax the eyes</b> Close your eyes and breathe out as long as you can and try to relax. When breathing in, again do it as slowly as possible. Try to count slowly to 8 for each time you breathe in and out. To extra relax your eyes, try closing them in micro pauses too. You can do this for 12 seconds."]
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/messages/icebreaker.py
messages = ["<b>Icebreaker from Qxf2Bot</b> What is the most unique thing you have within reach of your desk? ", "<b>Icebreaker from Qxf2Bot</b> Who is the last person you talked to in Qxf2 this week?", "<b>Icebreaker from Qxf2Bot</b> Do you have a dedicated office space at home?", "<b>Icebreaker from Qxf2Bot</b> Where do you work most frequently from at home? Your office? Your kitchen table? The backyard? Your bed?", "<b>Icebreaker from Qxf2Bot</b> What’s something on your desk, a nearby wall, or out the window that cheers you up during the day?", "<b>Icebreaker from Qxf2Bot</b> What does your typical work from home uniform look like?", "<b>Icebreaker from Qxf2Bot</b> What’s your favorite sports team", "<b>Icebreaker from Qxf2Bot</b> How long have you worked from home?", "<b>Icebreaker from Qxf2Bot</b> Have you ever traveled alone?", "<b>Icebreaker from Qxf2Bot</b> Have you ever quit doing something that you used to be really passionate about? Do you regret it? Or are you happy you quit? Either way: Do you think you’ll ever take it up again?", "<b>Icebreaker from Qxf2Bot</b> What’s your favorite thing about working from home?", "<b>Icebreaker from Qxf2Bot</b> Do you work better at home with background noise? Is the TV on? Radio?", "<b>Icebreaker from Qxf2Bot</b> What is your favorite “work from home” exercise?", "<b>Icebreaker from Qxf2Bot</b> What’s your number one tip for combating distractions when working from home?", "<b>Icebreaker from Qxf2Bot</b> Messy desk or clean desk?", "<b>Icebreaker from Qxf2Bot</b> Which is your favourite car?", "<b>Icebreaker from Qxf2Bot</b> What does your work-from-home space look like? Give the team a snap or tour!", "<b>Icebreaker from Qxf2Bot</b> Do you prefer to work in an office or from home?", "<b>Icebreaker from Qxf2Bot</b> What is your least favorite part of working from home?", "<b>Icebreaker from Qxf2Bot</b> Have you ever won a trophy? what for?", "<b>Icebreaker from Qxf2Bot</b> Hero or antihero?", "<b>Icebreaker from Qxf2Bot</b> What is the most challenging part of working from home?", "<b>Icebreaker from Qxf2Bot</b> What part of working from home makes you most grateful?", "<b>Icebreaker from Qxf2Bot</b> What helps you stay productive while working from home?", "<b>Icebreaker from Qxf2Bot</b> What's your favorite way to spend a rainy weekend at home by yourself?", "<b>Icebreaker from Qxf2Bot</b> What does your morning routine look like when working from home?", "<b>Icebreaker from Qxf2Bot</b> Are you more productive in a home office, at the kitchen table, from bed?", "<b>Icebreaker from Qxf2Bot</b> What work from home habit is most successful for you?", "<b>Icebreaker from Qxf2Bot</b> What is your favorite aspect of working from home?", "<b>Icebreaker from Qxf2Bot</b> What work from home habit is most successful for you?", "<b>Icebreaker from Qxf2Bot</b> What is your favorite aspect of working from home?", "<b>Icebreaker from Qxf2Bot</b> Book or movie?", "<b>Icebreaker from Qxf2Bot</b> Bot is tired today, can someone help by posting an Icebreaker for the day?"]
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/tests/test_desk_exercise_all.py
""" Code level tests for /desk-exercise/all endpoint """ from unittest.mock import patch import main from messages import desk_exercises @patch('messages.desk_exercises.messages', ['msg1', 'msg2']) def test_get_all_desk_exercise_message(): "Test that correct content is returned" expected_messages = ['msg1', 'msg2'] message = main.get_all_desk_exercise_message() assert message['msg'] == expected_messages def test_length_all_culture_messages(): "Verify that /desk-exercise/all returns same number of lines as desk_exercises.py file" lines = desk_exercises.messages expected_length = len(lines) message = main.get_all_desk_exercise_message() assert len(message.get('msg', [])) == expected_length
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/tests/test_sep20_interns.py
""" Tests for the Sep 20 interns messages endpoint """ import os from unittest.mock import patch import main @patch('main.get_messages_from_file') def test_message_selection(mock_obj): "Test that /message gets the right content" print("\n") test_msg_1 = "Hello! This is unit test message 1!" test_msg_2 = "Hello! This is unit test message 2!" expected_messages = [test_msg_1, test_msg_2] mock_obj.return_value = expected_messages message = main.get_sep20_message() assert message.get('msg', '') in expected_messages print("/message is selecting the right message") def test_message_file_exists(): "Test the message file exists" assert os.path.exists(main.SEP20_INTERNS_FILE) print("Culture file exists") def test_message_content_matches(): "Test that the selected message is in the culture file" with open(main.SEP20_INTERNS_FILE, 'r') as file_handler: lines = [line.strip() for line in file_handler] message = main.get_sep20_message() assert message['msg'] in lines print("Found message selected by /message in culture file")
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/tests/test_contract_daily_message.py
""" Contract test for daily messages """ import os import random import logging import atexit import unittest import requests from pact import Consumer, Provider, Format from messages import reminders import main # Declaring logger log = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) print(Format().__dict__) #Declaring PACT directory REPO_DIR = os.path.dirname(os.path.dirname(__file__)) PACT_DIR = os.path.join(REPO_DIR,'tests') pact = Consumer('Qxf2 employee messages lambda').\ has_pact_with(Provider('Qxf2 daily messages microservices'),pact_dir=PACT_DIR, log_dir=PACT_DIR) pact.start_service() atexit.register(pact.stop_service) class Getmessage(unittest.TestCase): """ Defining Test class contract test """ def test_get_index(self): """ Defining test for /index endpoint """ expected = { 'msg' : 'This is the endpoint for the home page. /message \ and /reminder are more useful starting points.' } (pact\ . given('Request to get home page') \ . upon_receiving('a request for home page')\ . with_request('GET', '/')\ . will_respond_with(200, body=expected))\ with pact:\ result = requests.get(pact.uri + '/')\ self.assertEqual(result.json(), expected) pact.verify() def test_get_message(self): """ Defining test for /message endpoint """ lines = [] with open(main.CULTURE_FILE, 'r') as fileprocess: lines = fileprocess.readlines() message = random.choice(lines) expected = { 'msg': message.strip()\ } (pact . given('Request to get message') \ . upon_receiving('a request for get message')\ . with_request('GET', '/message')\ . will_respond_with(200, body=expected))\ with pact:\ result = requests.get(pact.uri + '/message')\ self.assertEqual(result.json(), expected) pact.verify() def test_get_reminder(self): """ Defining test for /reminder endpoint """ weekday = main.get_weekday() lines = reminders.messages.get(weekday, ['']) message = "<b>Reminder:</b> " + random.choice(lines) expected = { 'msg': message.strip() } (pact . given('Request to get reminder') \ . upon_receiving('a request for reminder')\ . with_request('GET', '/reminder')\ . will_respond_with(200, body=expected))\ with pact:\ result = requests.get(pact.uri + '/reminder')\ self.assertEqual(result.json(), expected) pact.verify() def test_get_sep20_message(self): """ Defining test for /sep20-interns endpoint """ lines = [] with open(main.SEP20_INTERNS_FILE, 'r') as fileprocess: lines = fileprocess.readlines() expected = { 'msg': random.choice(lines).strip() } (pact . given('Request to sep20 interns') \ . upon_receiving('a request to sep20 interns')\ . with_request('GET', '/sep20-interns')\ . will_respond_with(200, body=expected))\ with pact:\ result = requests.get(pact.uri + '/sep20-interns')\ self.assertEqual(result.json(), expected) pact.verify()
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/tests/test_index.py
""" Test for the index page. """ import main def test_index_contents(): "Test the index page contents" expected_message = "This is the endpoint for the home page. /message \ and /reminder are more useful starting points." message = main.index() assert message.get('msg', '') == expected_message
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/tests/test_reminders.py
""" Code level tests for the reminders endpoint """ from datetime import datetime from unittest.mock import patch import main from messages import reminders @patch('main.get_weekday') def test_reminder_day(mock_obj): "Test that the right reminder is coming for the right day" print("\n") for i in range(0, 7): mock_obj.return_value = i message = main.get_reminder() message = message.get('msg', 'Incorrect value!!') message = message.split('Reminder:</b>')[-1].lstrip() assert message in reminders.messages.get(i, ['']) print(f'Got a valid reminder for day {i}') def test_weekday(): "Check if current weekday returned is right" #This is a super weird test just to get to 100% line coverage #Ideally, we will not need a test for a method that returns #only built in calls #I'm using an alternative way to get weekday and then checking today = int(datetime.today().strftime('%w')) assert (main.get_weekday() + 1)%7 == today
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/tests/test_all_culture.py
""" Code level tests for /culture/all endpoint """ from unittest.mock import patch import main @patch('main.get_messages_from_file') def test_get_all_culture_messages(mock_obj): "Test that /message gets the right content" print("\n") test_msg_1 = "Hello! This is unit test message 1!" test_msg_2 = "Hello! This is unit test message 2!" expected_messages = [test_msg_1, test_msg_2] mock_obj.return_value = expected_messages message = main.get_all_culture_messages() assert message.get('msg', '') == expected_messages, "Something fishy. /culture/all is NOT returning all messages from get_messages_from_file" def test_length_all_culture_messages(): "Verify that /culture/all returns same number of lines as CULTURE FILE" with open(main.CULTURE_FILE, 'r') as file_handler: lines = file_handler.readlines() expected_length = len(lines) message = main.get_all_culture_messages() assert len(message.get('msg', [])) == expected_length, "/culture/all is returning a different number of lines that in CULTURE FILE"
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/tests/test_main.py
""" Test for main page using fastapi test client. """ import datetime import os import sys from datetime import date import pytest from unittest.mock import patch from unittest.mock import Mock import mock from fastapi.testclient import TestClient from freezegun import freeze_time import main from main import app from messages import reminders from messages import senior_qa_training from messages import comments_reviewer from messages import desk_exercises from messages import icebreaker sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Declaring test client client = TestClient(app) # Test case for index page def test_index(): "asserting main endpoint" response = client.get("/") assert response.status_code == 200 assert response.json()["msg"] != '' assert response.json() == {"msg":"This is the endpoint for the home page. /message \ and /reminder are more useful starting points."} # Test for status code for get message def test_get_message(): "asserting status code" response = client.get("/message") assert response.status_code == 200 # Test for asserting random message is in the file def test_get_message_text(): "asserting random message is in the file" response = client.get("/message") message = response.json() assert response.json()["msg"] != '' with open(main.CULTURE_FILE, 'r') as file_handler: lines = [line.strip() for line in file_handler] assert message['msg'] in lines # Test for Reminders status code def test_get_reminder(): "asserting status code" response = client.get("/reminder") assert response.status_code == 200 # Test for asserting correct reminder sent def test_get_reminder_text_check(): "asserting message from the file" response = client.get("/reminder") message = response.json() assert response.json()["msg"] != '' weekday = main.get_weekday() lines = reminders.messages.get(weekday, ['']) message = message.get('msg', '') message = message.split('Reminder:</b>')[-1].lstrip() assert message in lines # Test for sep20_interns status code def test_get_sep20_message(): "asserting status code" response = client.get("/sep20-interns") assert response.status_code == 200 # Test for asserting correct message for sep20_interns def test_get_sep20_message_text_check(): "asserting message from the file" response = client.get("/sep20-interns") message = response.json() assert response.json()["msg"] != '' with open(main.SEP20_INTERNS_FILE, 'r') as file_handler: lines = [line.strip() for line in file_handler] assert message['msg'] in lines # Test for trainig status code def test_get_trainig(): "asserting status code" response = client.get("/training") assert response.status_code == 200 # Test for asserting message with senior_qa_training messages def test_get_senior_qa_training_message_text_check(): "asserting message text check" response = client.get("/training") message = response.json() assert response.json()["msg"] != '' lines = senior_qa_training.messages assert message['msg'] in lines # Test for checking first message shown after first cycle is completed. @patch('messages.senior_qa_training.messages', ['msg1', 'msg2']) @patch('main.get_senior_qa_training_user_index') def test_get_senior_training_unique_message(mock_get_index): "Test that the senior QA training messages cycle" mock_get_index.return_value = {'Qxf2':0} result = main.get_snior_qa_training_message('Qxf2') assert result['msg'] == 'msg1', f"{result['msg']}" result = main.get_snior_qa_training_message('Qxf2') assert result['msg'] == 'msg2', f"{result['msg']}" result = main.get_snior_qa_training_message('Qxf2') assert result['msg'] == 'msg1', f"{result['msg']}" # Test for checking first message shown after first cycle is completed for /desk-exercise endpoint @patch('messages.desk_exercises.messages', ['msg1', 'msg2']) @patch('main.get_desk_exercise_index') def test_get_desk_exercise_message(mock_get_index): "Test desk exercise messages cycle" mock_get_index.return_value = {'exercise':0} result = main.get_desk_exercise_message('exercise') assert result['msg'] == 'msg1', f"{result['msg']}" result = main.get_desk_exercise_message('exercise') assert result['msg'] == 'msg2', f"{result['msg']}" result = main.get_desk_exercise_message('exercise') assert result['msg'] == 'msg1', f"{result['msg']}" # Test for checking first message shown after first cycle is completed for /desk-exercise endpoint @patch('messages.desk_exercises.messages', ['msg1', 'msg2']) @patch('main.get_desk_exercise_index') def test_get_desk_exercise_message(mock_get_index): "Test desk exercise messages cycle" mock_get_index.return_value = {'exercise':0} result = main.get_desk_exercise_message('exercise') assert result['msg'] == 'msg1', f"{result['msg']}" result = main.get_desk_exercise_message('exercise') assert result['msg'] == 'msg2', f"{result['msg']}" result = main.get_desk_exercise_message('exercise') assert result['msg'] == 'msg1', f"{result['msg']}" # Test for comment-reviewers status code def test_get_comments(): "asserting status code" response = client.get("/comment-reviewers") assert response.status_code == 200 # Test for checking message def test_get_comment_reviewers(): "asserting message as per date" response = client.get("/comment-reviewers") if date.today().weekday() != 3: assert response.json()["msg"] == "Either today is not Thursday or data is not available for this date" else: assert response.json()["msg"] != '' #Test for distinct reviewers @patch('messages.comments_reviewer.first_reviewers', ['user1']) @patch('messages.comments_reviewer.first_reviewers', ['user2']) def test_get_distinct_reviewers_different(): "Test getting distinct reviewer" message = main.get_distinct_reviewers() assert message == "user1, user2 are comments reviewers" or "user2, user1 are comments reviewers" @patch('messages.comments_reviewer.first_reviewers', ['user1','user2','user3']) @mock.patch('main.get_first_comment_reviewer_cycle_index') @mock.patch('main.set_first_comment_reviewer_cycle_index') def test_get_first_reviewer(mock_get_index,mock_set_index): "Test for get_first_reviewer method" mock_get_index.return_value = {'Qxf2':0} mock_set_index.return_value = {'Qxf2':1} result = main.get_first_reviewer('Qxf2') assert result == 'user1' or 'user2' or 'user3' mock_set_index.return_value = {'Qxf2':2} result1 = main.get_first_reviewer('Qxf2') assert result1 != result mock_set_index.return_value = {'Qxf2':3} result2 = main.get_first_reviewer('Qxf2') assert result2 != result or result1 mock_set_index.return_value = {'Qxf2':4} result4 = main.get_first_reviewer('Qxf2') assert result4 == 'user1' or 'user2' or 'user3' @patch('messages.comments_reviewer.second_reviewers', ['user1','user2','user3']) @mock.patch('main.get_second_comment_reviewer_cycle_index') @mock.patch('main.set_second_comment_reviewer_cycle_index') def test_get_first_reviewer(mock_get_index,mock_set_index): "Test for get_second_reviewer method" mock_get_index.return_value = {'Qxf2':0} mock_set_index.return_value = {'Qxf2':1} result = main.get_second_reviewer('Qxf2') assert result == 'user1' or 'user2' or 'user3' mock_set_index.return_value = {'Qxf2':2} result1 = main.get_second_reviewer('Qxf2') assert result1 != result mock_set_index.return_value = {'Qxf2':3} result2 = main.get_second_reviewer('Qxf2') assert result2 != result or result1 mock_set_index.return_value = {'Qxf2':4} result4 = main.get_second_reviewer('Qxf2') assert result4 == 'user1' or 'user2' or 'user3' @patch('messages.comments_reviewer.first_reviewers', ['user1','user2','user3']) @mock.patch('main.get_first_comment_reviewer_cycle_index') def test_get_unique_first_reviewer(mock_get_index): "checking unique second reviewers" mock_get_index.return_value = {'Qxf2':0} result = main.get_first_reviewer('Qxf2') assert result == 'user1' result = main.get_first_reviewer('Qxf2') assert result == 'user2' result = main.get_first_reviewer('Qxf2') assert result == 'user3' result = main.get_first_reviewer('Qxf2') assert result == 'user1' @patch('messages.comments_reviewer.second_reviewers', ['user1','user2','user3']) @mock.patch('main.get_second_comment_reviewer_cycle_index') def test_get_unique_second_reviewer(mock_get_index): "checking unique second reviewers" mock_get_index.return_value = {'Qxf2':0} result = main.get_second_reviewer('Qxf2') assert result == 'user1' result = main.get_second_reviewer('Qxf2') assert result == 'user2' result = main.get_second_reviewer('Qxf2') assert result == 'user3' result = main.get_second_reviewer('Qxf2') assert result == 'user1' # Test for icebreaker status code def test_get_icebreaker(): "asserting status code" response = client.get("/icebreaker") assert response.status_code == 200 # Test for checking message genearted for icebreaker is always new @patch('messages.icebreaker.messages', ['msg1', 'msg2']) @patch('main.get_icebraker_index') def test_get_icebreaker_message(mock_get_index): "Test icebreaker messages cycle" mock_get_index.return_value = {'icebreaker':0} result = main.get_icebreaker_message('icebreaker') assert result['msg'] == 'msg1', f"{result['msg']}" result = main.get_icebreaker_message('icebreaker') assert result['msg'] == 'msg2', f"{result['msg']}" result = main.get_icebreaker_message('icebreaker') assert result['msg'] == 'msg1', f"{result['msg']}"
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/tests/test_all_icebreaker_messages.py
""" Code level tests for /icebreaker/all endpoint """ from unittest.mock import patch import main from messages import icebreaker @patch('messages.icebreaker.messages', ['msg1', 'msg2']) def test_get_all_icebreaker_message(): "Test that correct content is returned" expected_messages = ['msg1', 'msg2'] message = main.get_all_icebreaker_message() assert message['msg'] == expected_messages def test_length_all_icebreaker_messages(): "Verify that /icebreaker/all returns same number of lines as icebreaker.py file" lines = icebreaker.messages expected_length = len(lines) message = main.get_all_icebreaker_message() assert len(message.get('msg', [])) == expected_length
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/tests/test_messages.py
""" Code level tests for messages endpoint """ import os from unittest.mock import patch import main @patch('main.get_messages_from_file') def test_message_selection(mock_obj): "Test that /message gets the right content" print("\n") test_msg_1 = "Hello! This is unit test message 1!" test_msg_2 = "Hello! This is unit test message 2!" expected_messages = [test_msg_1, test_msg_2] mock_obj.return_value = expected_messages message = main.get_message() assert message.get('msg', '') in expected_messages print("/message is selecting the right message") def test_message_file_exists(): "Test the message file exists" assert os.path.exists(main.CULTURE_FILE) print("Culture file exists") def test_message_content_matches(): "Test that the selected message is in the culture file" with open(main.CULTURE_FILE, 'r') as file_handler: lines = [line.strip() for line in file_handler] message = main.get_message() assert message['msg'] in lines print("Found message selected by /message in culture file")
0
qxf2_public_repos/daily-messages
qxf2_public_repos/daily-messages/utils/delete_test_log_files.py
""" Method for deleting pickle file """ import os,sys sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) #Declaring directory REPO_DIR = os.path.dirname(os.path.dirname(__file__)) MESSAGES_DIR = os.path.join(REPO_DIR, 'messages') TESTS_DIR = os.path.join(REPO_DIR, 'tests') # Declaring files to delete PICKLE_FILE_DELETE = ['senior_qa_training.pickle','first_reviewer.pickle','second_reviewer.pickle','desk_exercises.pickle','icebreaker.pickle'] PACT_JSON = ['qxf2_employee_messages_lambda-qxf2_daily_messages_microservices.json'] # Delete file def delete_file(file_name): """ This method will delete a particular file """ if os.path.exists(file_name): os.remove(file_name) print(f'{file_name} deleted') # Delete files from particular directory def delete_files_in_dir(directory, files): "The method will delete files in a particular directory" for file_name in files: delete_file(os.path.join(directory, file_name)) # Delete pickle file def delete_pickle_file(): "The method will delete pickle file" delete_files_in_dir(MESSAGES_DIR, PICKLE_FILE_DELETE) # Delete json file def delete_pact_json_file(): "This method will delete pact json file" delete_files_in_dir(TESTS_DIR, PACT_JSON) # Delete desk exercise pickle file def delete_desk_exercise_pickle(): "This method will delete desk exercise file" delete_files_in_dir(MESSAGES_DIR, DESK_EXERCISES_PICKLE)
0