当前位置:网站首页>Project framework of robot framework

Project framework of robot framework

2022-04-23 16:36:00 Sink the wine cup and fleeting time

Project framework

Directory structure

 Insert picture description here

Project encapsulation

Python The configuration directory

pylib The folder is used to place Python The configuration file ,dirconfig.py The file is used to configure the path ,baseconfig.py File is used to configure the content of custom keywords

dirconfig.py

import os
#  File and folder management 

#  Project path 
base_dir = os.path.split(os.path.split(os.path.abspath(__file__))[0])[0]


#  Browser default download directory 
download_path = 'C:\\Users\Admin\Downloads'

#  Upload directory 
upload_path = os.path.join(base_dir,'filepath\\upload')
#  Upload files 
file1 = os.path.join(upload_path,'test.xlsx')

baseconfig.py

import os
import time
from robot.api import logger
from pylib import dirconfig
from openpyxl import load_workbook
from openpyxl.worksheet.worksheet import Worksheet

#  Remove commas from the amount and convert to numeric type 
def ReturnMoney(money):
    return int("".join(money.split(",")))

#  Return the path where the uploaded file is located 
def ReturnPath(userinput):
    if userinput == ' test ':
        return dirconfig.file1

#  Get all file names under the specified path 
def GetFileNames(filepath):
    for dirpath,dirnames,files in os.walk(filepath):
        return files    #  Back to the list , You can have multiple file names 

#  Empty the files in the specified folder 
def CleanFile(filepath=dirconfig.download_path):
    filenames1 = GetFileNames(filepath)
    if 'desktop.ini' in filenames1:
        filenames1.remove('desktop.ini')
    elif filenames1 == []:
        return " The file under the folder is empty "
    else:
        for file in GetFileNames(filepath):
            filename =os.path.join(filepath,file)
            os.remove(filename)
        filenames2 = GetFileNames(filepath)
        if filenames2 == []:
            return " The file under the folder is empty "

#  Returns the date of the day 
def ReturnTime():
    TimeToday = time.strftime("%Y-%m-%d", time.localtime())
    return TimeToday

#  Download file name 
def ReturnFilename(userinput):
    if userinput ==" test ":
        filename = ReturnTime()+" test .xlsx"
        return filename

#  Verify file name 
def CheckFileName(userinput,download_path=dirconfig.download_path):
    download_filename = GetFileNames(download_path)
    filename = ReturnFilename(userinput)
    if download_filename == []:
        return " There are no files in this folder "
    elif 'desktop.ini' in download_filename:
        download_filename.remove('desktop.ini')

    if filename == download_filename[0]:
        logger.info(" Download the {} The file name is called :{}".format(userinput, download_filename[0]))
        return "{} File name verification pass ".format(userinput)
    else:
        logger.info(" Download the {} The file name is called :{}".format(userinput, download_filename[0]))
        return "{} The document name cannot be verified ".format(userinput,download_filename[0],)


# Excel Document processing 
class ExcelHandler():
    '''  operation Excel, Read Excel The contents of the document  '''

    def __init__(self, file):
        ''' Initialization function '''
        self.file = file

    def open_sheet(self, sheet_name) -> Worksheet:
        ''' Open form '''
        wb = load_workbook(self.file)
        sheet = wb[sheet_name]
        return sheet

    def read_header1(self, sheet_name):
        ''' Get the header of the form ( first line )'''
        sheet = self.open_sheet(sheet_name)
        headers = []
        for i in sheet[1]:
            headers.append(i.value)
        return headers

#  Verify file content 
def CheckFile(userinput):
    filename = ReturnFilename(userinput)
    file = os.path.join(dirconfig.download_path,filename)

    if userinput == " test ":
        header = ExcelHandler(file).read_header1("Sheet1")
        logger.info(" Download the {} The header of the document is :{}".format(userinput,header))
        if header == [' Department number ', ' Department name ', ' Department level ', ' The remaining amount of the Department ']:
            return "{} The document header has passed the verification ".format(userinput)
        else:
            return "{} Document header verification failed ".format(userinput)

RF The configuration directory

For the data to be used 、 Element positioning, etc , You can put rflib Under the table of contents . Create a new one common.robot file , Used to place public variables

common.robot

*** Variables ***

#  Landing page element location 
@{
     Netease email address }     https://mail.126.com/		https://mail.163.com/
${
    iframe}      xpath=//iframe[contains(@id,'iframe')]
${
     User name input box }       xpath=//*[@name="email"]
${
     Password input box }      xpath=//*[@name="password"]
${
     The login button }      xpath=//*[@id="dologin"]

