RequestsLibrary

repository·master·Indexed 19 days ago

https://github.com/marketsquare/robotframework-requests

A Robot Framework library that provides HTTP API testing capabilities by wrapping the Python Requests library. It supports sessionless keywords (GET, POST, etc.) with implicit response tracking, session-based requests via Create Session and * On Session keywords, and multipart-encoded file uploads. The library includes built-in status verification keywords like Status Should Be and Request Should Be Successful, and provides access to standard Python Requests response object attributes.

Tokens
5.7K
Snippets
18
Records
31
Agent score
68%

What's inside robotframework-requests

  1. Understand the transition from v0.8 to v1.0

    master

    The library is undergoing a significant architectural change to align with the Python Requests library and improve session management.

    • Keyword Renaming: Old keywords ending in * Request (e.g., Get Request) are deprecated and will be removed in version 1.0.0. They have been replaced by * On Session keywords (e.g., GET On Session).
    • Sessionless Support: The new structure allows for the introduction of sessionless keywords (e.g., GET) which do not require a pre-created session.
  2. Quick start with sessionless requests

    master

    In version 0.9 and later, you can perform HTTP requests without explicitly creating a session. You can call keywords like GET directly with a full URL.

    Key features:

    • Sessionless Keywords: Use GET, POST, etc., directly with a URL.
    • Implicit Response Tracking: Keywords like Status Should Be and Request Should Be Successfull can operate on the last response automatically without needing to pass the response object explicitly.
    *** Settings ***
    Library               RequestsLibrary
    
    *** Test Cases ***
    Quick Get Request Test
        ${response}=    GET  https://www.google.com
    
    Quick Get Request With Parameters Test
        ${response}=    GET  https://www.google.com/search  params=query=ciao  expected_status=200
    
    Quick Get A JSON Body Test
        ${response}=    GET  https://jsonplaceholder.typicode.com/posts/1
        Should Be Equal As Strings    1  ${response.json()}[id]
    
    # Using implicit response tracking (v0.9+)
    Verify Status
        GET  https://www.google.com
        Status Should Be  200
  3. Install RequestsLibrary

    master

    Depending on your Python version and requirements, you can install the library using pip.

    • For version 0.9 (supports Python 2.7+): Use the standard installation command.
    • For pre-release version 1.0a (supports Python 3.8+): Use the --pre flag to include pre-release versions.
    # Install version 0.9 (Python 2.7+)
    pip install robotframework-requests
    
    # Install pre-release version 1.0a (Python 3.8+)
    pip install robotframework-requests --pre
  4. Use GET On Session and POST On Session

    master

    For structured testing, use the * On Session keywords. This requires creating a session first using Create Session.

    Key Behaviors:

    • Implicit Assertions: * On Session keywords automatically fail if an error status code is returned.
    • Status Control: Use expected_status= to specify a desired status code (e.g., 201, OK, Bad request) or anything to prevent the keyword from failing on error status codes.
    • Parameter Order: These keywords follow the parameter order and structure of the original Python Requests library.
    *** Settings ***
    Library    Collections
    Library    RequestsLibrary
    Suite Setup    Create Session  jsonplaceholder  https://jsonplaceholder.typicode.com
    
    *** Test Cases ***
    Get Request Test
        Create Session    google  http://www.google.com
        ${resp_google}=   GET On Session  google  /  expected_status=200
        ${resp_json}=     GET On Session  jsonplaceholder  /posts/1
        Should Be Equal As Strings          ${resp_google.reason}  OK
        Dictionary Should Contain Value     ${resp_json.json()}  sunt aut facere repellat provident
    
    Post Request Test
        &{data}=    Create dictionary  title=Robotframework requests  body=This is a test!  userId=1
        ${resp}=    POST On Session    jsonplaceholder  /posts  json=${data}  expected_status=anything
        Status Should Be                 201  ${resp}
  5. Configure SSL verification and CA bundles

    master

    The verify parameter in session creation keywords controls SSL certificate validation:

    • Pass a Boolean (True or False) to enable or disable verification.
    • Pass a String representing a path to a CA bundle file to use a specific certificate authority.
    • Note: If passing a string, do not use the literal strings 'True' or 'False' if you intend to provide a file path.
  6. Configure retry logic for sessions

    master

    You can configure automatic retries during session creation using the following parameters:

    • max_retries: Total number of retries. A value of 0 disables retries.
    • backoff_factor: Delay between retries (e.g., 0.1 results in sleeps of 0.0, 0.2, 0.4).
    • retry_status_list: A list of integer HTTP status codes that trigger a retry (e.g., [502, 503]).
    • retry_method_list: A list of uppercased HTTP verbs (e.g., ['GET', 'POST']) that are allowed to be retried.
  7. Use HTTP 'On Session' keywords to perform requests

    master

    The RequestsOnSessionKeywords class provides a suite of Robot Framework keywords designed to perform HTTP requests using a previously established session. Instead of creating a new connection for every request, you provide the alias of an existing session created via Create Session.

    Common Parameters

    • alias: The name of the existing HTTP session to use.
    • url: The endpoint for the request.
    • expected_status: Defines which status codes are acceptable. By default, the keyword fails if an error status code is returned. To disable this implicit assertion, pass any or anything.
    • msg: A custom error message to use if the status code assertion fails.
    • **kwargs: Additional arguments supported by the underlying requests library (e.g., headers, cookies, timeout).
  8. Use HTTP Sessions for improved performance

    master

    To share an HTTP Session (including the same URL, headers, and cookies) across multiple requests, use the Create Session keyword. This allows the connection and SSL handshake to be recycled, increasing performance.

    Once a session is created with an alias, use the * On Session keywords (e.g., GET On Session, POST On Session) and pass the session alias as the first argument.

    *** Settings ***
    Library    Collections
    Library    RequestsLibrary
    Suite Setup    Create Session  jsonplaceholder  https://jsonplaceholder.typicode.com
    
    *** Test Cases ***
    Get Request Test
        Create Session    google  http://www.google.com
        ${resp_google}=   GET On Session  google  /  expected_status=200
        ${resp_json}=     GET On Session  jsonplaceholder  /posts/1
    
        Should Be Equal As Strings          ${resp_google.reason}  OK
        Dictionary Should Contain Value     ${resp_json.json()}  sunt aut facere repellat provident
    
    Post Request Test
        &{data}=    Create dictionary  title=Robotframework requests  body=This is a test!  userId=1
        ${resp}=    POST On Session    jsonplaceholder  /posts  json=${data}  expected_status=anything
        Status Should Be                 201  ${resp}
        Dictionary Should Contain Key    ${resp.json()}  id
    *** Settings ***
    Library    Collections
    Library    RequestsLibrary
    Suite Setup    Create Session  jsonplaceholder  https://jsonplaceholder.typicode.com
    
    *** Test Cases ***
    Get Request Test
        Create Session    google  http://www.google.com
        ${resp_google}=   GET On Session  google  /  expected_status=200
        ${resp_json}=     GET On Session  jsonplaceholder  /posts/1
    
        Should Be Equal As Strings          ${resp_google.reason}  OK
        Dictionary Should Contain Value     ${resp_json.json()}  sunt aut facere repellat provident
    
    Post Request Test
        &{data}=    Create dictionary  title=Robotframework requests  body=This is a test!  userId=1
        ${resp}=    POST On Session    jsonplaceholder  /posts  json=${data}  expected_status=anything
        Status Should Be                 201  ${resp}
        Dictionary Should Contain Key    ${resp.json()}  id
  9. Stream large file uploads

    master

    To upload large files without reading them entirely into memory, use Get File For Streaming Upload to obtain a file descriptor, then pass it to the data parameter of a request keyword. The library will automatically close the file descriptor after the request is completed.

    ${file_handle}=    Get File For Streaming Upload    /path/to/large_file.dat
    ${resp}=    POST    https://api.example.com/upload    data=${file_handle}
  10. Quick start with RequestsLibrary

    master

    To use RequestsLibrary in Robot Framework, import it in your *** Settings *** section. You can perform simple HTTP requests like GET or POST directly using URLs.

    Simple GET Request

    *** Settings ***
    Library    RequestsLibrary
    
    *** Test Cases ***
    Quick Get Request Test
        ${response}=    GET  https://www.google.com

    GET Request with Parameters

    *** Test Cases ***
    Quick Get Request With Parameters Test
        ${response}=    GET  https://www.google.com/search  params=query=ciao  expected_status=200

    Accessing JSON Body

    *** Test Cases ***
    Quick Get A JSON Body Test
        ${response}=    GET  https://jsonplaceholder.typicode.com/posts/1
        Should Be Equal As Strings    1  ${response.json()}[id]
    *** Settings ***
    Library    RequestsLibrary
    
    *** Test Cases ***
    Quick Get Request Test
        ${response}=    GET  https://www.google.com
    
    Quick Get Request With Parameters Test
        ${response}=    GET  https://www.google.com/search  params=query=ciao  expected_status=200
    
    Quick Get A JSON Body Test
        ${response}=    GET  https://jsonplaceholder.typicode.com/posts/1
        Should Be Equal As Strings    1  ${response.json()}[id]
  11. Handle RequestsLibrary exceptions

    master

    When writing Robot Framework tests using RequestsLibrary, you can catch the following custom exceptions to handle specific failure scenarios related to HTTP responses and status validation:

    • UnknownStatusError: Raised when an unexpected or unrecognized status code is encountered.
    • InvalidResponse: Raised when the response received from the server is malformed or invalid.
    • InvalidExpectedStatus: Raised when the actual status code of a response does not match the expected status code provided in a keyword argument.