「深度学习福利」大神带你进阶工程师,立即查看>>> 编译Magic Lantern时,遇到了 /lib/ld-linux.so.2: bad ELF interpreter: No such file or directory 错误,但是安装 glibc 却提示已经 already installed and latest version 其实这是因为只能依赖32位的glibc,我使用的系统是Centos7 x64,所以只要安装glibc.32就行了。 yum install glibc.i686 如果还遇到了类似的问题,都可以试着安装下32位的依赖解决问题。
supported Introduction Robot Framework test library for verifying and modifying XML documents. As the name implies, XML is a test library for verifying contents of XML files. In practice it is a pretty thin wrapper on top of Python's ElementTree XML API . The library has the following main usages: Parsing an XML file, or a string containing XML, into an XML element structure and finding certain elements from it for for further analysis (e.g. Parse XML and Get Element keywords). Getting text or attributes of elements (e.g. Get Element Text and Get Element Attribute ). Directly verifying text, attributes, or whole elements (e.g Element Text Should Be and Elements Should Be Equal ). Modifying XML and saving it (e.g. Set Element Text , Add Element and Save XML ). Table of contents Parsing XML Using lxml Example Finding elements with xpath Element attributes Handling XML namespaces Boolean arguments Shortcuts Keywords Parsing XML XML can be parsed into an element structure using Parse XML keyword. It accepts both paths to XML files and strings that contain XML. The keyword returns the root element of the structure, which then contains other elements as its children and their children. Possible comments and processing instructions in the source XML are removed. XML is not validated during parsing even if has a schema defined. How possible doctype elements are handled otherwise depends on the used XML module and on the platform. The standard ElementTree strips doctypes altogether but when using lxml they are preserved when XML is saved. With IronPython parsing XML with a doctype is not supported at all. The element structure returned by Parse XML , as well as elements returned by keywords such as Get Element , can be used as the source argument with other keywords. In addition to an already parsed XML structure, other keywords also accept paths to XML files and strings containing XML similarly as Parse XML . Notice that keywords that modify XML do not write those changes back to disk even if the source would be given as a path to a file. Changes must always saved explicitly using Save XML keyword. When the source is given as a path to a file, the forward slash character ( / ) can be used as the path separator regardless the operating system. On Windows also the backslash works, but it the test data it needs to be escaped by doubling it ( \\ ). Using the built-in variable ${/} naturally works too. Using lxml By default this library uses Python's standard ElementTree module for parsing XML, but it can be configured to use lxml module instead when importing the library. The resulting element structure has same API regardless which module is used for parsing. The main benefits of using lxml is that it supports richer xpath syntax than the standard ElementTree and enables using Evaluate Xpath keyword. It also preserves the doctype and possible namespace prefixes saving XML. The lxml support is new in Robot Framework 2.8.5. Example The following simple example demonstrates parsing XML and verifying its contents both using keywords in this library and in BuiltIn and Collections libraries. How to use xpath expressions to find elements and what attributes the returned elements contain are discussed, with more examples, in Finding elements with xpath and Element attributes sections. In this example, as well as in many other examples in this documentation, ${XML} refers to the following example XML document. In practice ${XML} could either be a path to an XML file or it could contain the XML itself. textmore text
Text with bold and italics.
${root} =
Parse XML
${XML}
Should Be Equal
${root.tag}
example
${first} =
Get Element
${root}
first
Should Be Equal
${first.text}
text
Dictionary Should Contain Key
${first.attrib}
id
Element Text Should Be
Element Attribute Should Be
Element Attribute Should Be
Element Attribute Should Be ${first}
${first}
${root}
${XML} text
id
id
id
1
1
1
xpath=first
xpath=first
Notice that in the example three last lines are equivalent. Which one to use in practice depends on which other elements you need to get or verify. If you only need to do one verification, using the last line alone would suffice. If more verifications are needed, parsing the XML with Parse XML only once would be more efficient. Finding elements with xpath ElementTree, and thus also this library, supports finding elements using xpath expressions. ElementTree does not, however, support the full xpath syntax, and what is supported depends on its version. ElementTree 1.3 that is distributed with Python 2.7 supports richer syntax than earlier versions. The supported xpath syntax is explained below and ElementTree documentation provides more details. In the examples ${XML} refers to the same XML structure as in the earlier example. If lxml support is enabled when importing the library, the whole xpath 1.0 standard is supported. That includes everything listed below but also lot of other useful constructs. Tag names When just a single tag name is used, xpath matches all direct child elements that have that tag name.
${elem} =
Get Element
${XML}
third Should Be Equal
@{children} =
Length Should Be ${elem.tag}
Get Elements
${children} third
${elem}
2
child
Paths Paths are created by combining tag names with a forward slash ( / ). For example, parent/child matches all child elements under parent element. Notice that if there are multiple parent elements that all have child elements, parent/child xpath will match all these child elements.
${elem} =
Get Element
${XML}
second/child Should Be Equal
${elem} =
Should Be Equal ${elem.tag}
Get Element
${elem.tag} child
${XML}
grandchild
third/child/grandchild
Wildcards An asterisk ( * ) can be used in paths instead of a tag name to denote any element. @{children} =
Length Should Be Get Elements
${children} ${XML}
3 */child
Current element The current element is denoted with a dot ( . ). Normally the current element is implicit and does not need to be included in the xpath. Parent element The parent element of another element is denoted with two dots ( .. ). Notice that it is not possible to refer to the parent of the current element. This syntax is supported only in ElementTree 1.3 (i.e. Python/Jython 2.7 and newer). ${elem} =
Should Be Equal Get Element
${elem.tag} ${XML}
third */second/..
Search all sub elements Two forward slashes ( // ) mean that all sub elements, not only the direct children, are searched. If the search is started from the current element, an explicit dot is required.
@{elements} =
Get Elements
${XML}
.//second Length Should Be
${b} =
Should Be Equal ${elements}
Get Element
${b.text} 2
${XML}
bold
html//b
Predicates Predicates allow selecting elements using also other criteria than tag names, for example, attributes or position. They are specified after the normal tag name or path using syntax path[predicate] . The path can have wildcards and other special syntax explained above. What predicates ElementTree supports is explained in the table below. Notice that predicates in general are supported only in ElementTree 1.3 (i.e. Python/Jython 2.7 and newer). Predicate Matches Example
@attrib
Elements with attribute attrib .
second[ @id ]
@attrib="value"
Elements with attribute attrib having value value .
*[@id="2"] position
tag Elements at the specified position. Position can be an integer (starting from 1), expression last() , or relative expression like last() - 1 .
Elements with a child element named tag . third/child[1]
third/child[grandchild]
Predicates can also be stacked like path[predicate1][predicate2] . A limitation is that possible position predicate must always be first. Element attributes All keywords returning elements, such as Parse XML , and Get Element , return ElementTree's Element objects . These elements can be used as inputs for other keywords, but they also contain several useful attributes that can be accessed directly using the extended variable syntax. The attributes that are both useful and convenient to use in the test data are explained below. Also other attributes, including methods, can be accessed, but that is typically better to do in custom libraries than directly in the test data. The examples use the same ${XML} structure as the earlier examples. tag The tag of the element. ${root} =
Should Be Equal Parse XML
${root.tag} ${XML}
example text The text that the element contains or Python None if the element has no text. Notice that the text does not contain texts of possible child elements nor text after or between children. Notice also that in XML whitespace is significant, so the text contains also possible indentation and newlines. To get also text of the possible children, optionally whitespace normalized, use Get Element Text keyword.
${1st} =
Get Element
${XML}
first
Should Be Equal
${1st.text}
text
${2nd} =
Get Element
${XML}
second/child Should Be Equal
${p} =
Should Be Equal ${2nd.text}
Get Element
${p.text} ${NONE}
${XML}
\n${SPACE*6}Text with${SPACE}
html/p
tail The text after the element before the next opening or closing tag. Python None if the element has no tail. Similarly as with text , also tail contains possible indentation and newlines. ${b} =
Should Be Equal Get Element
${b.tail} ${XML}
${SPACE}and${SPACE} html/p/b
attrib A Python dictionary containing attributes of the element.
${2nd} =
Get Element
${XML}
second Should Be Equal
${3rd} =
Should Be Empty ${2nd.attrib['id']}
Get Element
${3rd.attrib} 2
${XML}
third
Handling XML namespaces ElementTree and lxml handle possible namespaces in XML documents by adding the namespace URI to tag names in so called Clark Notation. That is inconvenient especially with xpaths, and by default this library strips those namespaces away and moves them to xmlns attribute instead. That can be avoided by passing keep_clark_notation argument to Parse XML keyword. Alternatively Parse XML supports stripping namespace information altogether by using strip_namespaces argument. The pros and cons of different approaches are discussed in more detail below. How ElementTree handles namespaces If an XML document has namespaces, ElementTree adds namespace information to tag names in Clark Notation (e.g. {http://ns.uri}tag ) and removes original xmlns attributes. This is done both with default namespaces and with namespaces with a prefix. How it works in practice is illustrated by the following example, where ${NS} variable contains this XML document:
As you can see, including the namespace URI in tag names makes xpaths really long and complex. If you save the XML, ElementTree moves namespace information back to xmlns attributes. Unfortunately it does not restore the original prefixes: The resulting output is semantically same as the original, but mangling prefixes like this may still not be desirable. Notice also that the actual output depends slightly on ElementTree version. Default namespace handling Because the way ElementTree handles namespaces makes xpaths so complicated, this library, by default, strips namespaces from tag names and moves that information back to xmlns attributes. How this works in practice is shown by the example below, where ${NS} variable contains the same XML document as in the previous example.
${root} =
Parse XML
${NS}
Should Be Equal
Element Should Exist
Element Attribute Should Be
Element Attribute Should Be ${root.tag}
${root}
${root}
${root} stylesheet
template/html
xmlns
xmlns
http://www.w3.org/1999/XSL/Transform
http://www.w3.org/1999/xhtml
xpath=template/html
Now that tags do not contain namespace information, xpaths are simple again. A minor limitation of this approach is that namespace prefixes are lost. As a result the saved output is not exactly same as the original one in this case either: Also this output is semantically same as the original. If the original XML had only default namespaces, the output would also look identical. Namespaces when using lxml This library handles namespaces same way both when using lxml and when not using it. There are, however, differences how lxml internally handles namespaces compared to the standard ElementTree. The main difference is that lxml stores information about namespace prefixes and they are thus preserved if XML is saved. Another visible difference is that lxml includes namespace information in child elements got with Get Element if the parent element has namespaces. Stripping namespaces altogether Because namespaces often add unnecessary complexity, Parse XML supports stripping them altogether by using strip_namespaces=True . When this option is enabled, namespaces are not shown anywhere nor are they included if XML is saved. Attribute namespaces Attributes in XML documents are, by default, in the same namespaces as the element they belong to. It is possible to use different namespaces by using prefixes, but this is pretty rare. If an attribute has a namespace prefix, ElementTree will replace it with Clark Notation the same way it handles elements. Because stripping namespaces from attributes could cause attribute conflicts, this library does not handle attribute namespaces at all. Thus the following example works the same way regardless how namespaces are handled. ${root} =
Element Attribute Should Be
Element Attribute Should Be Parse XML
${root}
${root}
id
{http://my.ns}id
1
2 Boolean arguments Some keywords accept arguments that are handled as Boolean values true or false. If such an argument is given as a string, it is considered false if it is either an empty string or case-insensitively equal to false , none or no . Other strings are considered true regardless their value, and other argument types are tested using the same rules as in Python . True examples:
Parse XML
${XML}
keep_clark_notation=True
# Strings are generally true. Parse XML
Parse XML
Parse XML ${XML}
${XML}
${XML} keep_clark_notation=yes
keep_clark_notation=${TRUE}
keep_clark_notation=${42} # Same as the above.
# Python True is true.
# Numbers other than 0 are true.
False examples:
Parse XML
${XML}
keep_clark_notation=False
# String false is false. Parse XML
Parse XML
Parse XML ${XML}
${XML}
${XML} keep_clark_notation=no
keep_clark_notation=${EMPTY}
keep_clark_notation=${FALSE} # Also string no is false.
# Empty string is false.
# Python False is false.
Prior to Robot Framework 2.9, all non-empty strings, including false and no , were considered to be true. Considering none false is new in Robot Framework 3.0.3. Importing Arguments Documentation use_lxml=False Import library with optionally lxml mode enabled. By default this library uses Python's standard ElementTree module for parsing XML. If use_lxml argument is given a true value (see Boolean arguments ), the library will use lxml module instead. See Using lxml section for benefits provided by lxml. Using lxml requires that the lxml module is installed on the system. If lxml mode is enabled but the module is not installed, this library will emit a warning and revert back to using the standard ElementTree. The support for lxml is new in Robot Framework 2.8.5. Shortcuts Add Element · Clear Element · Copy Element · Element Attribute Should Be · Element Attribute Should Match · Element Should Exist · Element Should Not Exist · Element Should Not Have Attribute · Element Text Should Be · Element Text Should Match · Element To String · Elements Should Be Equal · Elements Should Match · Evaluate Xpath · Get Child Elements · Get Element · Get Element Attribute · Get Element Attributes · Get Element Count · Get Element Text · Get Elements · Get Elements Texts · Log Element · Parse Xml · Remove Element · Remove Element Attribute · Remove Element Attributes · Remove Elements · Remove Elements Attribute · Remove Elements Attributes · Save Xml · Set Element Attribute · Set Element Tag · Set Element Text · Set Elements Attribute · Set Elements Tag · Set Elements Text Keywords Keyword Arguments Documentation
Add Element
source, element,index=None, xpath=.
Adds a child element to the specified element. The element to whom to add the new element is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place. The element to add can be specified as a path to an XML file or as a string containing XML, or it can be an already parsed XML element. The element is copied before adding so modifying either the original or the added element has no effect on the other . The element is added as the last child by default, but a custom index can be used to alter the position. Indices start from zero (0 = first position, 1 = second position, etc.), and negative numbers refer to positions at the end (-1 = second last position, -2 = third last, etc.). Examples using ${XML} structure from Example :
Add Element
${XML}
Add Element
Add Element
${new} =
Elements Should Be Equal ${XML}
${XML}
Get Element
${new}
${XML}
xpath=new
index=1
new
xpath=new
Use Remove Element or Remove Elements to remove elements.
Clear Element
source, xpath=.,clear_tail=False
Clears the contents of the specified element. The element to clear is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place. Clearing the element means removing its text, attributes, and children. Element's tail text is not removed by default, but that can be changed by giving clear_tail a true value (see Boolean arguments ). See Element attributes section for more information about tail in general. Examples using ${XML} structure from Example :
Clear Element
${XML}
xpath=first
${first} =
Get Element
${XML}
xpath=first
Elements Should Be Equal
${first}
Clear Element
Element Text Should Be
Clear Element
Elements Should Be Equal ${XML}
${XML}
${XML}
${XML} xpath=html/p/b
Text with italics.
clear_tail=yes
xpath=html/p
normalize_whitespace=yes
Use Remove Element to remove the whole element.
Copy Element
source, xpath=.
Returns a copy of the specified element. The element to copy is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. If the copy or the original element is modified afterwards, the changes have no effect on the other. Examples using ${XML} structure from Example :
${elem} =
Get Element
${XML}
xpath=first
${copy1} =
Copy Element
${elem}
${copy2} =
Copy Element
${XML}
xpath=first
Set Element Text
${XML}
new text
xpath=first
Set Element Attribute
${copy1}
id
new Elements Should Be Equal
Elements Should Be Equal
Elements Should Be Equal ${elem}
${copy1}
${copy2} new text
text
text
Element Attribute Should Be
source, name, expected,xpath=., message=None
Verifies that the specified attribute is expected . The element whose attribute is verified is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The keyword passes if the attribute name of the element is equal to the expected value, and otherwise it fails. The default error message can be overridden with the message argument. To test that the element does not have a certain attribute, Python None (i.e. variable ${NONE} ) can be used as the expected value. A cleaner alternative is using Element Should Not Have Attribute . Examples using ${XML} structure from Example : Element Attribute Should Be
Element Attribute Should Be ${XML}
${XML} id
id 1
${NONE} xpath=first
See also Element Attribute Should Match and Get Element Attribute .
Element Attribute Should Match
source, name, pattern,xpath=., message=None
Verifies that the specified attribute matches expected . This keyword works exactly like Element Attribute Should Be except that the expected value can be given as a pattern that the attribute of the element must match. Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern, '*' matches anything and '?' matches any single character. Examples using ${XML} structure from Example :
Element Attribute Should Match
Element Attribute Should Match ${XML}
${XML} id
id ?
c*d xpath=first
xpath=third/second
Element Should Exist
source, xpath=.,message=None
Verifies that one or more element match the given xpath . Arguments source and xpath have exactly the same semantics as with Get Elements keyword. Keyword passes if the xpath matches one or more elements in the source . The default error message can be overridden with the message argument. See also Element Should Not Exist as well as Get Element Count that this keyword uses internally.
Element Should Not Exist
source, xpath=.,message=None
Verifies that no element match the given xpath . Arguments source and xpath have exactly the same semantics as with Get Elements keyword. Keyword fails if the xpath matches any element in the source . The default error message can be overridden with the message argument. See also Element Should Exist as well as Get Element Count that this keyword uses internally.
Element Should Not Have Attribute
source, name, xpath=.,message=None
Verifies that the specified element does not have attribute name . The element whose attribute is verified is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The keyword fails if the specified element has attribute name . The default error message can be overridden with the message argument. Examples using ${XML} structure from Example :
Element Should Not Have Attribute
Element Should Not Have Attribute ${XML}
${XML} id
xxx
xpath=first See also Get Element Attribute , Get Element Attributes , Element Text Should Be and Element Text Should Match .
Verifies that the text of the specified element is expected . The element whose text is verified is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The text to verify is got from the specified element using the same logic as with Get Element Text . This includes optional whitespace normalization using the normalize_whitespace option. The keyword passes if the text of the element is equal to the expected value, and otherwise it fails. The default error message can be overridden with the message argument. Use Element Text Should Match to verify the text against a pattern instead of an exact value. Examples using ${XML} structure from Example :
Verifies that the text of the specified element matches expected . This keyword works exactly like Element Text Should Be except that the expected value can be given as a pattern that the text of the element must match. Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern, '*' matches anything and '?' matches any single character. Examples using ${XML} structure from Example : Element Text Should Match
${paragraph} =
Element Text Should Match ${XML}
Get Element
${paragraph} t???
${XML}
Text with * and *. xpath=first
xpath=html/p
normalize_whitespace=yes
Element To String
source, xpath=.,encoding=None
Returns the string representation of the specified element. The element to convert to a string is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. By default the string is returned as Unicode. If encoding argument is given any value, the string is returned as bytes in the specified encoding. The resulting string never contains the XML declaration. See also Log Element and Save XML .
Verifies that the given source element is equal to expected . Both source and expected can be given as a path to an XML file, as a string containing XML, or as an already parsed XML element structure. See introduction for more information about parsing XML in general. The keyword passes if the source element and expected element are equal. This includes testing the tag names, texts, and attributes of the elements. By default also child elements are verified the same way, but this can be disabled by setting exclude_children to a true value (see Boolean arguments ). All texts inside the given elements are verified, but possible text outside them is not. By default texts must match exactly, but setting normalize_whitespace to a true value makes text verification independent on newlines, tabs, and the amount of spaces. For more details about handling text see Get Element Text keyword and discussion about elements' text and tail attributes in the introduction . Examples using ${XML} structure from Example :
${first} =
Get Element
${XML}
first
Elements Should Be Equal
${p} =
Elements Should Be Equal
Elements Should Be Equal ${first}
Get Element
${p}
${p} text
${XML}
Text with bold and italics.
Text with
html/p
normalize_whitespace=yes
exclude
normalize
The last example may look a bit strange because the
element only has text Text with . The reason is that rest of the text inside
actually belongs to the child elements. This includes the . at the end that is the tail text of the element. See also Elements Should Match .
Verifies that the given source element matches expected . This keyword works exactly like Elements Should Be Equal except that texts and attribute values in the expected value can be given as patterns. Pattern matching is similar as matching files in a shell, and it is always case-sensitive. In the pattern, '*' matches anything and '?' matches any single character. Examples using ${XML} structure from Example :
${first} =
Elements Should Match Get Element
${first} ${XML}
* first
See Elements Should Be Equal for more examples.
Evaluate Xpath
source, expression,context=.
Evaluates the given xpath expression and returns results. The element in which context the expression is executed is specified using source and context arguments. They have exactly the same semantics as source and xpath arguments have with Get Element keyword. The xpath expression to evaluate is given as expression argument. The result of the evaluation is returned as-is. Examples using ${XML} structure from Example :
${count} =
Evaluate Xpath
${XML}
count(third/*)
Should Be Equal
${count}
${3}
${text} =
Should Be Equal
${bold} =
Should Be Equal Evaluate Xpath
${text}
Evaluate Xpath
${bold} ${XML}
child
${XML}
${True} string(descendant::second[last()]/@id)
boolean(preceding-sibling::*[1] = 'bold')
context=html/p/i
This keyword works only if lxml mode is taken into use when importing the library. New in Robot Framework 2.8.5.
Get Child Elements
source, xpath=.
Returns the child elements of the specified element as a list. The element whose children to return is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. All the direct child elements of the specified element are returned. If the element has no children, an empty list is returned. Examples using ${XML} structure from Example :
${children} =
Get Child Elements
${XML}
Length Should Be
${children} =
Should Be Empty ${children}
Get Child Elements
${children} 4
${XML}
xpath=first
Get Element
source, xpath=.
Returns an element in the source matching the xpath . The source can be a path to an XML file, a string containing XML, or an already parsed XML element. The xpath specifies which element to find. See the introduction for more details about both the possible sources and the supported xpath syntax. The keyword fails if more, or less, than one element matches the xpath . Use Get Elements if you want all matching elements to be returned. Examples using ${XML} structure from Example : ${element} =
${child} = Get Element
Get Element ${XML}
${element} second
child Parse XML is recommended for parsing XML when the whole structure is needed. It must be used if there is a need to configure how XML namespaces are handled. Many other keywords use this keyword internally, and keywords modifying XML are typically documented to both to modify the given source and to return it. Modifying the source does not apply if the source is given as a string. The XML structure parsed based on the string and then modified is nevertheless returned.
Get Element Attribute
source, name, xpath=.,default=None
Returns the named attribute of the specified element. The element whose attribute to return is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The value of the attribute name of the specified element is returned. If the element does not have such element, the default value is returned instead. Examples using ${XML} structure from Example :
${attribute} =
Should Be Equal
${attribute} =
Should Be Equal Get Element Attribute
${attribute}
Get Element Attribute
${attribute} ${XML}
1
${XML}
value id
xx
xpath=first
xpath=first
default=value
See also Get Element Attributes , Element Attribute Should Be , Element Attribute Should Match and Element Should Not Have Attribute .
Get Element Attributes
source, xpath=.
Returns all attributes of the specified element. The element whose attributes to return is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. Attributes are returned as a Python dictionary. It is a copy of the original attributes so modifying it has no effect on the XML structure. Examples using ${XML} structure from Example :
${attributes} =
Get Element Attributes
${XML}
first Dictionary Should Contain Key
${attributes} =
Should Be Empty ${attributes}
Get Element Attributes
${attributes} id
${XML}
third
Use Get Element Attribute to get the value of a single attribute.
Get Element Count
source, xpath=.
Returns and logs how many elements the given xpath matches. Arguments source and xpath have exactly the same semantics as with Get Elements keyword that this keyword uses internally. See also Element Should Exist and Element Should Not Exist .
Get Element Text
source, xpath=.,normalize_whitespace=False
Returns all text of the element, possibly whitespace normalized. The element whose text to return is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. This keyword returns all the text of the specified element, including all the text its children and grandchildren contain. If the element has no text, an empty string is returned. The returned text is thus not always the same as the text attribute of the element. By default all whitespace, including newlines and indentation, inside the element is returned as-is. If normalize_whitespace is given a true value (see Boolean arguments ), then leading and trailing whitespace is stripped, newlines and tabs converted to spaces, and multiple spaces collapsed into one. This is especially useful when dealing with HTML data. Examples using ${XML} structure from Example :
${text} =
Get Element Text
${XML}
first
Should Be Equal
${text}
text
${text} =
Get Element Text
${XML}
second/child
Should Be Empty
${text}
${paragraph} =
${text} =
Should Be Equal Get Element
Get Element Text
${text} ${XML}
${paragraph}
Text with bold and italics. html/p
normalize_whitespace=yes
See also Get Elements Texts , Element Text Should Be and Element Text Should Match .
Get Elements
source, xpath
Returns a list of elements in the source matching the xpath . The source can be a path to an XML file, a string containing XML, or an already parsed XML element. The xpath specifies which element to find. See the introduction for more details. Elements matching the xpath are returned as a list. If no elements match, an empty list is returned. Use Get Element if you want to get exactly one match. Examples using ${XML} structure from Example :
${children} =
Get Elements
${XML}
third/child Length Should Be
${children} =
Should Be Empty ${children}
Get Elements
${children} 2
${XML}
first/child
Get Elements Texts
source, xpath,normalize_whitespace=False
Returns text of all elements matching xpath as a list. The elements whose text to return is specified using source and xpath . They have exactly the same semantics as with Get Elements keyword. The text of the matched elements is returned using the same logic as with Get Element Text . This includes optional whitespace normalization using the normalize_whitespace option. Examples using ${XML} structure from Example :
@{texts} =
Get Elements Texts
${XML}
third/child Length Should Be
Should Be Equal
Should Be Equal ${texts}
@{texts}[0]
@{texts}[1] 2
more text
${EMPTY}
Log Element
source, level=INFO, xpath=.
Logs the string representation of the specified element. The element specified with source and xpath is first converted into a string using Element To String keyword internally. The resulting string is then logged using the given level . The logged string is also returned.
Parses the given XML file or string into an element structure. The source can either be a path to an XML file or a string containing XML. In both cases the XML is parsed into ElementTree element structure and the root element is returned. Possible comments and processing instructions in the source XML are removed. As discussed in Handling XML namespaces section, this keyword, by default, removes namespace information ElementTree has added to tag names and moves it into xmlns attributes. This typically eases handling XML documents with namespaces considerably. If you do not want that to happen, or want to avoid the small overhead of going through the element structure when your XML does not have namespaces, you can disable this feature by giving keep_clark_notation argument a true value (see Boolean arguments ). If you want to strip namespace information altogether so that it is not included even if XML is saved, you can give a true value to strip_namespaces argument. This functionality is new in Robot Framework 3.0.2. Examples:
${root} =
${xml} =
${xml} = Parse XML
Parse XML
Parse XML
${CURDIR}/test.xml
${CURDIR}/test.xml
keep_clark_notation=True
strip_namespaces=True Use Get Element keyword if you want to get a certain element and not the whole structure. See Parsing XML section for more details and examples.
Remove Element
source, xpath=,remove_tail=False
Removes the element matching xpath from the source structure. The element to remove from the source is specified with xpath using the same semantics as with Get Element keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place. The keyword fails if xpath does not match exactly one element. Use Remove Elements to remove all matched elements. Element's tail text is not removed by default, but that can be changed by giving remove_tail a true value (see Boolean arguments ). See Element attributes section for more information about tail in general. Examples using ${XML} structure from Example :
Remove Element
Element Should Not Exist
Remove Element
Element Text Should Be ${XML}
${XML}
${XML}
${XML} xpath=second
xpath=second
xpath=html/p/b
Text with italics.
remove_tail=yes
xpath=html/p
normalize_whitespace=yes
Remove Element Attribute
source, name, xpath=.
Removes attribute name from the specified element. The element whose attribute to remove is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place. It is not a failure to remove a non-existing attribute. Use Remove Element Attributes to remove all attributes and Set Element Attribute to set them. Examples using ${XML} structure from Example : Remove Element Attribute
Element Should Not Have Attribute ${XML}
${XML} id
id xpath=first
xpath=first Can only remove an attribute from a single element. Use Remove Elements Attribute to remove an attribute of multiple elements in one call.
Remove Element Attributes
source, xpath=.
Removes all attributes from the specified element. The element whose attributes to remove is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place. Use Remove Element Attribute to remove a single attribute and Set Element Attribute to set them. Examples using ${XML} structure from Example :
Remove Element Attributes
Element Should Not Have Attribute ${XML}
${XML} xpath=first
id
xpath=first Can only remove attributes from a single element. Use Remove Elements Attributes to remove all attributes of multiple elements in one call.
Remove Elements
source, xpath=,remove_tail=False
Removes all elements matching xpath from the source structure. The elements to remove from the source are specified with xpath using the same semantics as with Get Elements keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place. It is not a failure if xpath matches no elements. Use Remove Element to remove exactly one element. Element's tail text is not removed by default, but that can be changed by using remove_tail argument similarly as with Remove Element . Examples using ${XML} structure from Example :
Remove Elements
${XML}
xpath=*/child Element Should Not Exist
Element Should Not Exist ${XML}
${XML} xpath=second/child
xpath=third/child
Remove Elements Attribute
source, name, xpath=.
Removes attribute name from the specified elements. Like Remove Element Attribute but removes the attribute of all elements matching the given xpath . New in Robot Framework 2.8.6.
Remove Elements Attributes
source, xpath=.
Removes all attributes from the specified elements. Like Remove Element Attributes but removes all attributes of all elements matching the given xpath . New in Robot Framework 2.8.6.
Save Xml
source, path,encoding=UTF-8
Saves the given element to the specified file. The element to save is specified with source using the same semantics as with Get Element keyword. The file where the element is saved is denoted with path and the encoding to use with encoding . The resulting file always contains the XML declaration. The resulting XML file may not be exactly the same as the original: Comments and processing instructions are always stripped. Possible doctype and namespace prefixes are only preserved when using lxml . Other small differences are possible depending on the ElementTree or lxml version. Use Element To String if you just need a string representation of the element.
Set Element Attribute
source, name, value,xpath=.
Sets attribute name of the specified element to value . The element whose attribute to set is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place. It is possible to both set new attributes and to overwrite existing. Use Remove Element Attribute or Remove Element Attributes for removing them. Examples using ${XML} structure from Example :
Set Element Attribute
Element Attribute Should Be
Set Element Attribute
Element Attribute Should Be ${XML}
${XML}
${XML}
${XML} attr
attr
id
id value
value
new
new
xpath=first
xpath=first Can only set an attribute of a single element. Use Set Elements Attribute to set an attribute of multiple elements in one call.
Set Element Tag
source, tag, xpath=.
Sets the tag of the specified element. The element whose tag to set is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place. Examples using ${XML} structure from Example :
Set Element Tag
${XML}
newTag
Should Be Equal
${XML.tag}
newTag
Set Element Tag
Element Should Exist
Element Should Not Exist ${XML}
${XML}
${XML} xxx
second/xxx
second/child xpath=second/child
Can only set the tag of a single element. Use Set Elements Tag to set the tag of multiple elements in one call.
Set Element Text
source, text=None,tail=None, xpath=.
Sets text and/or tail text of the specified element. The element whose text to set is specified using source and xpath . They have exactly the same semantics as with Get Element keyword. The resulting XML structure is returned, and if the source is an already parsed XML structure, it is also modified in place. Element's text and tail text are changed only if new text and/or tail values are given. See Element attributes section for more information about text and tail in general. Examples using ${XML} structure from Example :
Set Element Text
${XML}
new text
xpath=first
Element Text Should Be
${XML}
new text
xpath=first
Set Element Text
Element Text Should Be
Set Element Text
Element Text Should Be ${XML}
${XML}
${XML}
${XML} tail=&
Text with bold&italics.
slanted
Text with bold&slanted!! xpath=html/p/b
xpath=html/p
!!
xpath=html/p
normalize_whitespace=yes
xpath=html/p/i
normalize_whitespace=yes
Can only set the text/tail of a single element. Use Set Elements Text to set the text/tail of multiple elements in one call.
Set Elements Attribute
source, name, value,xpath=.
Sets attribute name of the specified elements to value . Like Set Element Attribute but sets the attribute of all elements matching the given xpath . New in Robot Framework 2.8.6. Set Elements Tag
Set Elements Text source, tag, xpath=.
source, text=None,tail=None, xpath=. Sets the tag of the specified elements. Like Set Element Tag but sets the tag of all elements matching the given xpath . New in Robot Framework 2.8.6.
Sets text and/or tail text of the specified elements. Like Set Element Text but sets the text or tail of all elements matching the given xpath . New in Robot Framework 2.8.6.
Altogether 37 keywords. Generated by Libdoc on 2018-04-25 23:41:29.
XML 图书馆版本:
3.0.4 图书馆范围:
全球 命名参数:
支持的 介绍 Robot Framework测试库,用于验证和修改XML文档。 顾名思义, XML 是用于验证XML文件内容的测试库。实际上,它是Python的 ElementTree XML API 之上的一个非常薄的包装器。 该库具有以下主要用途: 将XML文件或包含XML的字符串解析为XML元素结构,并从中查找某些元素以供进一步分析(例如, Parse XML 和 Get Element 关键字)。 获取元素的文本或属性(例如, 获取元素文本 和 获取元素属性 )。 直接验证文本,属性或整个元素(例如 元素文本应该 和 元素应该相等 )。 修改XML并保存它(例如, 设置元素文本 , 添加元素 和 保存XML )。 目录 解析XML 使用lxml 例 使用xpath查找元素 元素属性 处理XML名称空间 布尔参数 快捷键 关键词 解析XML 可以使用 Parse XML 关键字将XML解析为元素结构。它接受XML文件的路径和包含XML的字符串。关键字返回结构的根元素,然后包含其他元素作为其子元素及其子元素。将删除源XML中可能的注释和处理指令。 即使已定义架构,在解析期间也不验证XML。如何处理doctype元素,否则取决于使用的XML模块和平台。标准的ElementTree完全剥离了doctypes,但是当 使用lxml时, 它们会在保存XML时保留。使用IronPython时,根本不支持使用doctype解析XML。 Parse XML 返回的元素结构以及 Get Element source 等关键字返回的 元素 可以用作其他关键字的参数。除了已经解析的XML结构之外,其他关键字也接受XML文件的路径和包含XML的字符串,类似于 Parse XML 。请注意,修改XML的关键字不会将这些更改写回磁盘,即使源是作为文件的路径提供的。必须始终使用 Save XML 关键字显式 保存 更改。 当源作为文件的路径给出时,正斜杠字符( / )可以用作路径分隔符,而不管操作系统如何。在Windows上也可以使用反斜杠,但它需要通过加倍( \\ )来转义它所需的测试数据。使用内置变量也很 ${/} 自然。 使用lxml 默认情况下,此库使用Python的标准 ElementTree 模块来解析XML,但可以将其配置为在 导入 库时使用 lxml 模块。无论使用哪个模块进行解析,结果元素结构都具有相同的API。 使用lxml的主要好处是它支持比标准ElementTree更丰富的xpath语法,并允许使用 Evaluate Xpath 关键字。它还保留了保存XML的doctype和可能的名称空间前缀。 lxml支持是Robot Framework 2.8.5中的新增功能。 例 下面的简单示例演示了如何使用此库中的关键字以及 BuiltIn 和 Collections 库来解析XML并验证其内容。如何使用xpath表达式来查找元素以及返回的元素包含哪些属性,以及更多示例,在“ 使用xpath 和 元素属性 查找元素” 部分中进行讨论。 在此示例中,以及本文档中的许多其他示例中,请 ${XML} 参考以下示例XML文档。实际上, ${XML} 它可以是XML文件的路径,也可以包含XML本身。 <实例> text first> <子/> 秒> <第三> 更多文字 child> <子> <孙子/> 子> 第三>
返回 xpath 作为列表匹配的所有元素的文本。 要返回的文本使用 source 和指定的元素 xpath 。它们与 Get Elements 关键字具有完全相同的语义。 使用与 Get Element Text 相同的逻辑返回匹配元素的 文本 。这包括使用该 normalize_whitespace 选项的可选空白规范化。 使用示例 ${XML} 结构的 示例 :
@ {texts} =
获取元素文本
$ {} XML
第三/儿童 应该是长度
应该是平等的
应该是平等的 $ {}文本
@ {文本} [0]
@ {文本} [1] 2
更多文字
$ {EMPTY}
日志元素
source , level = INFO , xpath =。
记录指定元素的字符串表示形式。 使用 source 和指定的元素 xpath 首先在内部使用 Element To String 关键字转换为字符串。然后使用给定的字符串记录生成的字符串 level 。 还会返回记录的字符串。
supported Introduction A test library providing communication over Telnet connections. Telnet is Robot Framework's standard library that makes it possible to connect to Telnet servers and execute commands on the opened connections. Table of contents Connections Writing and reading Configuration Terminal emulation Logging Time string format Boolean arguments Importing Shortcuts Keywords Connections The first step of using Telnet is opening a connection with Open Connection keyword. Typically the next step is logging in with Login keyword, and in the end the opened connection can be closed with Close Connection . It is possible to open multiple connections and switch the active one using Switch Connection . Close All Connections can be used to close all the connections, which is especially useful in suite teardowns to guarantee that all connections are always closed. Writing and reading After opening a connection and possibly logging in, commands can be executed or text written to the connection for other reasons using Write and Write Bare keywords. The main difference between these two is that the former adds a configurable newline after the text automatically. After writing something to the connection, the resulting output can be read using Read , Read Until , Read Until Regexp , and Read Until Prompt keywords. Which one to use depends on the context, but the latest one is often the most convenient. As a convenience when running a command, it is possible to use Execute Command that simply uses Write and Read Until Prompt internally. Write Until Expected Output is useful if you need to wait until writing something produces a desired output. Written and read text is automatically encoded/decoded using a configured encoding . The ANSI escape codes, like cursor movement and color codes, are normally returned as part of the read operation. If an escape code occurs in middle of a search pattern it may also prevent finding the searched string. Terminal emulation can be used to process these escape codes as they would be if a real terminal would be in use. Configuration Many aspects related the connections can be easily configured either globally or per connection basis. Global configuration is done when library is imported , and these values can be overridden per connection by Open Connection or with setting specific keywords Set Timeout , Set Newline , Set Prompt , Set Encoding , Set Default Log Level and Set Telnetlib Log Level . Values of environ_user , window_size , terminal_emulation , and terminal_type can not be changed after opening the connection. Timeout Timeout defines how long is the maximum time to wait when reading output. It is used internally by Read Until , Read Until Regexp , Read Until Prompt , and Login keywords. The default value is 3 seconds. Connection Timeout Connection Timeout defines how long is the maximum time to wait when opening the telnet connection. It is used internally by Open Connection . The default value is the system global default timeout. New in Robot Framework 2.9.2. Newline Newline defines which line separator Write keyword should use. The default value is CRLF that is typically used by Telnet connections. Newline can be given either in escaped format using \n and \r or with special LF and CR syntax. Examples: Set Newline
Set Newline \n
CRLF Prompt Often the easiest way to read the output of a command is reading all the output until the next prompt with Read Until Prompt . It also makes it easier, and faster, to verify did Login succeed. Prompt can be specified either as a normal string or a regular expression. The latter is especially useful if the prompt changes as a result of the executed commands. Prompt can be set to be a regular expression by giving prompt_is_regexp argument a true value (see Boolean arguments ). Examples: Open Connection
Set Prompt lolcathost
(> |# ) prompt=$
prompt_is_regexp=true Encoding To ease handling text containing non-ASCII characters, all written text is encoded and read text decoded by default. The default encoding is UTF-8 that works also with ASCII. Encoding can be disabled by using a special encoding value NONE . This is mainly useful if you need to get the bytes received from the connection as-is. Notice that when writing to the connection, only Unicode strings are encoded using the defined encoding. Byte strings are expected to be already encoded correctly. Notice also that normal text in test data is passed to the library as Unicode and you need to use variables to use bytes. It is also possible to configure the error handler to use if encoding or decoding characters fails. Accepted values are the same that encode/decode functions in Python strings accept. In practice the following values are the most useful: ignore : ignore characters that cannot be encoded (default) strict : fail if characters cannot be encoded replace : replace characters that cannot be encoded with a replacement character Examples: Open Connection
Set Encoding
Set Encoding lolcathost
ISO-8859-15
errors=ignore encoding=Latin1
encoding_errors=strict
Using UTF-8 encoding by default and being able to configure the encoding are new features in Robot Framework 2.7.6. In earlier versions only ASCII was supported and encoding errors were silently ignored. Robot Framework 2.7.7 added a possibility to specify the error handler, changed the default behavior back to ignoring encoding errors, and added the possibility to disable encoding. Default log level Default log level specifies the log level keywords use for logging unless they are given an explicit log level. The default value is INFO , and changing it, for example, to DEBUG can be a good idea if there is lot of unnecessary output that makes log files big. Configuring default log level in importing and with Open Connection are new features in Robot Framework 2.7.6. In earlier versions only Set Default Log Level could be used. Terminal type By default the Telnet library does not negotiate any specific terminal type with the server. If a specific terminal type, for example vt100 , is desired, the terminal type can be configured in importing and with Open Connection . New in Robot Framework 2.8.2. Window size Window size for negotiation with the server can be configured when importing the library and with Open Connection . New in Robot Framework 2.8.2. USER environment variable Telnet protocol allows the USER environment variable to be sent when connecting to the server. On some servers it may happen that there is no login prompt, and on those cases this configuration option will allow still to define the desired username. The option environ_user can be used in importing and with Open Connection . New in Robot Framework 2.8.2. Terminal emulation Starting from Robot Framework 2.8.2, Telnet library supports terminal emulation with Pyte . Terminal emulation will process the output in a virtual screen. This means that ANSI escape codes, like cursor movements, and also control characters, like carriage returns and backspaces, have the same effect on the result as they would have on a normal terminal screen. For example the sequence acdc[3Dbba will result in output abba . Terminal emulation is taken into use by giving terminal_emulation argument a true value (see Boolean arguments ) either in the library initialization or with Open Connection . As Pyte approximates vt-style terminal, you may also want to set the terminal type as vt100 . We also recommend that you increase the window size, as the terminal emulation will break all lines that are longer than the window row length. When terminal emulation is used, the newline and encoding can not be changed anymore after opening the connection. Examples: Open Connection lolcathost terminal_emulation=True terminal_type=vt100 window_size=400x100 As a prerequisite for using terminal emulation, you need to have Pyte installed. Due to backwards incompatible changes in Pyte, different Robot Framework versions support different Pyte versions: Pyte 0.6 and newer are supported by Robot Framework 3.0.3. Latest Pyte version can be installed (or upgraded) with pip install --upgrade pyte . Pyte 0.5.2 and older are supported by Robot Framework 3.0.2 and earlier. Pyte 0.5.2 can be installed with pip install pyte==0.5.2 . Logging All keywords that read something log the output. These keywords take the log level to use as an optional argument, and if no log level is specified they use the configured default value. The valid log levels to use are TRACE , DEBUG , INFO (default), and WARN . Levels below INFO are not shown in log files by default whereas warnings are shown more prominently. The telnetlib module used by this library has a custom logging system for logging content it sends and receives. By default these messages are written using TRACE level. Starting with Robot Framework 2.8.7 the level is configurable with the telnetlib_log_level option either in the library initialization, to the Open Connection or by using the Set Telnetlib Log Level keyword to the active connection. Special level NONE con be used to disable the logging altogether. Time string format Timeouts and other times used must be given as a time string using format like 15 seconds or 1min 10s . If the timeout is given as just a number, for example, 10 or 1.5 , it is considered to be seconds. The time string format is described in more detail in an appendix of Robot Framework User Guide . Boolean arguments Some keywords accept arguments that are handled as Boolean values true or false. If such an argument is given as a string, it is considered false if it is either an empty string or case-insensitively equal to false , none or no . Other strings are considered true regardless their value, and other argument types are tested using the same rules as in Python . True examples:
Open Connection
lolcathost
terminal_emulation=True
# Strings are generally true. Open Connection
Open Connection
Open Connection lolcathost
lolcathost
lolcathost terminal_emulation=yes
terminal_emulation=${TRUE}
terminal_emulation=${42} # Same as the above.
# Python True is true.
# Numbers other than 0 are true.
False examples:
Open Connection
lolcathost
terminal_emulation=False
# String false is false. Open Connection
Open Connection
Open Connection lolcathost
lolcathost
lolcathost terminal_emulation=no
terminal_emulation=${EMPTY}
terminal_emulation=${FALSE} # Also string no is false.
# Empty string is false.
# Python False is false.
Prior to Robot Framework 2.9, all non-empty strings, including false and no , were considered to be true. Considering none false is new in Robot Framework 3.0.3. Importing Arguments Documentation timeout=3 seconds, newline=CRLF, prompt=None, prompt_is_regexp=False, encoding=UTF-8, encoding_errors=ignore, default_log_level=INFO, window_size=None, environ_user=None,terminal_emulation=False, terminal_type=None, telnetlib_log_level=TRACE,connection_timeout=None Telnet library can be imported with optional configuration parameters. Configuration parameters are used as default values when new connections are opened with Open Connection keyword. They can also be overridden after opening the connection using the Set ... keywords . See these keywords as well as Configuration , Terminal emulation and Logging sections above for more information about these parameters and their possible values. See Time string format and Boolean arguments sections for information about using arguments accepting times and Boolean values, respectively. Examples (use only one of these): Setting Value Value Value Value Comment
Library
Telnet
# default values
Library
Telnet
5 seconds
# set only timeout Library
Library
Library
Library
Library Telnet
Telnet
Telnet
Telnet
Telnet newline=LF
prompt=$
prompt=(> |# )
terminal_emulation=True
telnetlib_log_level=NONE encoding=ISO-8859-1
prompt_is_regexp=yes
terminal_type=vt100
window_size=400x100
# set newline and encoding using named arguments
# set prompt
# set prompt as a regular expression
# use terminal emulation with defined window size and terminal type
# disable logging messages from the underlying telnetlib
Shortcuts Close All Connections · Close Connection · Execute Command · Login · Open Connection · Read · Read Until · Read Until Prompt · Read Until Regexp · Set Default Log Level · Set Encoding · Set Newline · Set Prompt · Set Telnetlib Log Level · Set Timeout · Switch Connection · Write · Write Bare · Write Control Character · Write Until Expected Output Keywords Keyword Arguments Documentation
Close All Connections
Closes all open connections and empties the connection cache. If multiple connections are opened, this keyword should be used in a test or suite teardown to make sure that all connections are closed. It is not an error is some of the connections have already been closed by Close Connection . After this keyword, new indexes returned by Open Connection keyword are reset to 1.
Close Connection
loglevel=None
Closes the current Telnet connection. Remaining output in the connection is read, logged, and returned. It is not an error to close an already closed connection. Use Close All Connections if you want to make sure all opened connections are closed. See Logging section for more information about log levels.
Execute Command
command, loglevel=None, strip_prompt=False
Executes the given command and reads, logs, and returns everything until the prompt. This keyword requires the prompt to be configured either in importing or with Open Connection or Set Prompt keyword. This is a convenience keyword that uses Write and Read Until Prompt internally. Following two examples are thus functionally identical:
${out} = Execute Command pwd
Write
${out} = pwd
Read Until Prompt See Logging section for more information about log levels and Read Until Prompt for more information about the strip_prompt parameter.
Logs in to the Telnet server with the given user information. This keyword reads from the connection until the login_prompt is encountered and then types the given username . Then it reads until the password_prompt and types the given password . In both cases a newline is appended automatically and the connection specific timeout used when waiting for outputs. How logging status is verified depends on whether a prompt is set for this connection or not: 1) If the prompt is set, this keyword reads the output until the prompt is found using the normal timeout. If no prompt is found, login is considered failed and also this keyword fails. Note that in this case both login_timeout and login_incorrect arguments are ignored. 2) If the prompt is not set, this keywords sleeps until login_timeout and then reads all the output available on the connection. If the output contains login_incorrect text, login is considered failed and also this keyword fails. Both of these configuration parameters were added in Robot Framework 2.7.6. In earlier versions they were hard coded. See Configuration section for more information about setting newline, timeout, and prompt.
Opens a new Telnet connection to the given host and port. The timeout , newline , prompt , prompt_is_regexp , encoding , default_log_level , window_size , environ_user , terminal_emulation , terminal_type and telnetlib_log_level arguments get default values when the library is imported . Setting them here overrides those values for the opened connection. See Configuration , Terminal emulation and Logging sections for more information about these parameters and their possible values. Possible already opened connections are cached and it is possible to switch back to them using Switch Connection keyword. It is possible to switch either using explicitly given alias or using index returned by this keyword. Indexing starts from 1 and is reset back to it by Close All Connections keyword.
Read
loglevel=None
Reads everything that is currently available in the output. Read output is both returned and logged. See Logging section for more information about log levels.
Read Until
expected, loglevel=None
Reads output until expected text is encountered. Text up to and including the match is returned and logged. If no match is found, this keyword fails. How much to wait for the output depends on the configured timeout . See Logging section for more information about log levels. Use Read Until Regexp if more complex matching is needed.
Read Until Prompt
loglevel=None, strip_prompt=False
Reads output until the prompt is encountered. This keyword requires the prompt to be configured either in importing or with Open Connection or Set Prompt keyword. By default, text up to and including the prompt is returned and logged. If no prompt is found, this keyword fails. How much to wait for the output depends on the configured timeout . If you want to exclude the prompt from the returned output, set strip_prompt to a true value (see Boolean arguments ). If your prompt is a regular expression, make sure that the expression spans the whole prompt, because only the part of the output that matches the regular expression is stripped away. See Logging section for more information about log levels. Optionally stripping prompt is a new feature in Robot Framework 2.8.7.
Read Until Regexp
*expected
Reads output until any of the expected regular expressions match. This keyword accepts any number of regular expressions patterns or compiled Python regular expression objects as arguments. Text up to and including the first match to any of the regular expressions is returned and logged. If no match is found, this keyword fails. How much to wait for the output depends on the configured timeout . If the last given argument is a valid log level , it is used as loglevel similarly as with Read Until keyword. See the documentation of Python re module for more information about the supported regular expression syntax. Notice that possible backslashes need to be escaped in Robot Framework test data. Examples:
Read Until Regexp
(#|$)
Read Until Regexp
Read Until Regexp first_regexp
\\d{4}-\\d{2}-\\d{2} second_regexp
DEBUG
Set Default Log Level
level
Sets the default log level used for logging in the current connection. The old default log level is returned and can be used to restore the log level later. See Configuration section for more information about global and connection specific configuration.
Set Encoding
encoding=None, errors=None
Sets the encoding to use for writing and reading in the current connection. The given encoding specifies the encoding to use when written/read text is encoded/decoded, and errors specifies the error handler to use if encoding/decoding fails. Either of these can be omitted and in that case the old value is not affected. Use string NONE to disable encoding altogether. See Configuration section for more information about encoding and error handlers, as well as global and connection specific configuration in general. The old values are returned and can be used to restore the encoding and the error handler later. See Set Prompt for a similar example. If terminal emulation is used, the encoding can not be changed on an open connection. Setting encoding in general is a new feature in Robot Framework 2.7.6. Specifying the error handler and disabling encoding were added in 2.7.7.
Set Newline
newline
Sets the newline used by Write keyword in the current connection. The old newline is returned and can be used to restore the newline later. See Set Timeout for a similar example. If terminal emulation is used, the newline can not be changed on an open connection. See Configuration section for more information about global and connection specific configuration.
Set Prompt
prompt, prompt_is_regexp=False
Sets the prompt used by Read Until Prompt and Login in the current connection. If prompt_is_regexp is given a true value (see Boolean arguments ), the given prompt is considered to be a regular expression. The old prompt is returned and can be used to restore the prompt later. Example:
${prompt}
Do Something
Set Prompt ${regexp} =
${prompt} Set Prompt
${regexp} $
See the documentation of Python re module for more information about the supported regular expression syntax. Notice that possible backslashes need to be escaped in Robot Framework test data. See Configuration section for more information about global and connection specific configuration.
Set Telnetlib Log Level
level
Sets the log level used for logging in the underlying telnetlib . Note that telnetlib can be very noisy thus using the level NONE can shutdown the messages generated by this library. New in Robot Framework 2.8.7.
Set Timeout
timeout
Sets the timeout used for waiting output in the current connection. Read operations that expect some output to appear ( Read Until , Read Until Regexp , Read Until Prompt , Login ) use this timeout and fail if the expected output does not appear before this timeout expires. The timeout must be given in time string format . The old timeout is returned and can be used to restore the timeout later. Example:
${old} =
Set Timeout
2 minute 30 seconds Do Something
Set Timeout
${old}
See Configuration section for more information about global and connection specific configuration.
Switch Connection
index_or_alias
Switches between active connections using an index or an alias. Aliases can be given to Open Connection keyword which also always returns the connection index. This keyword returns the index of previous active connection. Example:
Open Connection
myhost.net
Login
john
secret
Write
some command
Open Connection
yourhost.com
2nd conn
Login
root
password
Write
another cmd
${old index}=
Switch Connection
1
# index
Write
something
Switch Connection
2nd conn
# alias Write
Switch Connection
[Teardown] whatever
${old index}
Close All Connections
# back to original
The example above expects that there were no other open connections when opening the first one, because it used index 1 when switching to the connection later. If you are not sure about that, you can store the index into a variable as shown below.
${index} =
Open Connection
myhost.net Do Something
Switch Connection
${index}
Write
text, loglevel=None
Writes the given text plus a newline into the connection. The newline character sequence to use can be configured both globally and per connection basis. The default value is CRLF . This keyword consumes the written text, until the added newline, from the output and logs and returns it. The given text itself must not contain newlines. Use Write Bare instead if either of these features causes a problem. Note: This keyword does not return the possible output of the executed command. To get the output, one of the Read ... keywords must be used. See Writing and reading section for more details. See Logging section for more information about log levels.
Write Bare
text
Writes the given text, and nothing else, into the connection. This keyword does not append a newline nor consume the written text. Use Write if these features are needed. Write Control Character
Write Until Expected Output character
text, expected, timeout, retry_interval, loglevel=None Writes the given control character into the connection. The control character is prepended with an IAC (interpret as command) character. The following control character names are supported: BRK, IP, AO, AYT, EC, EL, NOP. Additionally, you can use arbitrary numbers to send any control character. Example:
Write Control Character
Write Control Character BRK
241 # Send Break command
# Send No operation command
Writes the given text repeatedly, until expected appears in the output. text is written without appending a newline and it is consumed from the output before trying to find expected . If expected does not appear in the output within timeout , this keyword fails. retry_interval defines the time to wait expected to appear before writing the text again. Consuming the written text is subject to the normal configured timeout . Both timeout and retry_interval must be given in time string format . See Logging section for more information about log levels. Example:
Write Until Expected Output
... ps -ef| grep myprocess\r\n
5 s myprocess
0.5 s The above example writes command ps -ef | grep myprocess\r\n until myprocess appears in the output. The command is written every 0.5 seconds and the keyword fails if myprocess does not appear in the output in 5 seconds. Altogether 20 keywords. Generated by Libdoc on 2018-04-25 23:41:29. 远程登录 图书馆版本:
3.0.4 图书馆范围:
测试套件 命名参数:
支持的 介绍 通过Telnet连接提供通信的测试库。 Telnet 是Robot Framework的标准库,可以连接到Telnet服务器并在打开的连接上执行命令。 目录 连接 写作和阅读 组态 终端仿真 记录 时间字符串格式 布尔参数 输入 快捷键 关键词 连接 使用的第一步骤 Telnet 是打开与连接 打开连接 关键字。通常,下一步是使用 Login 关键字 登录 ,最后可以使用 Close Connection 关闭打开的连接。 可以使用 Switch Connection 打开多个连接并切换活动 连接 。 关闭所有连接 可用于关闭所有连接,这在套件拆卸中尤其有用,可确保始终关闭所有连接。 写作和阅读 打开连接并可能登录后,可以使用 Write 和 Write Bare 关键字执行命令或使用 Write 和 Write Bare 关键字将文本写入连接。这两者之间的主要区别在于前者在文本后自动添加可 配置的换行符 。 在向连接写入内容后,可以使用 Read , Read Until , Read Until Regexp 和 Read Until Prompt 关键字读取结果输出。使用哪一个取决于上下文,但最新的一个通常是最方便的。 为了方便运行命令,可以使用只 在 内部使用 Write 和 Read Until Prompt的 Execute Command 。如果您需要等到写入内容产生所需的输出,则 写入直到预期输出 非常有用。 使用 配置的编码 自动编码/解码写入和读取的文本。 ANSI转义码(如光标移动和颜色代码)通常作为读取操作的一部分返回。如果转义代码出现在搜索模式的中间,它也可能阻止查找搜索到的字符串。 终端仿真 可用于处理这些转义代码,如果真正的终端将被使用的话。 组态 可以在全局或每个连接的基础上轻松配置与连接相关的许多方面。 导入库 时完成全局配置,并且可以通过 Open Connection 或设置特定关键字 Set Timeout , Set Newline , Set Prompt , Set Encoding , Set Default Log Level 和 Set Telnetlib Log Level 来覆盖每个连接的这些值。 的价值观 environ_user , window_size , terminal_emulation ,和 terminal_type 无法打开连接后更改。 时间到 超时定义读取输出时等待的最长时间。它由 Read Until , Read Until Regexp , Read Until Prompt 和 Login 关键字在内部使用。默认值为3秒。 连接超时 连接超时定义打开telnet连接时等待的最长时间。它由 Open Connection在 内部使用。默认值是系统全局默认超时。 Robot Framework 2.9.2中的新功能。 新队 换行符定义 Write 关键字应使用的行分隔符。默认值是 CRLF Telnet连接通常使用的值。 新行可以使用给定无论是在转义格式 \n 和 \r 或有特殊 LF 和 CR 语法。 例子: 设置换行符
Sets the default log level used for logging in the current connection. The old default log level is returned and can be used to restore the log level later. See Configuration section for more information about global and connection specific configuration.
Set Encoding
encoding=None , errors=None
Sets the encoding to use for writing and reading in the current connection. The given encoding specifies the encoding to use when written/read text is encoded/decoded, and errors specifies the error handler to use if encoding/decoding fails. Either of these can be omitted and in that case the old value is not affected. Use string NONE to disable encoding altogether. See Configuration section for more information about encoding and error handlers, as well as global and connection specific configuration in general. The old values are returned and can be used to restore the encoding and the error handler later. See Set Prompt for a similar example. If terminal emulation is used, the encoding can not be changed on an open connection. Setting encoding in general is a new feature in Robot Framework 2.7.6. Specifying the error handler and disabling encoding were added in 2.7.7.
Set Newline
newline
Sets the newline used by Write keyword in the current connection. The old newline is returned and can be used to restore the newline later. See Set Timeout for a similar example. 如果使用终端仿真,则无法在打开的连接上更改换行符。 有关全局和连接特定配置的详细信息,请参阅 配置 部分。
supported Introduction A test library for string manipulation and verification. String is Robot Framework's standard library for manipulating strings (e.g. Replace String Using Regexp , Split To Lines ) and verifying their contents (e.g. Should Be String ). Following keywords from BuiltIn library can also be used with strings: Catenate Get Length Length Should Be Should (Not) Be Empty Should (Not) Be Equal (As Strings/Integers/Numbers) Should (Not) Match (Regexp) Should (Not) Contain Should (Not) Start With Should (Not) End With Convert To String Convert To Bytes Shortcuts Convert To Lowercase · Convert To Uppercase · Decode Bytes To String · Encode String To Bytes · Fetch From Left · Fetch From Right · Generate Random String · Get Line · Get Line Count · Get Lines Containing String · Get Lines Matching Pattern · Get Lines Matching Regexp · Get Regexp Matches · Get Substring · Remove String · Remove String Using Regexp · Replace String · Replace String Using Regexp · Should Be Byte String · Should Be Lowercase · Should Be String · Should Be Titlecase · Should Be Unicode String · Should Be Uppercase · Should Not Be String · Split String · Split String From Right · Split String To Characters · Split To Lines · Strip String Keywords Keyword Arguments Documentation
Convert To Lowercase
string
Converts string to lowercase. Examples:
${str1} =
Convert To Lowercase
ABC
${str2} =
Convert To Lowercase
1A2c3D Should Be Equal
Should Be Equal ${str1}
${str2} abc
1a2c3d
New in Robot Framework 2.8.6.
Convert To Uppercase
string
Converts string to uppercase. Examples:
${str1} =
Convert To Uppercase
abc
${str2} =
Convert To Uppercase
1a2C3d Should Be Equal
Should Be Equal ${str1}
${str2} ABC
1A2C3D
New in Robot Framework 2.8.6.
Decode Bytes To String
bytes, encoding,errors=strict
Decodes the given bytes to a Unicode string using the given encoding . errors argument controls what to do if decoding some bytes fails. All values accepted by decode method in Python are valid, but in practice the following values are most useful: strict : fail if characters cannot be decoded (default) ignore : ignore characters that cannot be decoded replace : replace characters that cannot be decoded with a replacement character Examples:
${string} =
${string} = Decode Bytes To String
Decode Bytes To String ${bytes}
${bytes} UTF-8
ASCII
errors=ignore Use Encode String To Bytes if you need to convert Unicode strings to byte strings, and Convert To String in BuiltIn if you need to convert arbitrary objects to Unicode strings.
Encode String To Bytes
string, encoding,errors=strict
Encodes the given Unicode string to bytes using the given encoding . errors argument controls what to do if encoding some characters fails. All values accepted by encode method in Python are valid, but in practice the following values are most useful: strict : fail if characters cannot be encoded (default) ignore : ignore characters that cannot be encoded replace : replace characters that cannot be encoded with a replacement character Examples:
${bytes} =
${bytes} = Encode String To Bytes
Encode String To Bytes ${string}
${string} UTF-8
ASCII
errors=ignore Use Convert To Bytes in BuiltIn if you want to create bytes based on character or integer sequences. Use Decode Bytes To String if you need to convert byte strings to Unicode strings and Convert To String in BuiltIn if you need to convert arbitrary objects to Unicode.
Fetch From Left
string, marker
Returns contents of the string before the first occurrence of marker . If the marker is not found, whole string is returned. See also Fetch From Right , Split String and Split String From Right .
Fetch From Right
string, marker
Returns contents of the string after the last occurrence of marker . If the marker is not found, whole string is returned. See also Fetch From Left , Split String and Split String From Right .
Generate Random String
length=8, chars=[LETTERS][NUMBERS]
Generates a string with a desired length from the given chars . The population sequence chars contains the characters to use when generating the random string. It can contain any characters, and it is possible to use special markers explained in the table below: Marker Explanation
[LOWER]
Lowercase ASCII characters from a to z .
[UPPER]
Uppercase ASCII characters from A to Z . [LETTERS]
[NUMBERS] Lowercase and uppercase ASCII characters.
Numbers from 0 to 9.
Examples:
${ret} =
Generate Random String
${low} =
${bin} =
${hex} = Generate Random String
Generate Random String
Generate Random String 12
8
4 [LOWER]
01
[NUMBERS]abcdef
Get Line
string, line_number
Returns the specified line from the given string . Line numbering starts from 0 and it is possible to use negative indices to refer to lines from the end. The line is returned without the newline character. Examples: ${first} =
${2nd last} = Get Line
Get Line ${string}
${string} 0
-2 Use Split To Lines if all lines are needed.
Get Line Count
string
Returns and logs the number of lines in the given string.
Get Lines Containing String
string, pattern,case_insensitive=False
Returns lines of the given string that contain the pattern . The pattern is always considered to be a normal string, not a glob or regexp pattern. A line matches if the pattern is found anywhere on it. The match is case-sensitive by default, but giving case_insensitive a true value makes it case-insensitive. The value is considered true if it is a non-empty string that is not equal to false , none or no . If the value is not a string, its truth value is got directly in Python. Considering none false is new in RF 3.0.3. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples:
${lines} =
${ret} = Get Lines Containing String
Get Lines Containing String ${result}
${ret} An example
FAIL
case-insensitive See Get Lines Matching Pattern and Get Lines Matching Regexp if you need more complex pattern matching.
Get Lines Matching Pattern
string, pattern,case_insensitive=False
Returns lines of the given string that match the pattern . The pattern is a glob pattern where:
*
matches everything
?
matches any single character [chars]
[!chars] matches any character inside square brackets (e.g. [abc] matches either a , b or c )
matches any character not inside square brackets
A line matches only if it matches the pattern fully. The match is case-sensitive by default, but giving case_insensitive a true value makes it case-insensitive. The value is considered true if it is a non-empty string that is not equal to false , none or no . If the value is not a string, its truth value is got directly in Python. Considering none false is new in RF 3.0.3. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: ${lines} =
${ret} = Get Lines Matching Pattern
Get Lines Matching Pattern ${result}
${ret} Wild???? example
FAIL: *
case_insensitive=true See Get Lines Matching Regexp if you need more complex patterns and Get Lines Containing String if searching literal strings is enough.
Get Lines Matching Regexp
string, pattern,partial_match=False
Returns lines of the given string that match the regexp pattern . See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. By default lines match only if they match the pattern fully, but partial matching can be enabled by giving the partial_match argument a true value. The value is considered true if it is a non-empty string that is not equal to false , none or no . If the value is not a string, its truth value is got directly in Python. Considering none false is new in RF 3.0.3. If the pattern is empty, it matches only empty lines by default. When partial matching is enabled, empty pattern matches all lines. Notice that to make the match case-insensitive, you need to prefix the pattern with case-insensitive flag (?i) . Lines are returned as one string concatenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples:
${lines} =
${lines} =
${ret} = Get Lines Matching Regexp
Get Lines Matching Regexp
Get Lines Matching Regexp ${result}
${result}
${ret} Reg\\w{3} example
Reg\\w{3} example
(?i)FAIL: .*
partial_match=true
See Get Lines Matching Pattern and Get Lines Containing String if you do not need full regular expression powers (and complexity). partial_match argument is new in Robot Framework 2.9. In earlier versions exact match was always required.
Get Regexp Matches
string, pattern,*groups
Returns a list of all non-overlapping matches in the given string. string is the string to find matches from and pattern is the regular expression. See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. If no groups are used, the returned list contains full matches. If one group is used, the list contains only contents of that group. If multiple groups are used, the list contains tuples that contain individual group contents. All groups can be given as indexes (starting from 1) and named groups also as names. Examples:
Returns a substring from start index to end index. The start index is inclusive and end is exclusive. Indexing starts from 0, and it is possible to use negative indices to refer to characters from the end. Examples:
${ignore first} =
Get Substring
${string}
1
${ignore last} =
${5th to 10th} =
${first two} =
${last two} = Get Substring
Get Substring
Get Substring
Get Substring ${string}
${string}
${string}
${string}
4
-2 -1
10
1
Remove String
string, *removables
Removes all removables from the given string . removables are used as literal strings. Each removable will be matched to a temporary string from which preceding removables have been already removed. See second example below. Use Remove String Using Regexp if more powerful pattern matching is needed. If only a certain number of matches should be removed, Replace String or Replace String Using Regexp can be used. A modified version of the string is returned and the original string is not altered. Examples: ${str} =
Should Be Equal
${str} =
Should Be Equal Remove String
${str}
Remove String
${str} Robot Framework
Robot Frame
Robot Framework
R Framewrk work
o
bt
New in Robot Framework 2.8.2.
Remove String Using Regexp
string, *patterns
Removes patterns from the given string . This keyword is otherwise identical to Remove String , but the patterns to search for are considered to be a regular expression. See Replace String Using Regexp for more information about the regular expression syntax. That keyword can also be used if there is a need to remove only a certain number of occurrences. New in Robot Framework 2.8.2.
Replace String
string, search_for,replace_with,count=-1
Replaces search_for in the given string with replace_with . search_for is used as a literal string. See Replace String Using Regexp if more powerful pattern matching is needed. If you need to just remove a string see Remove String . If the optional argument count is given, only that many occurrences from left are replaced. Negative count means that all occurrences are replaced (default behaviour) and zero means that nothing is done. A modified version of the string is returned and the original string is not altered. Examples:
${str} =
Should Be Equal
${str} =
Should Be Equal Replace String
${str}
Replace String
${str} Hello, world!
Hello, tellus!
Hello, world!
Helo, world! world
l
tellus
${EMPTY}
count=1
Replace String Using Regexp
string, pattern,replace_with,count=-1
Replaces pattern in the given string with replace_with . This keyword is otherwise identical to Replace String , but the pattern to search for is considered to be a regular expression. See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. If you need to just remove a string see Remove String Using Regexp . Examples: ${str} =
${str} = Replace String Using Regexp
Replace String Using Regexp ${str}
${str} 20\\d\\d-\\d\\d-\\d\\d
(Hello|Hi)
${EMPTY}
count=1
Should Be Byte String
item, msg=None
Fails if the given item is not a byte string. Use Should Be Unicode String if you want to verify the item is a Unicode string, or Should Be String if both Unicode and byte strings are fine. See Should Be String for more details about Unicode strings and byte strings. The default error message can be overridden with the optional msg argument.
Should Be Lowercase
string, msg=None
Fails if the given string is not in lowercase. For example, 'string' and 'with specials!' would pass, and 'String' , '' and ' ' would fail. The default error message can be overridden with the optional msg argument. See also Should Be Uppercase and Should Be Titlecase .
Should Be String
item, msg=None
Fails if the given item is not a string. With Python 2, except with IronPython, this keyword passes regardless is the item a Unicode string or a byte string. Use Should Be Unicode String or Should Be Byte String if you want to restrict the string type. Notice that with Python 2, except with IronPython, 'string' creates a byte string and u'unicode' must be used to create a Unicode string. With Python 3 and IronPython, this keyword passes if the string is a Unicode string but fails if it is bytes. Notice that with both Python 3 and IronPython, 'string' creates a Unicode string, and b'bytes' must be used to create a byte string. The default error message can be overridden with the optional msg argument.
Should Be Titlecase
string, msg=None
Fails if given string is not title. string is a titlecased string if there is at least one character in it, uppercase characters only follow uncased characters and lowercase characters only cased ones. For example, 'This Is Title' would pass, and 'Word In UPPER' , 'Word In lower' , '' and ' ' would fail. The default error message can be overridden with the optional msg argument. See also Should Be Uppercase and Should Be Lowercase .
Should Be Unicode String
item, msg=None
Fails if the given item is not a Unicode string. Use Should Be Byte String if you want to verify the item is a byte string, or Should Be String if both Unicode and byte strings are fine. See Should Be String for more details about Unicode strings and byte strings. The default error message can be overridden with the optional msg argument.
Should Be Uppercase
string, msg=None
Fails if the given string is not in uppercase. For example, 'STRING' and 'WITH SPECIALS!' would pass, and 'String' , '' and ' ' would fail. The default error message can be overridden with the optional msg argument. See also Should Be Titlecase and Should Be Lowercase .
Should Not Be String
item, msg=None
Fails if the given item is a string. See Should Be String for more details about Unicode strings and byte strings. The default error message can be overridden with the optional msg argument.
Split String
string,separator=None,max_split=-1
Splits the string using separator as a delimiter string. If a separator is not given, any whitespace string is a separator. In that case also possible consecutive whitespace as well as leading and trailing whitespace is ignored. Split words are returned as a list. If the optional max_split is given, at most max_split splits are done, and the returned list will have maximum max_split + 1 elements. Examples:
@{words} =
@{words} =
${pre} Split String
Split String
${post} = ${string}
${string}
Split String
,${SPACE}
${string}
::
1 See Split String From Right if you want to start splitting from right, and Fetch From Left and Fetch From Right if you only want to get first/last part of the string.
Split String From Right
string,separator=None,max_split=-1
Splits the string using separator starting from right. Same as Split String , but splitting is started from right. This has an effect only when max_split is given. Examples:
${first}
${rest} ${rest} =
${last} = Split String
Split String From Right ${string}
${string} -
- 1
1
Split String To Characters
string
Splits the given string to characters. Example: @{characters} = Split String To Characters ${string} Split To Lines
Strip String string, start=0,end=None
string, mode=both,characters=None Splits the given string to lines. It is possible to get only a selection of lines from start to end so that start index is inclusive and end is exclusive. Line numbering starts from 0, and it is possible to use negative indices to refer to lines from the end. Lines are returned without the newlines. The number of returned lines is automatically logged. Examples:
@{lines} =
Split To Lines
${manylines}
@{ignore first} =
Split To Lines
${manylines}
1
@{ignore last} =
@{5th to 10th} =
@{first two} =
@{last two} = Split To Lines
Split To Lines
Split To Lines
Split To Lines ${manylines}
${manylines}
${manylines}
${manylines}
4
-2 -1
10
1
Use Get Line if you only need to get a single line.
Remove leading and/or trailing whitespaces from the given string. mode is either left to remove leading characters, right to remove trailing characters, both (default) to remove the characters from both sides of the string or none to return the unmodified string. If the optional characters is given, it must be a string and the characters in the string will be stripped in the string. Please note, that this is not a substring to be removed but a list of characters, see the example below. Examples:
${stripped}=
Strip String
${SPACE}Hello${SPACE}
Should Be Equal
${stripped}
Hello
${stripped}=
Strip String
${SPACE}Hello${SPACE}
mode=left Should Be Equal
${stripped}=
Should Be Equal ${stripped}
Strip String
${stripped} Hello${SPACE}
aabaHelloeee
Hello
characters=abe
New in Robot Framework 3.0. Altogether 30 keywords. Generated by Libdoc on 2018-04-25 23:41:29. 串 图书馆版本:
错误=忽略 Use Convert To Bytes in BuiltIn if you want to create bytes based on character or integer sequences. Use Decode Bytes To String if you need to convert byte strings to Unicode strings and Convert To String in BuiltIn if you need to convert arbitrary objects to Unicode.
Fetch From Left
string , marker
Returns contents of the string before the first occurrence of marker . If the marker is not found, whole string is returned. See also Fetch From Right , Split String and Split String From Right .
Fetch From Right
string , marker
Returns contents of the string after the last occurrence of marker . If the marker is not found, whole string is returned. See also Fetch From Left , Split String and Split String From Right .
Generate Random String
length=8 , chars=[LETTERS][NUMBERS]
Generates a string with a desired length from the given chars . The population sequence chars contains the characters to use when generating the random string. It can contain any characters, and it is possible to use special markers explained in the table below: Marker Explanation
[LOWER]
Lowercase ASCII characters from a to z .
[UPPER]
Uppercase ASCII characters from A to Z . [LETTERS]
[NUMBERS] Lowercase and uppercase ASCII characters.
Numbers from 0 to 9.
Examples:
${ret} =
Generate Random String
${low} =
${bin} =
${hex} = Generate Random String
Generate Random String
Generate Random String 12
8
4 [LOWER]
01
[NUMBERS]abcdef
Get Line
string , line_number
Returns the specified line from the given string . Line numbering starts from 0 and it is possible to use negative indices to refer to lines from the end. The line is returned without the newline character. Examples: ${first} =
${2nd last} = Get Line
Get Line ${string}
${string} 0
-2 Use Split To Lines if all lines are needed.
Get Line Count
string
Returns and logs the number of lines in the given string.
Get Lines Containing String
string , pattern , case_insensitive=False
Returns lines of the given string that contain the pattern . The pattern is always considered to be a normal string, not a glob or regexp pattern. A line matches if the pattern is found anywhere on it. The match is case-sensitive by default, but giving case_insensitive a true value makes it case-insensitive. The value is considered true if it is a non-empty string that is not equal to false , none or no . If the value is not a string, its truth value is got directly in Python. Considering none false is new in RF 3.0.3. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples:
${lines} =
${ret} = Get Lines Containing String
Get Lines Containing String ${result}
${ret} An example
FAIL
case-insensitive See Get Lines Matching Pattern and Get Lines Matching Regexp if you need more complex pattern matching.
Get Lines Matching Pattern
string , pattern , case_insensitive=False
Returns lines of the given string that match the pattern . The pattern is a glob pattern where:
*
matches everything
?
matches any single character [chars]
[!chars] matches any character inside square brackets (e.g. [abc] matches either a , b or c )
matches any character not inside square brackets
A line matches only if it matches the pattern fully. The match is case-sensitive by default, but giving case_insensitive a true value makes it case-insensitive. The value is considered true if it is a non-empty string that is not equal to false , none or no . If the value is not a string, its truth value is got directly in Python. Considering none false is new in RF 3.0.3. Lines are returned as one string catenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples: ${lines} =
${ret} = Get Lines Matching Pattern
Get Lines Matching Pattern ${result}
${ret} Wild???? example
FAIL: *
case_insensitive=true See Get Lines Matching Regexp if you need more complex patterns and Get Lines Containing String if searching literal strings is enough.
Get Lines Matching Regexp
string , pattern , partial_match=False
Returns lines of the given string that match the regexp pattern . See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. By default lines match only if they match the pattern fully, but partial matching can be enabled by giving the partial_match argument a true value. The value is considered true if it is a non-empty string that is not equal to false , none or no . If the value is not a string, its truth value is got directly in Python. Considering none false is new in RF 3.0.3. If the pattern is empty, it matches only empty lines by default. When partial matching is enabled, empty pattern matches all lines. Notice that to make the match case-insensitive, you need to prefix the pattern with case-insensitive flag (?i) . Lines are returned as one string concatenated back together with newlines. Possible trailing newline is never returned. The number of matching lines is automatically logged. Examples:
${lines} =
${lines} =
${ret} = Get Lines Matching Regexp
Get Lines Matching Regexp
Get Lines Matching Regexp ${result}
${result}
${ret} Reg\\w{3} example
Reg\\w{3} example
(?i)FAIL: .*
partial_match=true
See Get Lines Matching Pattern and Get Lines Containing String if you do not need full regular expression powers (and complexity). partial_match argument is new in Robot Framework 2.9. In earlier versions exact match was always required.
Get Regexp Matches
string , pattern , *groups
Returns a list of all non-overlapping matches in the given string. string is the string to find matches from and pattern is the regular expression. See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. If no groups are used, the returned list contains full matches. If one group is used, the list contains only contents of that group. If multiple groups are used, the list contains tuples that contain individual group contents. All groups can be given as indexes (starting from 1) and named groups also as names. Examples:
Returns a substring from start index to end index. The start index is inclusive and end is exclusive. Indexing starts from 0, and it is possible to use negative indices to refer to characters from the end. Examples:
${ignore first} =
Get Substring
${string}
1
${ignore last} =
${5th to 10th} =
${first two} =
${last two} = Get Substring
Get Substring
Get Substring
Get Substring ${string}
${string}
${string}
${string}
4
-2 -1
10
1
Remove String
string , *removables
Removes all removables from the given string . removables are used as literal strings. Each removable will be matched to a temporary string from which preceding removables have been already removed. See second example below. Use Remove String Using Regexp if more powerful pattern matching is needed. If only a certain number of matches should be removed, Replace String or Replace String Using Regexp can be used. A modified version of the string is returned and the original string is not altered. Examples: ${str} =
Should Be Equal
${str} =
Should Be Equal Remove String
${str}
Remove String
${str} Robot Framework
Robot Frame
Robot Framework
R Framewrk work
o
bt
New in Robot Framework 2.8.2.
Remove String Using Regexp
string , *patterns
Removes patterns from the given string . This keyword is otherwise identical to Remove String , but the patterns to search for are considered to be a regular expression. See Replace String Using Regexp for more information about the regular expression syntax. That keyword can also be used if there is a need to remove only a certain number of occurrences. New in Robot Framework 2.8.2.
Replace String
string , search_for , replace_with , count=-1
Replaces search_for in the given string with replace_with . search_for is used as a literal string. See Replace String Using Regexp if more powerful pattern matching is needed. If you need to just remove a string see Remove String . If the optional argument count is given, only that many occurrences from left are replaced. Negative count means that all occurrences are replaced (default behaviour) and zero means that nothing is done. A modified version of the string is returned and the original string is not altered. Examples:
${str} =
Should Be Equal
${str} =
Should Be Equal Replace String
${str}
Replace String
${str} Hello, world!
Hello, tellus!
Hello, world!
Helo, world! world
l
tellus
${EMPTY}
count=1
Replace String Using Regexp
string , pattern , replace_with , count=-1
Replaces pattern in the given string with replace_with . This keyword is otherwise identical to Replace String , but the pattern to search for is considered to be a regular expression. See BuiltIn.Should Match Regexp for more information about Python regular expression syntax in general and how to use it in Robot Framework test data in particular. If you need to just remove a string see Remove String Using Regexp . Examples: ${str} =
${str} = Replace String Using Regexp
Replace String Using Regexp ${str}
${str} 20\\d\\d-\\d\\d-\\d\\d
(Hello|Hi)
${EMPTY}
count=1
Should Be Byte String
item , msg=None
Fails if the given item is not a byte string. Use Should Be Unicode String if you want to verify the item is a Unicode string, or Should Be String if both Unicode and byte strings are fine. See Should Be String for more details about Unicode strings and byte strings. The default error message can be overridden with the optional msg argument.
Should Be Lowercase
string , msg=None
Fails if the given string is not in lowercase. For example, 'string' and 'with specials!' would pass, and 'String' , '' and ' ' would fail. The default error message can be overridden with the optional msg argument. See also Should Be Uppercase and Should Be Titlecase .
Should Be String
item , msg=None
Fails if the given item is not a string. With Python 2, except with IronPython, this keyword passes regardless is the item a Unicode string or a byte string. Use Should Be Unicode String or Should Be Byte String if you want to restrict the string type. Notice that with Python 2, except with IronPython, 'string' creates a byte string and u'unicode' must be used to create a Unicode string. With Python 3 and IronPython, this keyword passes if the string is a Unicode string but fails if it is bytes. Notice that with both Python 3 and IronPython, 'string' creates a Unicode string, and b'bytes' must be used to create a byte string. The default error message can be overridden with the optional msg argument.
Should Be Titlecase
string , msg=None
Fails if given string is not title. string is a titlecased string if there is at least one character in it, uppercase characters only follow uncased characters and lowercase characters only cased ones. For example, 'This Is Title' would pass, and 'Word In UPPER' , 'Word In lower' , '' and ' ' would fail. The default error message can be overridden with the optional msg argument. See also Should Be Uppercase and Should Be Lowercase .
Should Be Unicode String
item , msg=None
Fails if the given item is not a Unicode string. Use Should Be Byte String if you want to verify the item is a byte string, or Should Be String if both Unicode and byte strings are fine. See Should Be String for more details about Unicode strings and byte strings. The default error message can be overridden with the optional msg argument.
Should Be Uppercase
string , msg=None
Fails if the given string is not in uppercase. For example, 'STRING' and 'WITH SPECIALS!' would pass, and 'String' , '' and ' ' would fail. The default error message can be overridden with the optional msg argument. See also Should Be Titlecase and Should Be Lowercase .
Should Not Be String
item , msg=None
Fails if the given item is a string. See Should Be String for more details about Unicode strings and byte strings. The default error message can be overridden with the optional msg argument.
Split String
string , separator=None , max_split=-1
Splits the string using separator as a delimiter string. If a separator is not given, any whitespace string is a separator. In that case also possible consecutive whitespace as well as leading and trailing whitespace is ignored. Split words are returned as a list. If the optional max_split is given, at most max_split splits are done, and the returned list will have maximum max_split + 1 elements. Examples:
@{words} =
@{words} =
${pre} Split String
Split String
${post} = ${string}
${string}
Split String
,${SPACE}
${string}
::
1 See Split String From Right if you want to start splitting from right, and Fetch From Left and Fetch From Right if you only want to get first/last part of the string.
Split String From Right
string , separator=None , max_split=-1
Splits the string using separator starting from right. Same as Split String , but splitting is started from right. This has an effect only when max_split is given. Examples:
${first}
${rest} ${rest} =
${last} = Split String
Split String From Right ${string}
${string} -
- 1
1
Split String To Characters
string
Splits the given string to characters. Example: @{characters} = Split String To Characters ${string} Split To Lines
带状线 string , start=0 , end=None
string , mode = both , characters = None Splits the given string to lines. It is possible to get only a selection of lines from start to end so that start index is inclusive and end is exclusive. Line numbering starts from 0, and it is possible to use negative indices to refer to lines from the end. Lines are returned without the newlines. The number of returned lines is automatically logged. Examples:
@{lines} =
Split To Lines
${manylines}
@ {忽略第一} =
拆分为线
$ {} manylines
1
@ {ignore last} =
@ {5th to 10th} =
@ {前两个} =
@ {last two} = 拆分为线
拆分为线
拆分为线
拆分为线 $ {} manylines
$ {} manylines
$ {} manylines
$ {} manylines
4
-2 -1
10
1
如果您只需要获得一行,请使用 获取 行。
从给定字符串中删除前导和/或尾随空格。 mode 要么 left 删除前导字符, right 要删除尾随字符, both (默认)删除字符串两边的字符或 none 返回未修改的字符串。 如果 characters 给出了可选项,则它必须是字符串,并且字符串中的字符将在字符串中被删除。请注意,这不是要删除的子字符串,而是字符列表,请参阅下面的示例。 例子:
supported Introduction A test library providing keywords for OS related tasks. OperatingSystem is Robot Framework's standard library that enables various operating system related tasks to be performed in the system where Robot Framework is running. It can, among other things, execute commands (e.g. Run ), create and remove files and directories (e.g. Create File , Remove Directory ), check whether files or directories exists or contain something (e.g. File Should Exist , Directory Should Be Empty ) and manipulate environment variables (e.g. Set Environment Variable ). Table of contents Path separators Pattern matching Tilde expansion Boolean arguments Example Shortcuts Keywords Path separators Because Robot Framework uses the backslash ( \ ) as an escape character in the test data, using a literal backslash requires duplicating it like in c:\\path\\file.txt . That can be inconvenient especially with longer Windows paths, and thus all keywords expecting paths as arguments convert forward slashes to backslashes automatically on Windows. This also means that paths like ${CURDIR}/path/file.txt are operating system independent. Notice that the automatic path separator conversion does not work if the path is only a part of an argument like with Run and Start Process keywords. In these cases the built-in variable ${/} that contains \ or / , depending on the operating system, can be used instead. Pattern matching Some keywords allow their arguments to be specified as glob patterns where:
*
matches anything, even an empty string
?
matches any single character [chars]
[!chars] matches any character inside square brackets (e.g. [abc] matches either a , b or c )
matches any character not inside square brackets
Unless otherwise noted, matching is case-insensitive on case-insensitive operating systems such as Windows. Pattern matching is implemented using fnmatch module . Starting from Robot Framework 2.9.1, globbing is not done if the given path matches an existing file even if it would contain a glob pattern. Tilde expansion Paths beginning with ~ or ~username are expanded to the current or specified user's home directory, respectively. The resulting path is operating system dependent, but typically e.g. ~/robot is expanded to C:
「深度学习福利」大神带你进阶工程师,立即查看>>> Shortcuts Execute Manual Step · Get Selection From User · Get Value From User · Pause Execution 执行手动步骤 · 获取选择从用户 · 获得值从用户 · 暂停执行 Keywords Keyword Arguments Documentation
Pauses test execution and asks user to select a value. The selected value is returned. Pressing Cancel fails the keyword. message is the instruction shown in the dialog and values are the options given to the user. Example: ${username} = Get Selection From User Select user name user1 user2 admin Get Value From User
message=Test execution paused. Press OK to continue. Pauses test execution and asks user to input a value. Value typed by the user, or the possible default value, is returned. Returning an empty value is fine, but pressing Cancel fails the keyword. message is the instruction shown in the dialog and default_value is the possible default value shown in the input field. If hidden is given a true value, the value typed by the user is hidden. hidden is considered true if it is a non-empty string not equal to false , none or no , case-insensitively. If it is not a string, its truth value is got directly using same rules as in Python . Example: ${username} =
${password} = Get Value From User
Get Value From User Input user name
Input password default
hidden=yes Possibility to hide the typed in value is new in Robot Framework 2.8.4. Considering strings false and no to be false is new in RF 2.9 and considering string none false is new in RF 3.0.3.
暂停测试执行直到用户单击 Ok 按钮。. message is the message shown in the dialog.
「深度学习福利」大神带你进阶工程师,立即查看>>> 什么是 Fail2Ban? 我们需要在我们网站中防止密码的暴利破解。 Fail2Ban 是一个 Python 的应用来查看日志文件,使用的是 正则表达式 ,同时还可以与Shorewall (或者 iptables)直接工作来来启用临时黑名单。当一定的密码破解规则被使用后,就可以使用上面的方法了。我们可以用这个来限制给定的 URL 来访问 Confluence 的登录界面的次数。 安装要求 需要 Python 2.4 或者更新的版本。 需要指定下面的特定文档,这意味着你的 Apache 实例需要登录你的 Confluence 才能访问一个已知的日志文件(logfile)。你需要 按照下面的要求正确调整配置 。 如何设置 本列表是安装的核心部分: 针对 RHEL 我们有 RPM 是可以按照的,请进入 下载页面 ,同时你还可以下载源代码收手动进行安装。 配置文件在 /etc/fail2ban 在原始状态下,默认的配置文件在 .conf 文件( fail2ban.conf 和 jail.conf)。请不要对这个进行修改,如果你进行修改的话,将会导致升级的时候困难。 在 .local 文件中对配置进行修改,这个将会与 .conf 文件中的配置进行合并。这个文件只会对你需要的修改部分进行修改,能够让你的维护更加容易和简单。 过滤器(Filters)在 filter.d 中进行定义 — 在这里这里,你可以定义正则表达式,每个正则表达式进入自己的文件。 Actions 在 action.d 文件中定义 — 你可能不需要添加一个,但是你知道在那里进行定义的能够帮你更好的找到问题。 "jails" 是配置单元,这个配置单元用来指定一个进行检查的正则表达式,当线程达到数量后,更多的 actions 将会被启动,这个是在线程中配置的(例如,在 60 秒钟,超过 3 次的满足正则表达式条件的地址,将会被禁止访问 600 秒) Jails 是在 jail.conf and jail.local 中定义的。不要忘记了为每一个都启动设置 — 这个有可能导致错误的启用,正确的却没有启用。 运行 Fail2Ban 使用 /etc/init.d/fail2ban {start|stop|status } 来进行进程相关的操作 使用 fail2ban-client -d 来导出当前的配置到 STDOUT。在你对问题进行查看的时候,这个就非常有帮助。 请注意 CPU 的使用。尽管可能你使用了非常简单的正则表达式,也有可能会导致 CPU 的使用飙升,如果你的站点的访问量比较大的话。 日志可以日志到 syslog 或者一个文件,你可以选择哪种方式更加适合你。 通用配置 jail.local # The DEFAULT allows a global definition of the options. They can be override # in each jail afterwards. [DEFAULT] # "ignoreip" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not # ban a host which matches an address in this list. Several addresses can be # defined using space separator. # ignoreip = # "bantime" is the number of seconds that a host is banned. bantime = 600 # A host is banned if it has generated "maxretry" during the last "findtime" # seconds. findtime = 60 # "maxretry" is the number of failures before a host get banned. maxretry = 3 [ssh-iptables] enabled = false [apache-shorewall] enabled = true filter = cac-login action = shorewall logpath = /var/log/httpd/confluence-access.log bantime = 600 maxretry = 3 findtime = 60 backend = polling Confluence 的配置 下面仅仅被用来作为示例,你需要根据你的站点调整。 filter.d/confluence-login.conf [Definition] failregex = .*"GET /login.action ignoreregex = https://www.cwiki.us/display/CONF6ZH/Using+Fail2Ban+to+limit+login+attempts
public class KeyUtil { /** * 生成唯一的主键 * 格式: 时间+随机数 */ public static synchronized String genUniqueKey() { Random random = new Random(); Integer number = random.nextInt(900000) + 100000; return System.currentTimeMillis() + String.valueOf(number); } }
新建ResultVO.java ResultVO.java
@Data public class ResultVO { private Integer code; private String msg; private T data; }
1) model 配置表对应的实体类,类名、字段最好和表中一致 a.使用这个插件,可以省略getter/setter方法
RobotFramework之DateTime 背景 继续学习RobotFramework框架,这次看的是DateTime库。 DateTime 库是RobotFramework操作时间的一个库,可以进行很多时间方面的操作。 DateTime is a Robot Framework standard library that supports creating and converting date and time values (e.g. Get Current Date, Convert Time), as well as doing simple calculations with them (e.g. Subtract Time From Date, Add Time To Time). It supports dates and times in various formats, and can also be used by other libraries programmatically. Get Current Date 示例代码 *** Settings *** Library DateTime *** Test Cases *** test1 ${tm} get_current_date log ${tm 执行结果 11:08:49.158 INFO 2017-05-01 11:08:49.157 源代码 def get_current_date(time_zone='local', increment=0, result_format='timestamp', exclude_millis=False): if time_zone.upper() == 'LOCAL': dt = datetime.now() elif time_zone.upper() == 'UTC': dt = datetime.utcnow() else: raise ValueError("Unsupported timezone '%s'." % time_zone) date = Date(dt) + Time(increment) return date.convert(result_format, millis=is_falsy(exclude_millis)) 说明 这个方法可以不传入参数,默认使用的是当地时间,如果第一个参数传入 utc 不区分大小写,则会使用 utc 时间。如果需要一个时间偏移量,则可以在第二个参数中传入时间偏移,传入的参数可以是一个数字或者str的数字,单位为秒,比如如下代码,执行的结果就会相差1分钟 test1 ${tmdl} get_current_date local 60 ${tm} get_current_date log ${tm} log ${tmdl} Result KEYWORD BuiltIn . Log ${tm} Documentation: Logs the given message with the given level. Start / End / Elapsed: 20170501 11:22:13.600 / 20170501 11:22:13.600 / 00:00:00.000 11:22:13.600 INFO 2017-05-01 11:22:13.600 00:00:00.001KEYWORD BuiltIn . Log ${tmdl} Documentation: Logs the given message with the given level. Start / End / Elapsed: 20170501 11:22:13.600 / 20170501 11:22:13.601 / 00:00:00.001 11:22:13.601 INFO 2017-05-01 11:23:13.599 当然,也可以传入一个 timedelta ,会通过如下代码解析成秒数进行处理。 class Time(object): def __init__(self, time): self.seconds = float(self._convert_time_to_seconds(time)) def _convert_time_to_seconds(self, time): if isinstance(time, timedelta): # timedelta.total_seconds() is new in Python 2.7 return (time.days * 24 * 60 * 60 + time.seconds + time.microseconds / 1e6) return timestr_to_secs(time, round_to=None) 第三个参数为格式化参数,从代码中可以看到,默认传入的是 timestamp ,而这里的解析源代码如下 def convert(self, format, millis=True): dt = self.datetime if not millis: secs = 1 if dt.microsecond >= 5e5 else 0 dt = dt.replace(microsecond=0) + timedelta(seconds=secs) if '%' in format: return self._convert_to_custom_timestamp(dt, format) format = format.lower() if format == 'timestamp': return self._convert_to_timestamp(dt, millis) if format == 'datetime': return dt if format == 'epoch': return self._convert_to_epoch(dt) raise ValueError("Unknown format '%s'." % format) 所以,可以传入 timestamp 、 datetime 、 epoch 或者是我们正常格式化时间的 %Y%m%d 第四个参数传入的是布尔值,是否需要毫秒级的数据,默认是False,也就是有毫秒的,如果不需要的话,传入 ${true} 即可 Convert Date 示例代码 *** Settings *** Library DateTime *** Test Cases *** test1 ${tm} convert_date 20170501 log ${tm} 执行结果 11:58:27.558 INFO 2017-05-01 00:00:00.000 源代码 def convert_date(date, result_format='timestamp', exclude_millis=False, date_format=None): return Date(date, date_format).convert(result_format, millis=is_falsy(exclude_millis)) def convert(self, format, millis=True): dt = self.datetime if not millis: secs = 1 if dt.microsecond >= 5e5 else 0 dt = dt.replace(microsecond=0) + timedelta(seconds=secs) if '%' in format: return self._convert_to_custom_timestamp(dt, format) format = format.lower() if format == 'timestamp': return self._convert_to_timestamp(dt, millis) if format == 'datetime': return dt if format == 'epoch': return self._convert_to_epoch(dt) raise ValueError("Unknown format '%s'." % format) 说明 该方法就是一个时间格式转换的方法,在上一个方法 Get Current Date 中获取的结果如果需要其他格式,就可以用这个方法进行转换,参数传入与上一个方法一样。 Convert Time 示例代码 *** Settings *** Library DateTime *** Test Cases *** test1 ${tm} convert_time 10 timedelta log ${tm} 执行结果 12:06:08.990 INFO 0:00:10 源代码 def convert_time(time, result_format='number', exclude_millis=False): return Time(time).convert(result_format, millis=is_falsy(exclude_millis)) class Time(object): def __init__(self, time): self.seconds = float(self._convert_time_to_seconds(time)) def convert(self, format, millis=True): try: result_converter = getattr(self, '_convert_to_%s' % format.lower()) except AttributeError: raise ValueError("Unknown format '%s'." % format) seconds = self.seconds if millis else float(roundup(self.seconds)) return result_converter(seconds, millis) def _convert_to_number(self, seconds, millis=True): return seconds def _convert_to_verbose(self, seconds, millis=True): return secs_to_timestr(seconds) def _convert_to_compact(self, seconds, millis=True): return secs_to_timestr(seconds, compact=True) def _convert_to_timer(self, seconds, millis=True): return elapsed_time_to_string(seconds * 1000, include_millis=millis) def _convert_to_timedelta(self, seconds, millis=True): return timedelta(seconds=seconds) 说明 第一个参数是必传的,会在初始化 Time 类的时候转换成秒。源代码中的 convert 用了一个反射的方法,所以默认调用的是 _convert_to_number 会直接把传入的第一个参数转换成秒,然后返回。我写的示例代码填的是 timedelta ,会转换成时间格式。 Subtract Date From Date 示例代码 test ${time} Subtract Date From Date 2014-05-28 12:05:52 2014-05-28 12:05:10 log ${time} 执行结果 INFO 42.0 源代码 def subtract_date_from_date(date1, date2, result_format='number', exclude_millis=False, date1_format=None, date2_format=None): time = Date(date1, date1_format) - Date(date2, date2_format) return time.convert(result_format, millis=is_falsy(exclude_millis)) class Date(object): def __init__(self, date, input_format=None): self.seconds = self._convert_date_to_seconds(date, input_format) def _convert_date_to_seconds(self, date, input_format): if is_string(date): return self._string_to_epoch(date, input_format) elif isinstance(date, datetime): return self._mktime_with_millis(date) elif is_number(date): return float(date) raise ValueError("Unsupported input '%s'." % date) 说明 方法是获取两个日期之间的差值,最终结果单位是秒,从示例代码中可以看得出来。 Date 类会将传入的 date1 和 date2 转换成默认的格式,然后做一次减法。最后得到的日期结果,通过 time.convert 方法转成秒 Add Time To Date 示例代码 test ${time} add time to date 2014-05-28 12:05:03.111 7 days log ${time} 执行结果 INFO 2014-06-04 12:05:03.111 示例代码 def add_time_to_date(date, time, result_format='timestamp', exclude_millis=False, date_format=None): date = Date(date, date_format) + Time(time) return date.convert(result_format, millis=is_falsy(exclude_millis)) 说明 传入的参数 7 days 表示7天,这里的时间类型用的是 timedelta 类,支持以下的单位 days, seconds, minutes, hours ,如果不传,默认是 seconds Subtract Time From Date 示例代码 test ${time} subtract time from date 2014-05-28 12:05:03.111 7 days log ${time} 执行结果 INFO 2014-05-21 12:05:03.111 源代码 def subtract_time_from_date(date, time, result_format='timestamp', exclude_millis=False, date_format=None): date = Date(date, date_format) - Time(time) return date.convert(result_format, millis=is_falsy(exclude_millis)) Add Time To Time 示例代码 test ${time} add time to time 1 days 7 days log ${time} 执行结果 INFO 691200.0 源代码 def add_time_to_time(time1, time2, result_format='number', exclude_millis=False): time = Time(time1) + Time(time2) return time.convert(result_format, millis=is_falsy(exclude_millis)) Subtract Time From Time 示例代码 test ${time} subtract time from time 1 days 7 days log ${time} 执行结果 INFO -518400.0 源代码 def subtract_time_from_time(time1, time2, result_format='number', exclude_millis=False): time = Time(time1) - Time(time2) return time.convert(result_format, millis=is_falsy(exclude_millis)) 总结 DateTime 库主要的操作方式就只有 Date 和 Time 这两个类,只要搞懂这两个类的处理逻辑,就能理解 DateTime 这个库的操作方式