MediaAerea-TI
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- title: 'Guía de pruebas automatizadas con Selenium + Robot Framework' --- # Guía de Pruebas Automatizadas con Selenium + Robot Framework La automatización de pruebas contribuye significativamente a mejorar la calidad del software, detectar errores de manera temprana y acelerar los ciclos de desarrollo. Además, facilita la ejecución de pruebas repetitivas en diferentes escenarios, navegadores o configuraciones sin intervención manual constante. En este contexto, herramientas como Selenium y Robot Framework permiten crear soluciones robustas para automatizar pruebas en aplicaciones web. Selenium proporciona la capacidad de controlar navegadores web y simular la interacción de un usuario con la interfaz, mientras que Robot Framework ofrece una estructura clara basada en palabras clave que facilita la creación, lectura y mantenimiento de los casos de prueba. La combinación de estas tecnologías permite desarrollar pruebas automatizadas eficientes, escalables y fáciles de comprender, incluso para equipos que no cuentan con una gran experiencia en programación. A lo largo de esta guía se abordarán los aspectos principales para implementar pruebas automatizadas utilizando Selenium y Robot Framework, incluyendo: - Requisitos previos y configuración del entorno de trabajo - Instalación de Robot Framework, Selenium y las dependencias necesarias - Diseño de pruebas automatizadas mediante archivos `.robot` - Interacción con elementos web utilizando distintos tipos de localizadores - Creación de validaciones para verificar el comportamiento del sistema - Organización de pruebas mediante keywords, recursos y variables - Ejecución de pruebas y generación de reportes automáticos - Aplicación de buenas prácticas para la automatización de pruebas --- ## Requisitos previos y entorno necesario ### Python (obligatorio) Python es el lenguaje base requerido para ejecutar Robot Framework y gestionar las dependencias del proyecto. Comando para verificar la instalación: ```bash python --version ``` ### Robot Framework Robot Framework permite crear y organizar casos de prueba utilizando una sintaxis basada en palabras clave. Comando de instalación: ```bash pip install robotframework ``` ### Selenium y SeleniumLibrary Selenium permite automatizar la interacción con navegadores web mediante la librería SeleniumLibrary. Comandos de instalación: ```bash pip install selenium pip install robotframework-seleniumlibrary ``` ### WebDriver del navegador Es necesario descargar el WebDriver correspondiente al navegador que se va a automatizar (por ejemplo, ChromeDriver para Google Chrome) y asegurarse de que esté en el PATH. ### Visual Studio Code Editor recomendado para crear y ejecutar los archivos `.robot`. --- ## ¿Qué es Robot Framework? Robot Framework es un framework open-source para automatización de pruebas. Permite crear, organizar y ejecutar casos de prueba usando una sintaxis basada en palabras clave (keywords), lo que facilita la lectura y mantenimiento de los tests incluso para personas con poca experiencia en programación. Se integra fácilmente con librerías como SeleniumLibrary para pruebas web, RequestsLibrary para APIs, y muchas otras. --- ## Diseño de pruebas con Robot Framework ### ¿Cómo funciona? Robot Framework organiza las pruebas mediante casos de prueba (Test Cases) y palabras clave (Keywords). - Cada caso de prueba describe una funcionalidad que se desea verificar. - Las palabras clave representan acciones, como abrir un navegador, escribir texto o hacer clic en un botón. - Las pruebas se pueden estructurar para ser reutilizables, legibles y mantenibles, incluso para personas con poca experiencia en programación. ### Estructura de un archivo `.robot` Un archivo `.robot` se divide en secciones principales: ```robot *** Settings *** # Configuración de librerías y recursos *** Variables *** # Declaración de variables reutilizables *** Test Cases *** # Casos de prueba *** Keywords *** # Palabras clave personalizadas ``` ### Ejemplo explicado paso a paso **Archivo:** `tests/login.robot` ```robot *** Settings *** Library SeleniumLibrary *** Variables *** ${URL} https://example.com/login ${USER} admin ${PASSWORD} 123456 *** Test Cases *** Login Correcto Open Browser ${URL} chrome Input Text id=username ${USER} Input Text id=password ${PASSWORD} Click Button id=login Wait Until Page Contains Dashboard Close Browser ``` **Explicación línea por línea:** 1. `Library SeleniumLibrary` → importa las funciones de Selenium para controlar navegadores. 2. **Variables** → `${URL}`, `${USER}`, `${PASSWORD}` se usan para no repetir datos. 3. **Test Case "Login Correcto"** → define un caso de prueba llamado "Login Correcto". 4. `Open Browser` → abre el navegador en la URL indicada. 5. `Input Text` → ingresa el usuario y la contraseña en los campos correspondientes. 6. `Click Button` → hace clic en el botón de login. 7. `Wait Until Page Contains` → espera hasta que la página muestre el texto "Dashboard" (verificación básica de éxito). 8. `Close Browser` → cierra el navegador al finalizar la prueba. --- ## Interacción con elementos web usando Selenium ### Tipos de localizadores Para automatizar pruebas web, Selenium permite identificar elementos de la página mediante localizadores. Los más comunes son: | Localizador | Descripción | |---|---| | `id` | Selecciona por el atributo `id` del elemento | | `name` | Selecciona por el atributo `name` | | `xpath` | Selecciona por la ruta XPath del elemento | | `css selector` | Selecciona usando selectores CSS | | `class name` | Selecciona por la clase CSS del elemento | | `link text` / `partial link text` | Selecciona enlaces por su texto completo o parcial | Ejemplo en Robot Framework: ```robot Input Text id=username ${USER} Click Button css=.btn-login ``` ### Acciones comunes en pruebas | Acción | Descripción | |---|---| | `Open Browser` | Abrir un navegador en una URL | | `Input Text` | Escribir texto en un campo | | `Click Button` / `Click Element` | Hacer clic en botones o enlaces | | `Select From List By Value / Label` | Seleccionar opciones en menús desplegables | | `Get Text` / `Element Should Contain` | Obtener o validar texto en la página | | `Close Browser` | Cerrar el navegador al finalizar la prueba | ### Esperas y sincronización Para asegurar que los elementos estén disponibles antes de interactuar, es importante usar esperas: - `Wait Until Element Is Visible` → espera hasta que el elemento aparezca en la página. - `Wait Until Page Contains` → espera hasta que aparezca cierto texto en la página. - `Sleep` → espera un tiempo fijo (menos recomendado). Ejemplo: ```robot Wait Until Element Is Visible id=login Input Text id=username ${USER} ``` --- ## Validaciones esenciales en pruebas Las validaciones permiten comprobar que la aplicación se comporta como se espera y son esenciales para garantizar la calidad del software. ### Verificación de elementos Se asegura que un elemento esté presente o visible antes de interactuar con él: ```robot Element Should Be Visible id=login-button Element Should Exist css=.form-input ``` - `Element Should Be Visible` → verifica que el elemento esté visible en la página. - `Element Should Exist` → verifica que el elemento exista en el DOM, aunque no sea visible. ### Validación de texto en la página Se comprueba que el contenido mostrado en la página sea correcto: ```robot Page Should Contain Dashboard Element Text Should Be id=welcome-msg Bienvenido, ${USER} ``` - `Page Should Contain` → valida que la página contenga un texto específico. - `Element Text Should Be` → valida que el texto de un elemento coincida exactamente con lo esperado. ### Uso de validaciones (asserts) Las validaciones permiten detener la prueba si ocurre un error, garantizando que los resultados sean confiables: ```robot Should Be Equal ${resultado} 10 Should Not Be Empty ${mensaje} ``` - `Should Be Equal` → compara dos valores y falla si no son iguales. - `Should Not Be Empty` → verifica que un valor no esté vacío. --- ## Gestión y organización de pruebas ### Keywords reutilizables Crear palabras clave personalizadas para acciones repetitivas y mejorar la mantenibilidad de los casos de prueba. ### Archivos de recursos Centralizar keywords y variables en archivos `.robot` o `.resource` para su reutilización en múltiples pruebas. ### Variables Definir variables globales para URLs, usuarios, contraseñas y otros datos que se repitan, facilitando cambios rápidos y consistentes. --- ## Estructura y ejecución de suites ### Agrupación de pruebas en suites Organizar los casos de prueba por funcionalidad o módulo, permitiendo ejecutar grupos de pruebas de manera ordenada y selectiva. ### Ejecución de pruebas - **Desde terminal:** ejecutar pruebas con el comando: ```bash robot nombre_archivo.robot ``` - **Desde Visual Studio Code:** usar la terminal integrada o extensiones de Robot Framework para ejecutar los tests. ### Generación de reportes automáticos Robot Framework crea automáticamente archivos HTML de reportes y logs, mostrando resultados detallados de cada ejecución: - `report.html` → resumen visual. - `log.html` → paso a paso de la ejecución. --- ## Buenas prácticas y solución de errores ### Errores comunes y soluciones | Error | Solución | |---|---| | Elementos no encontrados | Usar localizadores estables (`id`, `data-*`) y esperas explícitas | | Problemas de sincronización | Aplicar `Wait Until Element Is Visible` o `Wait Until Page Contains` | | Versiones incompatibles de WebDriver | Verificar compatibilidad con el navegador y la versión de Selenium | ### Buenas prácticas profesionales - Reutilizar keywords y variables. - Mantener nombres descriptivos para tests y keywords. - Organizar pruebas en suites lógicas. - Documentar los tests para facilitar mantenimiento y colaboración. - Probar en múltiples navegadores y entornos antes de producción. --- ## Referencias - (2022). *Robotframework.org*. https://robotframework.org/SeleniumLibrary/SeleniumLibrary.html - Ruiz, J. M. (2025, March 7). *Tutorial Robot Framework: Instalación y primeros pasos*. DEV Community. https://dev.to/jmr85/tutorial-robot-framework-instalacion-y-primeros-pasos-5cal

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully