QuickStart демо проект Robot Framework
Введение
Официальное руководство для быстрого старта в RobotFramework можно
клонировать
с github
Документация
В этом проект предлагается изучить тесты на скрипт
login.py
, который симулирует авторизацию в приложение. Скрипт написан на
Python
и использует текстовые файлы в качестве симуляции
базы данных
Тесты написаны, разумеется, на Robot Framework, но в формате
reStructuredText
который представляет из себя обычный текст с вкраплениями роботовского кода. Запускать тесты из таких файлов можно только если
дополнительно к роботу установить библиотеку docutils.
Выглядит .rst примерно так:
Текст текст текст .. code:: robotframework код код Текст текст текст
Удобно для написания документации. Крайне неудобно когда нужно почитать код. Возможно те кто пользуется этим форматом знают какие-то хитрости, неизвестные мне. Если вы из этих - напишите в телеграм .
Ниже отрывок кода QuickStart.rst
Data-driven tests ----------------- Quite often several test cases are otherwise similar but they have slightly different input or output data. In these situations *data-driven tests* allows varying the test data without duplicating the workflow. With Robot Framework the `[Template]` setting turns a test case into a data-driven test where the template keyword is executed using the data defined in the test case body: .. code:: robotframework *** Test Cases *** Invalid password [Template] Creating user with invalid password should fail abCD5 ${PWD INVALID LENGTH} abCD567890123 ${PWD INVALID LENGTH} 123DEFG ${PWD INVALID CONTENT} abcd56789 ${PWD INVALID CONTENT} AbCdEfGh ${PWD INVALID CONTENT} abCD56+ ${PWD INVALID CONTENT} In addition to using the `[Template]` setting with individual tests, it would be possible to use the `Test Template` setting once in the settings table like `setups and teardowns`_ defined later in this guide. In our case that
Для составления документации, это довольно удобно, но искать куски тестов в документе полном обычного текста неприятно.
Клонировать репозиторий
Подробнее про команду git clone вы можете узнать здесь
git clone https://github.com/robotframework/QuickStartGuide.git
Данные тесты написаны с помощью reStructuredText , поэтому нужно устанвоить docutils.
python -m pip install docutils
Изучить содержимое скачанной директории:
cd QuickStartGuide
ll
drwxr-xr-x 5 andrei urnsu 4096 May 5 11:25 ./ drwxr-xr-x 5 andrei urnsu 4096 May 5 11:25 ../ -rw-r--r-- 1 andrei urnsu 796 May 5 11:25 BUILD.rst drwxr-xr-x 8 andrei urnsu 4096 May 5 11:25 .git/ drwxr-xr-x 2 andrei urnsu 4096 May 5 11:25 lib/ -rw-r--r-- 1 andrei urnsu 21237 May 5 11:25 QuickStart.rst -rw-r--r-- 1 andrei urnsu 359 May 5 11:25 README.rst drwxr-xr-x 2 andrei urnsu 4096 May 5 11:25 sut/
Рекомендую заранее создать и активировать виртуальное окружение Python в котором затем установить Robot Framework по инструкции
python -m venv venv
source venv/Scripts/activate
python -m pip install --upgrade pip
python -m pip install robotframework
python -m pip install docutils
Структура проекта
QuickStartGuide/ |-- BUILD.rst |-- QuickStart.rst |-- README.rst |-- lib | `-- LoginLibrary.py `-- sut `-- login.py 2 directories, 5 files
Демонстрация
Проект для тестирования логина находится в директории
sut
Скрипт называется
login.py
python sut/login.py create andrei HeiHeiru1
SUCCESS
python sut/login.py login andrei HeiHeiru1
Logged In
robot QuickStart.rst
============================================================================== QuickStart ============================================================================== User can create an account and log in | PASS | ------------------------------------------------------------------------------ User cannot log in with bad password | PASS | ------------------------------------------------------------------------------ User can change password | PASS | ------------------------------------------------------------------------------ Invalid password | PASS | ------------------------------------------------------------------------------ User status is stored in database | PASS | ------------------------------------------------------------------------------ QuickStart | PASS | 5 tests, 5 passed, 0 failed ============================================================================== Output: /home/andrei/robotframework/QuickStartGuide/output.xml Log: /home/andrei/robotframework/QuickStartGuide/log.html Report: /home/andrei/robotframework/QuickStartGuide/report.html
Без .rst
Так как мне очень не нравится читать код из мешанины в
QuickStart.rst
файле, я переписал всё в обычный .robot файл.
Теперь структура проекта выглядит так:
QuickStartGuide/ |-- BUILD.rst |-- QuickStart.robot |-- QuickStart.rst |-- README.rst |-- lib | `-- LoginLibrary.py `-- sut `-- login.py 2 directories, 6 files
Получился следующий оригинальный файл
*** Settings *** Library OperatingSystem Library lib/LoginLibrary.py Suite Setup Clear Login Database Test Teardown Clear Login Database Force Tags quickstart Default Tags example smoke *** Variables *** ${USERNAME} janedoe ${PASSWORD} J4n3D0e ${NEW PASSWORD} e0D3n4J ${DATABASE FILE} ${TEMPDIR}${/}robotframework-quickstart-db.txt ${PWD INVALID LENGTH} Password must be 7-12 characters long ${PWD INVALID CONTENT} Password must be a combination of lowercase and ... uppercase letters and numbers *** Test Cases *** User can create an account and log in Create Valid User fred P4ssw0rd Attempt to Login with Credentials fred P4ssw0rd Status Should Be Logged In User cannot log in with bad password Create Valid User betty P4ssw0rd Attempt to Login with Credentials betty wrong Status Should Be Access Denied User can change password Given a user has a valid account When she changes her password Then she can log in with the new password And she cannot use the old password anymore Invalid password [Template] Creating user with invalid password should fail abCD5 ${PWD INVALID LENGTH} abCD567890123 ${PWD INVALID LENGTH} 123DEFG ${PWD INVALID CONTENT} abcd56789 ${PWD INVALID CONTENT} AbCdEfGh ${PWD INVALID CONTENT} abCD56+ ${PWD INVALID CONTENT} User status is stored in database [Tags] variables database Create Valid User ${USERNAME} ${PASSWORD} Database Should Contain ${USERNAME} ${PASSWORD} Inactive Login ${USERNAME} ${PASSWORD} Database Should Contain ${USERNAME} ${PASSWORD} Active *** Keywords *** Clear login database Remove file ${DATABASE FILE} Create valid user [Arguments] ${username} ${password} Create user ${username} ${password} Status should be SUCCESS Creating user with invalid password should fail [Arguments] ${password} ${error} Create user example ${password} Status should be Creating user failed: ${error} Login [Arguments] ${username} ${password} Attempt to login with credentials ${username} ${password} Status should be Logged In # Keywords below used by higher level tests. Notice how given/when/then/and # prefixes can be dropped. And this is a comment. A user has a valid account Create valid user ${USERNAME} ${PASSWORD} She changes her password Change password ${USERNAME} ${PASSWORD} ${NEW PASSWORD} Status should be SUCCESS She can log in with the new password Login ${USERNAME} ${NEW PASSWORD} She cannot use the old password anymore Attempt to login with credentials ${USERNAME} ${PASSWORD} Status should be Access Denied Database Should Contain [Arguments] ${username} ${password} ${status} ${database} = Get File ${DATABASE FILE} Should Contain ${database} ${username}\t${password}\t${status}\n
Отметим, что здесь используются устаревшние настройки Force Tags и Default Tags , которые по-хорошему нужно заменить на Test Tags
*** Settings *** … Test Tags quickstart example smoke … *** Test Cases *** User status is stored in database [Tags] variables database -example -smoke
Под капотом
Как работают эти тесты. Разберём по порядку.
Тест User can create an account and log in пользуется ключевым словом Create valid user
которое вызывает метод create_user() из
LoginLibrary.py
*** Test Cases *** User can create an account and log in Create Valid User fred P4ssw0rd Attempt to Login with Credentials fred P4ssw0rd Status Should Be Logged In &hellip *** Keywords *** … Create valid user [Arguments] ${username} ${password} Create user ${username} ${password} Status should be SUCCESS
Метод create_user() вызывает метод _run_command()
# lib/LoginLibrary.py import os.path import subprocess import sys class LoginLibrary(object): def __init__(self): self._sut_path = os.path.join(os.path.dirname(__file__), '..', 'sut', 'login.py') self._status = '' def create_user(self, username, password): self._run_command('create', username, password) # … def _run_command(self, command, *args): command = [sys.executable, self._sut_path, command] + list(args) process = subprocess.Popen(command, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) self._status = process.communicate()[0].strip()
Метод _run_command() использует библиотеки sys и
subprocess
Советую изучить мою статью про
subprocess
здесь
Разберём что происходит в методе _run_command во время работы ключевого слова Create Valid User из теста User can create an account and log in
Первая строка:
def _run_command(self, command, *args):
self - это экземпляр класса LoginLibary.
В нём при инициализации в атрибут
self._sut_path (тип str) записан путь до скрипта
login.py
И статус self._status, в данный момент равный пустой строке
command - это строка 'create' , которую мы получили из метода create_user()
*args - это строки fred и P4ssw0rd которые как username и password мы получили из метода create_user(), который получил их
из ключевого слова Create valid user
Подробности про то как работают
*args и **kwargs
вы можете прочитать в статье
*args **kwargs Python
на моём сайте
devhops.ru
Вторая строка:
command = [sys.executable, self._sut_path, command] + list(args)
Теперь в переменной command содержится список из следующих элементов:
Путь до python
Путь до
login.py
"create"
"fred"
"P4ssw0rd"
['C:\venv\Scripts\python.exe', 'C:\QuickStartGuide\lib\..\sut\login.py', 'login', 'fred', 'P4ssw0rd']
Автор статьи: Андрей ОлеговичRobot Framework | |
Основы | |
Тест логина | |
Пустые поля | |
reStructuredText | |
QuickStart | |
Robot из Python |