#  Account data 
${
     jurisdiction 1 account number }         user name 1
${
     jurisdiction 1 password }         password 1
${
     jurisdiction 2 account number }         user name 2
${
     jurisdiction 2 password }         password 2


#  Mailbox page element positioning 
${
     Home button }        xpath=//div[3]
${
     Write button }        xpath=//span[contains(.,' Write   Letter ')]
${
     Upload button }        xpath=//input[@type='file']
${
     File name - test }         test 
${
     Catalog - download }             download 

${
     Receiving button }          xpath=//span[contains(.,' closed   Letter ')]
${
     First email }        xpath=//div[4]/div[2]/div/div[2]/span
${
     View attachments button }        xpath=//a[contains(text(),' See attachment ')]
${
     Attachment documents }        xpath=//td/div/img
${
     Download button }        xpath=//a[contains(text(),' download ')]

expand : For element positioning , Using relative paths , In general , Do not use absolute paths . Specification for element location writing , Generally, in subsequent projects , Even if the page changes , There will also be less code changes

Here, for example. Download button Element orientation of , Generally not recommended Use contains, Suppose there's a button here , It's called Download the attachment , So this one xpath There will be two elements located . For text positioning , But be more accurate xpath=//a[text()=' download ']

Element localization , You don't have to find class、id These attributes .
For example, if it is based on class Attribute to locate , There will be more than one , According to the placeholder=' Start date ' To locate , It will be easier xpath=//input[@placeholder=' Start date '].

Of course , No problem at all , For example, positioning End date xpath=(//input[@class='el-range-input'])[2], Take the second , Namely End date , But after the page was changed , Such a position , You may not find End date 了 .
 Insert picture description here

Keyword encapsulation directory

WebKeyWord Directories are used to define user keywords , Implement business logic

Business keywords .robot

*** Settings ***
Library           Selenium2Library
Resource          rflib/common.robot
Library           pylib/baseconfig.py


*** Keywords ***
 Log in to Netease mailbox 
	[Arguments]    ${
     account number }=${
     jurisdiction 1 account number }      ${
     password }=${
     jurisdiction 1 password }
	#  open chrome Browser access 163 mailbox 
	open browser    ${
     Netease email address }[1]        chrome
	sleep    5
	maximize browser window
	#  Switch to iframe
	select frame    ${
    iframe}
	#  Enter... In the user name input box   user name 
	sleep    2
	input text    ${
     User name input box }      ${
     account number }
	sleep    2
	#  Enter... In the password input box   password 
	input text    ${
     Password input box }     ${
     password }
	sleep    2
	#  Click the login button 
	click element    ${
     The login button }
	sleep    10

 Close the browser 
	close browser


 Back to the front page 
	click element    ${
     Home button }
    sleep    10


 Go to the letter page 
	click element    ${
     Write button }
    sleep    10

 Upload files 
    [Arguments]       ${
     Upload to web page element location }     ${
     File name }
    ${
     File path }         ReturnPath      ${
     File name }
    sleep    1
    wait until page contains element        ${
     Upload to web page element location }
    choose file     ${
     Upload to web page element location }        ${
     File path }
    sleep    10

 Enter the mail 
    click element      ${
     Receiving button }
    sleep    2
    click element      ${
     First email }
    sleep    2


 Download the file 
    [Arguments]          ${
     Download button element location }
    CleanFile
    sleep    4
    wait until page contains element        ${
     Download button element location }
    click element      ${
     Download button element location }
    sleep    10


 Verify file name 
    sleep    5
    ${
     Verification results }         CheckFileName        test 
    log       ---------------------- Start validation --------------------
    should be true      $ Verification results ==' Test file name verification pass '



Test case catalog

TestSuit The directory is used to place the for executing test cases robot file

test.robot

*** Settings ***
Library           Selenium2Library
Library           pylib/baseconfig.py

Resource          WebKeyWord/ Business keywords .robot
Resource          rflib/common.robot

Suite Setup        Log in to Netease mailbox 
Suite Teardown     Close the browser 


*** Test Cases ***

 Test upload file 
	 Go to the letter page 
	 Upload files             ${
     Upload button }         ${
     File name - test }
	[Teardown]          Back to the front page 


 Test Download File 
	 Enter the mail 
	 Download the file             ${
     Download button }
	 Verify file name 
	[Teardown]          Back to the front page 

Carry out orders

Through the command robot -P . --name automated testing -d result TestSuit
perform TestSuit Test cases in the directory , And output the test report content file to result Under the folder , The test report is named automated testing

版权声明
本文为[Sink the wine cup and fleeting time]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231402128733.html