Automation from zero to learn Python-based RobotFramework

 

Automation from zero to learn Python-based RobotFramework

 

A,        Python basis

1) Version Differences

version

coding

grammar

other

2.X

ASCII

try:

    raise TypeError, type error "

except TypeError, err:

    print err.message

……

3.X

UTF-8

try:

    raise TypeError ( "type error")

except TypeError as err:

    print(err)

Removing not equal <>

Removal of long type

New bytes type

 

 

 

 

 

 

 

 

 

 

 

 

 

2) O

text = input('Enter any content : ')       #输入

print("Your input content is : %s" % text)     #输出        
=============== C:\Python37\python.exe E: /TestScript.py ====================== Enter any content : who am I. Your input content is : who am I.

 

____________________________________________________________________________________________

 

3) branch circulation

for i in range(10):                #range(start, stop[, step])

    if i % 2 == 0:

        print(i, end=' ')
=============== C:\Python37\python.exe E: /TestScript.py ====================== 0 2 4 6 8

 

____________________________________________________________________________________________

 

4) Data Types

123 = A          # integer int () 

B = ' 123 '            # string STR () 

C = [. 1, 2,. 3]           # List List () 

D = (. 1, 2,. 3)           # tuple tuple () 

E = {1, 2, 3}           # set sET () 

F = { ' AA ' : 1, ' BB ' : 2}        # dictionary dict ()

 note:

  •  Strings, lists, tuples can be obtained by the index value, and cutting out section. For example: a [0] >>> 1, b [1: -] >>> '2'.
  •  Integer, string, tuple data immutable; unordered set is unique; key value must be unique and the paired dictionary.

____________________________________________________________________________________________

 

5) Function Method

class Operation ():           # class definition

    DEF the Add (Self, A, B):     # method definition

        return A + B         # returns the result 

opt = Operation ()            # instantiated class

Print (opt.add (. 3,. 5))         # calling a class method
=============== C: \ Python37 \ python.exe E: /TestScript.py ===================== =

8

 

____________________________________________________________________________________________

 

6) Import Module

from robot.api import logger

import configparser

 

____________________________________________________________________________________________

 

7) abnormal error

²   the KeyboardInterrupt         the Ctrl + C is pressed

²   AttributeError                 trying to access the object does not have properties (such as foo no property x, is trying to access foo.x)

²   IOError                          input / output abnormal (usually unable to open file)

²   ImportError                    not introduced into the package or module (typically name or path error, or no such third party package)

²   IndentationError           Syntax error (usually code is not properly aligned)

²   SyntaxError                    code is illegal, the code will not compile (usually grammatical errors, wrong)

²   NameError                    use a variable has not been given an object

²   IndexError                     subscript index out of sequence boundaries, (only three such elements f, f is trying to access [. 5])

²   TypeError                      incoming object type does not conform with the requirements of

²   KeyError                       trying to access key does not exist in the dictionary

²   ValueError                    incoming caller does not expect a value

 

 

 

Two,        robot framework foundation

1) Version Differences

version

installation

stand by

run

other

1.5.X before

wxPython2.8.x

Pyhton2.x

pybat
robot
jybot

……

1.7.X After

wxPython4.0.x

Pyhton2.x
Pyhton3.x

robot
jybot
custom script

New debug mode
Edit new font color
Grid new json check

 

 

 

 

 

 

 

 

 

 

2) O

Import Library    Dialogs                                                 

${username} =     Get Value From User            Input user name           default      

Log               ${username}                                                    

=======================================================

20190724 12:37:36.010 :  INFO : ${username} = zhangsir

20190724 12: 37: 36.010: INFO: zhangsir

 

_________________________________________________________________________________

 

3) branch circulation

FOR      ${i}              IN RANGE       5                           

         Run Keyword If     ${i}%2==0      Log        ${i}    
END
======================================================= 20190724 12:51:55.658 : INFO : 0 20190724 12:51:55.658 : INFO : 2 20190724 12:51:55.658 : INFO : 4

 

________________________________________________________________________________

 

4) Data Types 

${a}=       Set Variable          ${123}                                                     

${b}=       Set Variable          123                                                         

@{c}=       Create List            1           2          3                                

&{d}=      Create Dictionary      aa=1       bb=2      cc=3                                                     

=======================================================

20190724 13:44:11.701 :  INFO : ${a} = 123

20190724 13: 44: 11.717: INFO: $ {b} = 123

20190724 13: 44: 11.717: INFO: @ {c} = [1 | 2 | 3 ]

20190724 13:44:11.717 :  INFO : &{d} = { aa=1 | bb=2 | cc=3 }

20190724 13:44:11.717 :  INFO : 123

20190724 13:44:11.717 :  INFO : 123

20190724 13:44:11.717 :  INFO : ['1', '2', '3']

20190724 13: 44: 11 717: INFO: { ' aa ' : ' 1 ' , ' b ' : ' 2 ' , ' cc ' : ' 3 ' }

 

________________________________________________________________________________

 

5) Function Method

*** Keywords ***                                                                                

Library  MyLibrary                                                                              
*** Keywords *** Query Redis String [Arguments] ${key} ${db}=8 ${conn} Connected To Redis ${db} ${result} Get From Redis ${conn} ${key} [Return] ${result}

 

________________________________________________________________________________

 

6) Import Module

Import Library      MyLibrary                                                                 

Import Resource     BasicResource.robot                                                 

Import Variables    ${adultCode}          

 

________________________________________________________________________________

 

7) abnormal error

=======================================================

20190724 14:08:07.692 :  INFO : 123

20190724 14:08:07.692 :  FAIL :

Replacing variables from setting 'Variables' failed: Variable '${test}' not found. Did you mean:

    ${TEST_TAGS}

    ${TEST_NAME}

20190724 14:08:07.692 : DEBUG :

Traceback (most recent call last):

  None

 

 

 

 

Three,        robot framework common keywords

1) Evaluate keywords

Python pattern in the specified calculation expression and returns the result.

    • ${random} =   Evaluate random.randint(0, sys.maxint)      modules=random, sys  

 

2) Should Series Keyword

Verification test result for determination.

    • Of Be Empty Should : if the specified object is not empty then fail (and vice versa Should Not ...).

    • Equal of Be Should : if the specified object is not equal failure (and vice versa Should Not ...).

    • Of Be True Should : If the specified condition is not satisfied then fail (and vice versa Should Not ...).

    • Contain Should : If the specified object does not contain the failed (and vice versa Should Not ...).

    • ……

 

3) Convert Series Keyword

For data type conversion.

    • Integer the To the Convert : the specified item into an integer.

    • Number The the To the Convert : the specified item into a floating point.

    • String the To the Convert : convert the unicode string specified item.

    • ……

 

4) Run Keyword Series Keyword

Perform keyword based on true and false judgment conditions

    • Keyword the If RUN : If the condition is true, then the specified operational parameters specified keyword.

    • Keyword entitled to a repayment RUN : If the condition is false, then the specified operational parameters specified keyword.

    • Keyword RUN : execute the specified keyword with the specified parameters.

    • Keywords RUN : perform all the keywords specified in the order (using AND connection).

    • ……

 

5) Get Series Keyword

Gets the value of keyword role.

    • The Count GET : Returns the number of times item1 item2 appears.

    • The Length GET : Returns the length of the specified item.

    • Time GET : Returns the time format.

    • ……

 

6) Set Series Keyword

Set parameters or variables.

    • Variable the SET : set variables.

    • Variable the If the SET : Set the variable according to the specified conditions.

    • The Log Level the SET : Set the log register.

    • ……

 

7) other keywords

    • SLEEP : Sleep force specified time (in seconds).

    • Catenate : connecting a plurality of strings (a space by default).

    • Method, Call : call the method parameters specified object using the provided.

    • The If the For Loop Exit : If the condition is true, the end of the FOR loop.

 

 

 

Four,        robot framework installation

1) Installation Python3.x

First run python-3.7.3-amd64.exe, check the "Add Path ...", the best choice for custom installation in the root directory.

DOS command window is then opened, and are input python --version pip -version, displays a corresponding installation was successful is determined.

 

2) Installation related modules

   pip install redis

   pip install pysolr

   pip install pymysql

   pip install robotframework

   pip install robotframework-ride

   pip install robotframework-requests # interface for testing

   pip install robotframework-databaselibrary # database for testing

 

3) custom library management

The custom package into the Lib / site-packages can be under Python directory.

 

4) Common Error Handling

  • RF3.X run error, the message "python2.x call failed"?

  This is due to RF2.X installed before you switch to RF3.X after the data file is not clear cause.

  Please delete and search librarykeywords.db file in the system tray (AppData \ Roaming \ robot framework \ Ride) , restart RIDE.

            

 

  • Run RF3.X error, the message "Can not find pybat"?

    This is because RF3.X removed pybat mode, merged into robot mode. Change the execution mode for the robot, and change the file format to use cases .robot.

   

 

 

 

Fifth, the        date and time of treatment

1) Date Format

Common forms of l: 2019-07-20 18:45:18 (format " % Y-M-% D%% H:% M:% S ")

l Solr library: 2019-07-20T18: 45: 18Z (format " % Y-dT%%% M- H:% M:% SZ ")

l Redis library: Jul 7, 2019 6:45:18 PM (format " % B% D, the I% the Y%:% M:% S% P" )

l   MySQL库: datetime.datetime(2019, 7, 20, 18, 45, 18)

ms l containing: 2019-07-2018: 45: 18.000 (Format " % Y-M-% D%% H:% M:% F% S. ")

l timestamp: 1564453476000

l Other: 20190720184518 (Format " % the Y% m% D% H% M% S ")

 

2) Processing Method

※  the Convert a Date : The date format conversion, input may specify the output format (Epoch of the timestamp).

parameter:

date: date string

result_format: Returns the date format,

exclude_millis: whether rounding ms

date_format: formatted date format

Example:

| Convert For a Date   | 2014-05-28 12: 05: 03.111 | result_format = Epoch | # returns '1401267903.111' |

| Convert Date   |   Jul 7, 2019 6:45:18 PM  |  date_format=%b %d, %Y %I:%M:%S %p  |  #返回'2014-05-28 12:05:03'|

 

※  the Get a Date Current : get the current date and time, you can specify the output format.

parameter:

time_zone: get at this time of the current time zone (currently only supports local and UTC)

increment: set the return date time increment may be negative

result_format: Returns the date format.

exclude_millis: whether rounding ms

Example:

|   The Get a Date Current  | result_format =% Y-% M-% d | # returns today's date |

 

 

 

Six,        JSON processing

1) a standard format

{

"key1": {

"key2": 123,

"key3": "123",

"key4": [1, 2, 3],

"key5": {"key": "value"}

},

"key6": true,

"key7": null

}

 

2)     处理方法

※  Get Json Value:获取JSON中指定目标节点值。

参数:

json_string:JSON文档

json_pointer:JSON节点

示例:

| ${result}=        | Get Json Value   | {"foo": {"bar": [1,2,3]}}      | /foo/bar |

| Should Be Equal  | ${result}         | [1, 2, 3]                  |

 

※  Set Json Value:设置JSON中指定目标节点值。

参数:

json_string:JSON文档

json_pointer:JSON节点

json_value:JSON值

示例:

| ${result}=        | Set Json Value       | {"foo": {"bar": [1,2,3]}}      | /foo | 123 |

| Should Be Equal  | ${result}             | {"foo": 123}              |

 

 

 

七、   Jenkins集成

        

 

 

 

Guess you like

Origin www.cnblogs.com/leozhanggg/p/11395055.html