Меню

Target controller is configured to use recording controller jmeter ошибка


Description


Philippe Mouawad



2014-12-21 14:57:27 UTC

Currently, HTTP(S) Test Script Recorder is very permissive when no recording controller is setup.
Documentation only mentions Recording Controller possibility but implementation tries to find a node in the following order:
- Defined / Saved target
- Recording Controller
- Thread Group
- Workbench

This behaviour is disturbing for many reasons:
- Created samples can sometime appear where you do not expect them to
- They can be created in Workbench which is weird as they will not be really usable

I propose to change this behaviour to:
- Display an error popup on start of proxy if targetNode.getTestElement() is not of type : GenericController or AbstractThreadGroup.

In fact I think it should be only Recording Controller but this may break existing behaviour.

Thoughts ?


Comment 1


Philippe Mouawad



2014-12-21 15:02:20 UTC

(In reply to Philippe Mouawad from comment #0)
> Currently, HTTP(S) Test Script Recorder is very permissive when no recording
> controller is setup.
> Documentation only mentions Recording Controller possibility but
> implementation tries to find a node in the following order:
> - Defined / Saved target
> - Recording Controller
> - Thread Group
> - Workbench
> 
> This behaviour is disturbing for many reasons:
> - Created samples can sometime appear where you do not expect them to
> - They can be created in Workbench which is weird as they will not be really
> usable
> 
> I propose to change this behaviour to:
> - Display an error popup on start of proxy if targetNode.getTestElement() is
> not of type : GenericController or AbstractThreadGroup.
> 
> In fact I think it should be only Recording Controller but this may break
> existing behaviour.
> 
> Thoughts ?

I propose to change this behaviour to:
- Display an error popup on start of proxy if "Target Controller" is configured to "Recording Controller" and if no "Recording Controller" exists

Thoughts


Comment 2


Milamber



2014-12-21 15:16:32 UTC

+1
The popup is a good idea.


Comment 3


Dzmitry Kashlach



2014-12-21 19:41:23 UTC

Hi JMeter team,

May be, another IMHO good variant is to remove "Use recording controller" from drop-down list e.g. to show user only nodes, which are really present in test-tree(Thread Groups, Controllers, whatever else)?


Comment 4


Sebb



2014-12-22 15:20:05 UTC

(In reply to Dzmitry Kashlach from comment #3)
> Hi JMeter team,
> 
> May be, another IMHO good variant is to remove "Use recording controller"
> from drop-down list e.g. to show user only nodes, which are really present
> in test-tree(Thread Groups, Controllers, whatever else)?

+1


Comment 5


UbikLoadPack support



2014-12-22 15:47:45 UTC

-1
This method is really helpful specially if you use Recording template.
Checking popup seems enough.

Regards


Comment 6


UbikLoadPack support



2014-12-22 15:48:02 UTC

(In reply to Milamber from comment #2)
> 
> +1
> The popup is a good idea.

+1 for this one


Comment 7


UbikLoadPack support



2014-12-22 15:54:45 UTC

(In reply to Dzmitry Kashlach from comment #3)
> Hi JMeter team,
> 
> May be, another IMHO good variant is to remove "Use recording controller"
> from drop-down list e.g. to show user only nodes, which are really present
> in test-tree(Thread Groups, Controllers, whatever else)?

Hi, another argument why removing it is not a good idea IMHO is bug 57382.
If you remove it then when reloading you will need to setup correctly target before using Test Plan, while with "Use recording controller", nothing is needed if you have a Recording controller.


Comment 8


Sebb



2014-12-22 16:01:13 UTC

(In reply to UbikLoadPack support from comment #5)
> -1
> This method is really helpful specially if you use Recording template.
> Checking popup seems enough.
> 
> Regards

Cannot the the recording template can be fixed so that it just works?


Comment 9


Sebb



2014-12-22 16:02:48 UTC

(In reply to UbikLoadPack support from comment #7)
> (In reply to Dzmitry Kashlach from comment #3)
> > Hi JMeter team,
> > 
> > May be, another IMHO good variant is to remove "Use recording controller"
> > from drop-down list e.g. to show user only nodes, which are really present
> > in test-tree(Thread Groups, Controllers, whatever else)?
> 
> Hi, another argument why removing it is not a good idea IMHO is bug 57382.
> If you remove it then when reloading you will need to setup correctly target
> before using Test Plan, while with "Use recording controller", nothing is
> needed if you have a Recording controller.

Not sure I see how Bug 57832 affects this.


Comment 10


UbikLoadPack support



2014-12-22 16:07:36 UTC

(In reply to Sebb from comment #9)
> (In reply to UbikLoadPack support from comment #7)
> > (In reply to Dzmitry Kashlach from comment #3)
> > > Hi JMeter team,
> > > 
> > > May be, another IMHO good variant is to remove "Use recording controller"
> > > from drop-down list e.g. to show user only nodes, which are really present
> > > in test-tree(Thread Groups, Controllers, whatever else)?
> > 
> > Hi, another argument why removing it is not a good idea IMHO is bug 57382.
> > If you remove it then when reloading you will need to setup correctly target
> > before using Test Plan, while with "Use recording controller", nothing is
> > needed if you have a Recording controller.
> 
> Not sure I see how Bug 57832 affects this.

Well if you remove "Use Recording Controller", then it means you rely on user setting the target controller explicitely right ?
So if he does, he saves his plans and reloads it later, due to bug the setting is forgotten and it now records not where user wanted it to record but as per the result of ProxyControl#findTargetControllerNode

So you have lost productivity with this change.

Regarding "Cannot the the recording template can be fixed so that it just works?" ? No you need to fix 57832 before.

Regards

(In reply to UbikLoadPack support from comment #10)
> (In reply to Sebb from comment #9)
> > (In reply to UbikLoadPack support from comment #7)
> > > (In reply to Dzmitry Kashlach from comment #3)
> > > > Hi JMeter team,
> > > > 
> > > > May be, another IMHO good variant is to remove "Use recording controller"
> > > > from drop-down list e.g. to show user only nodes, which are really present
> > > > in test-tree(Thread Groups, Controllers, whatever else)?
> > > 
> > > Hi, another argument why removing it is not a good idea IMHO is bug 57382.
> > > If you remove it then when reloading you will need to setup correctly target
> > > before using Test Plan, while with "Use recording controller", nothing is
> > > needed if you have a Recording controller.
> > 
> > Not sure I see how Bug 57832 affects this.
> 
> Well if you remove "Use Recording Controller", then it means you rely on
> user setting the target controller explicitely right ?

Yes.

> So if he does, he saves his plans and reloads it later, due to bug the
> setting is forgotten and it now records not where user wanted it to record
> but as per the result of ProxyControl#findTargetControllerNode
> 
> So you have lost productivity with this change.

Not if bug 57832 has been fixed, surely?
 
> Regarding "Cannot the the recording template can be fixed so that it just
> works?" ? No you need to fix 57832 before.

Fine, let's fix 57832.
 
> Regards


Comment 12


UbikLoadPack support



2014-12-22 16:22:24 UTC

(In reply to Sebb from comment #11)
> (In reply to UbikLoadPack support from comment #10)
> > (In reply to Sebb from comment #9)
> > > (In reply to UbikLoadPack support from comment #7)
> > > > (In reply to Dzmitry Kashlach from comment #3)
> > > > > Hi JMeter team,
> > > > > 
> > > > > May be, another IMHO good variant is to remove "Use recording controller"
> > > > > from drop-down list e.g. to show user only nodes, which are really present
> > > > > in test-tree(Thread Groups, Controllers, whatever else)?
> > > > 
> > > > Hi, another argument why removing it is not a good idea IMHO is bug 57382.
> > > > If you remove it then when reloading you will need to setup correctly target
> > > > before using Test Plan, while with "Use recording controller", nothing is
> > > > needed if you have a Recording controller.
> > > 
> > > Not sure I see how Bug 57832 affects this.
> > 
> > Well if you remove "Use Recording Controller", then it means you rely on
> > user setting the target controller explicitely right ?
> 
> Yes.
> 
> > So if he does, he saves his plans and reloads it later, due to bug the
> > setting is forgotten and it now records not where user wanted it to record
> > but as per the result of ProxyControl#findTargetControllerNode
> > 
> > So you have lost productivity with this change.
> 
> Not if bug 57832 has been fixed, surely?
>  
> > Regarding "Cannot the the recording template can be fixed so that it just
> > works?" ? No you need to fix 57832 before.
> 
> Fine, let's fix 57832.
>  
> > Regards


Ok, note that as users we would prefer "Use Recording Controller" to stay.

(In reply to UbikLoadPack support from comment #12)

> Ok, note that as users we would prefer "Use Recording Controller" to stay.

Why is it still necessary (assuming 57832 is fixed)?

It seems wrong to me to have a drop-down entry which refers to a non-existent controller.


Comment 14


UbikLoadPack support



2014-12-22 16:55:32 UTC

(In reply to Sebb from comment #13)
> (In reply to UbikLoadPack support from comment #12)
> 
> > Ok, note that as users we would prefer "Use Recording Controller" to stay.
> 
> Why is it still necessary (assuming 57832 is fixed)?
> 
> It seems wrong to me to have a drop-down entry which refers to a
> non-existent controller.

It is more of a conceptual Target saying Use Recording controller located somewhere in test plan. By implementing the popup check it would allow to leave this feature retaining backward compatibility.

(In reply to UbikLoadPack support from comment #14)
> (In reply to Sebb from comment #13)
> > (In reply to UbikLoadPack support from comment #12)
> > 
> > > Ok, note that as users we would prefer "Use Recording Controller" to stay.
> > 
> > Why is it still necessary (assuming 57832 is fixed)?
> > 
> > It seems wrong to me to have a drop-down entry which refers to a
> > non-existent controller.
> 
> It is more of a conceptual Target saying Use Recording controller located
> somewhere in test plan. By implementing the popup check it would allow to
> leave this feature retaining backward compatibility.

If I understand the pop-up proposal correctly, it would prevent the user from running the test plan. So it would not retain compatibility.

However maybe the intention is for the pop-up to be a Warning (rather than an Error).

But I'm not sure how useful it is to retain the existing behaviour, as it is rather unexpected.


Comment 17


Philippe Mouawad



2014-12-27 15:22:34 UTC

Date: Sat Dec 27 15:22:01 2014
New Revision: 1648056

URL: http://svn.apache.org/r1648056
Log:
Bug 57381 - HTTP(S) Test Script Recorder should display an error if Target Controller references a Recording Controller and no Recording Controller exists
Bugzilla Id: 57381

Modified:
    jmeter/trunk/src/components/org/apache/jmeter/control/gui/TreeNodeWrapper.java
    jmeter/trunk/src/protocol/http/org/apache/jmeter/protocol/http/proxy/ProxyControl.java
    jmeter/trunk/src/protocol/http/org/apache/jmeter/protocol/http/proxy/gui/ProxyControlGui.java
    jmeter/trunk/xdocs/changes.xml


Comment 18


Philippe Mouawad



2014-12-27 15:22:44 UTC

Thanks for patch


Comment 19


Philippe Mouawad



2014-12-27 16:02:38 UTC

Date: Sat Dec 27 16:01:49 2014
New Revision: 1648060

URL: http://svn.apache.org/r1648060
Log:
Bug 57381 - HTTP(S) Test Script Recorder should display an error if Target Controller references a Recording Controller and no Recording Controller exists
Oups forgot i18n
Bugzilla Id: 57381

Modified:
    jmeter/trunk/src/core/org/apache/jmeter/resources/messages.properties
    jmeter/trunk/src/core/org/apache/jmeter/resources/messages_fr.properties

Статья подготовлена сотрудниками отдела тестирования в компании, где я работаю.
На хабре уже не первый раз пишут про JMeter, но статьи имеют довольно узкую направленность, либо сложны для понимания. Поэтому, эта статья будет интересная именно начинающим.

Введение

Как-то я начал осваивать новый инструмент — JМeter — и не смог найти какого-то полноценного руководства как руководства к действию. Постепенно, разобравшись по некоторым довольно полезным статьям и блогам, пользовательской документации, я начал что-то понимать. И решил, что, возможно, я не один ищу то, с чего можно начать работать. Освоить некоторые принципы построения и логику самого инструмента. Так что вот — статья о том, как начать.
Так что в этой статье мы рассмотрим пример создания скрипта для 3 пользователей, которые хотят:
1. залогиниться;
2. добавить в какой-нибудь альбом новую фотографию;
3. поменять аватарку.
Как таковой — это обычный бизнес процесс для какой-нибудь социальной сети.

И для этих целей будут использованы такие встроенные компоненты:

  • HTTP Proxy Server
  • Recording Controller x3
  • User Define Variables
  • CSV Data Set Config x3
  • Constant Timer
  • Uniform Random Timer
  • HTTP Autorization Manager
  • HTTP Request x6
  • Debug Sampler х3
  • HTTP Cookie Manager
  • Once Only Controller
  • Возможно, некоторые другие.

Статья большая, потому что подробная. В итоге должно получиться что-то вроде такого:
c017f1f09f290a0fa142b4cb9edbc8b5.png

Автоматическая запись скрипта

Суть в том, что когда мы создаем скрипт для сайта, который мы тестируем методом черного ящика, мы не знаем всех тонкостей и особенностей его работы. Так, например, тот сайт, на базе которого в итоге получится мой скрипт, написан при помощи некоторого пакета Symphony2. Из-за неё отправка данных логин-пароль идет не прямо с формы на странице /login, а с некоторой несуществующей страницы /login_check. И ко всему этому отправляется еще одно пустое поле, которое для пользователя скрыто.
Обнаружить подобные подводные камни поможет HTTP Proxy Server (это, как и всё прочие, встроенный элемент). Эмулируя работу прокси сервера, он будет записывать все полученныеотправляемые запросы.

Подготовительные действия

Мы пока не будем добавлять HTTP Proxy Server в дерево теста. Обсудим, куда мы будем записывать полученные «шаги». Позже, когда мы добавим элемент в дерево, мы увидим, что есть несколько возможностей, куда именно записывать результаты. Их можно записать прямо в «катушку» (Thread), на «верстак» (Workbanch), либо в элемент «Recording Controller». Я советую воспользоваться последним способом. Во-первых, это позволит при необходимости отключить (ctrl+t) весь лог разом; во-вторых, так лучше отслеживается и формируется структура теста.
Все действия по добавлению и редактировнию происходят по нажатию правой кнопки мыши в контекстном меню. Созданные элементы можно просто перетаскивать (drag and drop).
Итак: Test Plan -> Add -> Threads ->Thread Group; Thread Group -> Add -> Logic Controller -> Recording Controller.
Настоятельно рекомендую дать сразу всем элементам понятные имена. В моём случае это будут «Картинки» и «Залогинимся», соответственно.
15bb271fb1ef8d13b8c0d94ba3319ef7.png

Записываем скрипт при помощи HTTP Proxy Server

Когда подготовительные действия завершены, добавим на «верстак» необходимый элемент: WorkBench -> Add -> Non-Test Elements -> HTTP Proxy Server.
В нем много настроек, но нас интересует пока только порт. Если порт 8080 занят, можно выставить, например, 8089. Я на своей машине использую именно этот (8089). Так же мы видим, что по умолчанию в поле Target Controller стоит «use recording controller». Т.е. записываться лог будет именно туда.
Остальные поля трогать не будем, но некоторые из них нам понадобятся, когда мы получим чуть больше информации о нашем сайте.
df806a35fb74dc3aac7b46f4dfb7421e.png
После того, как выставили порт, идем в настройки браузера. Я банально использую IE. Сервис — Свойства обозревателя — Подключения — кнопка Настройка сети. Ставим галки «Использовать прокси-сервер …», вторую галку снимаем. Рекомендую заглянуть в «Дополнительно» и посмотреть, что написано в «Исключения». В моей практике в процессе тестирования сайт перенесли на новый домен, который оказался в исключениях. Ушло около получаса, чтобы разобраться, почему действия моего виртуального пользователя на тестируемом сайте не записываются, а всякие ссылки на яндекс, твиттер и фэйсбук прекрасно логируются. В общем, если там неожиданно оказался домен вашего сайта, сотрите.
В поле Адрес пишем «Localhost», а порт указываем как из JMetеr’а: «8089». Без кавычек всё, разумеется.
795fceb9b55e67df06cbb39b501e9d61.png
Теперь все готово для записи. Возвращаемся в JMeter на прокси и внизу можем нажать кнопку Start. После нажатия все действия пользователя в браузере начнут записываться в созданный нами Recording Controller «Залогинимся». Записывать действия будем в несколько шагов, т.к. скрипт может оказаться чрезмерно большим и его будет сложно редактировать. Так что первое, что мы сделаем, а после отладим, это авторизация пользователя на сайте.
Итак, нажимаем Start и проходим процедуру авторизации на сервере (у вас может её не быть, а у меня есть) и процедуру авторизации на сайте. Возвращаемся в JMeter и жмем Stop. Смотрим на Recording Controller: у него куча дочерних элементов. Это то, что мы послали на сервер, а сервер ответил. Изучаем и чистим.
fc624c70b137e9f18e1c1106790f1ceb.png

Отладка скрипта

Отладка скрипта представляет собой удаление различных .jpg, .png и ссылок на сторонние ресурсы. У меня в скрипте больше половины таких сторонних ресурсов — это связи с различными социалками и яндекс картой. Всё это можно вычищать (клавишей delete). В целом, также можно вычистить .js. Главное найти запрос, который передает в своем теле учетные данные вашего пользователя. Ну и для красоты найти запрос, который ведет вас на страницу, на которой пользователь логинится. Таким образом, вместе они моделируют связку в действиях пользователя «зашел на страницу — залогинился».
Предположим, что нам повезло вычленить необходимые запросы. Ну, или нам кажется, что мы их вычленили. Дадим им читаемые имена! Чтобы проверить то ли мы вычленили, скрипт надо запустить. В моем случае, если запустить скрипт, то он выполнится с ошибками. Дело в том, что мне для тестирования нужно авторизоваться на сервере. Для этого добавим в верхушку дерева HTTP Autorization Manager (Thread Group – Add – Config Elements – HTTP Autorization Manager). Он интуитивно понятен. Записываем туда адрес нашего ресурса обязательно с http://, имя пользователя и пароль.
5327c7af9f700f2bcfdcff6f0e4cc4a1.png
Если Менеджер Авторизации нужен для авторизации на сервере, то абсолютно точно при авторизации на сайте используются куки. Добавляем Cookie Manager после Менеджера Авторизации (TestPlan – Add – Config Elements — HTTP Cookie Manager). Этот элемент необходимо добавлять, пожалуй, всегда, если речь идет о том, что пользователю нужно залогиниться.
Прежде чем запустить и проверить скрипт добавим элемент View Results Tree (Катушка – Add – Listener – View Results Tree), в котором можно будет наблюдать выполнение. Этот элемент удобно располагать всегда внизу. Ах да, еще нужно в настройках браузера убрать галку «использовать прокси» — он пока нам не понадобится.
09d903bd3717d97ac545623830610536.png
Итак, можно запустить. Запускаем (ctrl + r)!
В View Results Tree видим следующее:
023f9367cb24ffed7e5cca45b7f82831.png
Кажется, нам повезло. И даже если мы не залогинились, то, по крайней мере, запросы дошли до сервера. Чтобы убедиться, что пользователь был успешно залогинен, посмотрим в дереве на ответ. Нажимаем на Response Data. В ответе сервера ищем информацию, которая свидетельствует об успешной авторизации пользователя. В моем случае это будут имя пользователя, т.к. после авторизации оно высвечивается на странице.
a7915066621c3127e152cdd72739ea2d.png
Скрипт по-прежнему может нуждаться в чистке. Я, например, удалил из него HTTP Header Manager’ы. И без них всё работает отлично. Чтобы убедиться в нужности каждого элемента, его не обязательно сразу удалять, достаточно этот элемент отключить (ctrl + t).
Далее мы хотим привлечь к этому делу 3 пользователей. Для этого прежде выполним небольшой учебный пример по параметризации запросов. Параметризируем одного конкретного пользователя.

Параметризация

Для параметризации запросов добавим в самый верх User Define Variables. Thread -> Config Controllers -> User Define Variables. Внизу есть кнопка Add. Нажимаем ее, вбиваем две переменные, т.к. меняться у нас будут только два параметра: логин и пароль. Дадим им хорошие имена: userName и password. А в качестве значений впишем пока конкретные значения текущего пользователя.
64f29cba08c40a5eb434cd5592d333c0.png
Чтобы их использовать переходим в запрос Логин, и вместо конкретных значений пишем имена переменных в формате ${имя переменной}. В нашем случае записываем в поля Value для логина — ${userName}, для пароля — ${password}.
3ce15268749a60ff2bf390df1e63e2ac.jpg
Для отладки передачи параметров добавим еще один элемент – Debug Sampler. Thread –> Add -> Samplers –> Debug Sampler. Его поставим после запроса Логин. В настройках элемента оставим только JMeter variables, остальные поставим в false. Это делам для того, чтобы отловить только наши переменные. Да и всё равно других нет.
060ae24c1bb7116dd9584958c9a51b9a.png
Запускаем и смотрим в View Results Tree результаты. Должны видеть, что в качестве переменных передались именно наши значения, и запросы в целом вернули то, что нужно (см. выше).
ab2dea0a6bf3bf094fda5db1c90dec99.png
Теперь можно передать данные 3 пользователей. Для этого воспользуемся CSV Data Set Config.

CSV Data Set Config

Я предлагаю создавать .csv файл в блокноте. Для пользователей файл должен представлять собой набор из 3х строчек вида «UserName;Password». Мой файл представлен на скрине ниже:
494aec49fe34799d4b84496c9e3a86d7.png
Далее добавим в дерево элемент CSV Data Set Config (Add – Config Elements – CSV Data Set Config). Добавим его не в катушку, а в тест-план, ниже пользовательских переменных. В качестве filename для файла нужно указать полностью путь к файлу и его имя. Ниже указать кодировку (на ваш выбор). Если все данные на английском, то поле можно оставить пустым. Ниже написать переменные, которые считаются из файла. Для нас это будут UserName и Password. В качестве разделителя нужно указать точку с запятой, так как в файле используется она. Ниже, для того, кто хоть немного владеет английским, не сложно перевести имена логических переменных. Нужно поставить в false повтор файла по достижении конца, а также остановку катушки.
0e6afc60ec56cda8c1b2ec293e1dbf38.png
Далее удалим подобные переменные из User Define Variables. То, что он останется пустым, это не страшно. После этого в самой катушке количество потоков (Number of Threrads) установим на 3.
Теперь можно запустить скрипт и наблюдать в Debug Sampler и View Results Tree результаты. Не забудьте проверить, те ли данные вернул сервер, есть ли в них имена ваших пользователей.
c48389e089136baa81c6e0b43bc9d969.jpg

Добавляем фотографию в альбом

Теперь, когда наши пользователи научились логиниться, приступим к следующей части нашего скрипта. Научим их заливать в какой-нибудь определенный альбом нашего сайта фотографии. Для этого опять добавим в катушку Recording Controller, назвав его «Фотографии».
Чтобы сократить полученный скрипт, заранее авторизуемся пользователем на сайте и перейдем на страницу, на которой начнется непосредственно загрузка фотографии. После этого снова включим в настройках браузера прокси и воспользуемся элементом Proxy Server на верстаке (указав другой Recording Controller). Так же в URL Patterns to Exclude укажем расширения, которые нам не нужны в формате «*..ххх».
d7bc20766cd922782bef276dc4c859da.png
Start, заливаем в альбом фотографии, End. Приступаем к чистке скрипта. Точно также можно для красоты оставить лишь те запросы, которые образуют связку «зашел в альбом — добавил фотографию». У меня получилось так:
872415c5eb1f61833944faad3ab94d18.png
На самом деле, запрос «зашел в альбом» записан был вручную. Он не представляет собой ничего сложного: это GET запрос с указанием адреса страницы.
Обратим внимание на тело запроса, который отправляет на сервер файл. Единственное, что в нем представляет для нас ценность, — это путь и имя файла. Вот их мы и параметризируем, чтобы каждый пользователь заливал какую-то свою фотографию. Начнем с пути к файлу. Как таковой для тестирования он не представляет интереса. Вполне вероятно, что все фотографии будут у вас лежать в одной папке. Но в тесте он может встречаться много раз. Так что по правилам хорошего тона запишем его в переменную. Возвратимся к User Define Variables и добавим туда переменную filePath со значением пути до папки, в которой лежат фотографии, например, «** D:jakarta-jmeter-2.5.1images**». Именно со слэшем в конце, позже ясно будет для чего.
Как всегда, протестируем сначала скрипт на одном файле. Поэтому создадим еще одну переменную fileName, в качестве значения которой будет конкретное имя файла, например, «img.jpg«.
23b590db04c057d0d48817886a1107a4.png
Возвратимся в тело запроса. В разделе Send Files With the Request пишем путь уже таким образом: ${filePath}${fileName}. Если подставить в переменные указанные значения (value из user define variables), легко убедиться, что получается корректный путь. Посмотрим на параметры, которые передает запрос. Там тоже есть имя файла. Впишем вместо него ${fileName}.
31d4483e50685da1fa518f82c134d51e.png
Теперь, когда имитация пользователя в этой части закончена, добавим новый Debug Sampler. Подумаем на шаг вперед: если мы заставим катушку крутиться forever (пока не ставить!), то каждый пользователь будет логиниться по много-много раз, верно? Чтобы этого избежать, добавим в катушку логический элемент Only Once (Thread -> Add -> Logic Controllers -> Only Once Controller). Поместите его в соответствующее место над Recording Controller’ом, отвечающий за авторизацию пользователя на сайте, а сам контроллер перетащите в него как дочерний.
c762b94cfdb723ff46aa620a622cc7cd.png
Отключите в браузере прокси. Запустите срипт. Если всё сделано правильно, то в выбранный альбом добавится новая фотография. Если что-то не так, посмотрите Debug Sampler в View Results Tree.

Параметризируем

Теперь можно сделать так, чтобы пользователи добавляли разные фотографии. Для этого создадим csv файл, в кототором будут содержаться только имена фотографий:
Img.jpg
Img1.jpg
Img2.jpg

Создадим CSV Data Set Config, перетащив его под другой CSV Data Set Config, укажем путь к этому файлу. В качестве переменной (variable Names) укажем fileName, а из пользовательских переменных (User Defined Variables) её удалим. Поле для разделителя оставим пустым. В этот раз повторять файл при достижении конца (Recycle on EOF) оставим на True, а останавливать катушку при достижении конца (Stop thread on EOF) — на False. Для красивой логики нашего теста перенесем фотографии в отдельную папку: » D:jakarta-jmeter-2.5.1imagesPhoto » и соответствующим образом изменим значение переменной filePath на filePath_Photo. Сделаем это и в тех местах, где переменная используется.
Запускаем тест! После чего смотрим, добавилось ли в альбом 3 фотографии (да, все пользователи должны иметь достаточно прав, на добавление фотографий в альбом). Если всё ОК, продолжаем дальше. Если нет — читаем Debug Sampler и ответы сервера.
813d89e44911fc7e1ac02f404e708d01.png

Изменяем аватарку

На деле это ничем не отличается от предыдущего параграфа. Точно также нужно залить на сервер фотографию. Поэтому делаем все также:

  1. создаем очередной recording controller
  2. настраиваем прокси
  3. делаем действия на сайте (записываем скрипт)
  4. чистим скрипт
  5. параметризуем для одной аватарки
  6. отлаживаем
  7. параметризуем для множества аватарок

В качестве имен аватарок я использовал тот же csv файл, но залил картинки в другую папку и создал новую переменную для нее: filePath_Avatars.
Если всё работает, то это хорошо. Если нет, смотрим в Debug Sampler.
Чтобы скрипт был больше похож на живого человека, нужно добавить задержки. Например, после загрузки фото на сервер, можно поставить Constant Timer на 3 секунды (3000ms), будто пользователь ждет, пока картинка загрузится на сервер. А для смены аватарки Gaussian Random Timer от 2 до 6 секунд, будко пользователь ищет и выбирает аватарку. Так же для большего правдоподобия в каждом HTTP Request можно поставить галку Retrieve All Embedded Resourced From HTML Files, означающую что со страницы будет загружаться всё возможное, как в обычном браузере.
Итак, предположим, что всё работает и всё отлично. Всё. Задача полностью выполнена. Теперь осталось нагрузить наш сайт на всю ночь. Вернемся в Thread и установим галку forever. Это значит, что скрипт будет выполняться, пока не случится событие «stop thread». В CSV Data Set Config’ах мы выставили возможность такого события в False. Значит, тест будет выполняться, пока его не остановит тестировщик руками (меню Run -> Stop). Итоговый скрин выложен в начале статьи.
Тест моделирует банальный бизнес-процесс для какой-нибудь социалки: пользователь зашел в сеть, залил в альбом фотографию, которая ему ну уж очень понравилась, со вчерашней вечерины и поменял свою аватарку на это (либо другое) фото. Поставив такой процесс на forever, мы получили 3 пользователей, которые заливают фотки и меняют на них аватарки. Процесс можно изменить, добавляя различные другие элементы. Например, заливать фотографии можно только одну, поставив Only Once, а вот менять аватарки бесконечно. Если пополнить базу до 1000 пользователей, запустить скрипт непосредственно с сервера, а также с локальных машин в офисе — это будет достаточно серьезная нагрузка на сервер приложения.
Возможно, следующая статья будет посвящена тестированию поиска и регулярным выражениям, либо оценке и интерпретации собранных данных.
Будем рады любому обмену опыта.

So you started designing a scenario using JMeter manually. After working a while on this grueling task, you start wondering: Isn’t there a way to record browser interactions with JMeter?

The short answer is yes! Jmeter’s HTTP(s) Test Script Recorder is exactly designed to record test scenarios.

This tutorial teaches you:

  • What a Proxy is and how the recorder works,
  • How to intercept and record HTTP Requests automatically while using your web browser,
  • How to record SSL-secured (https requests),
  • How to configure Proxy Settings with Google Chrome and Firefox,
  • And the most important part: recording the script!

You’ll see there are a few caveats but everything is well explained.

We assume you already:

  • Have JMeter installed (See for Mac Setup and Windows Setup),
  • And know How to use JMeter.

I know how impatient you are, so let’s start now!

Recorder Setup

How a Proxy works

How Proxy Works

Picture showing Proxy Principle

Before we configure JMeter, let me briefly explain how the recording process works. A Proxy is a component which inserts between you and the remote server. In some way, it’s similar to a Man-In-The-Middle Attack, except you’re spying on yourself!

As anything between the remote server and you goes through the Proxy, when JMeter acts like a Proxy, it can record all your browser interactions (given it’s http or https).

How can JMeter act like a Proxy? By using Jmeter’s HTTP(s) Test Script Recorder.

JMeter Recorder Template

The easiest way to get started right away is to use the Recorder Template:

  • Launch JMeter,
  • Click on Files > Templates...,
  • Select Recorder from Select Template dropdown,
  • Then click on Create.

JMeter Recording Template

Templates panel accessible from Files > Templates

Once you click on Create, JMeter creates a bunch of elements required to properly record http and https traffic. Let’s examine the elements being created.

JMeter Recording Test Elements

JMeter Recording Test Elements

Your JMX project should now contain the following elements.

  • User Defined Variables: lets you define an initial set of variables, just as in the Test Plan,

User Defined Variables

  • HTTP Request Defaults: lets you set default values that your HTTP Request controllers use,

HTTP Request Defaults

  • HTTP Cookies Manager: stores and sends cookies just like a web browser,

HTTP Cookies Manager

  • Thread Group with a Recording Controller inside: it will contain the request being recorded by JMeter’s proxy,

Thread Group

  • And finally the HTTP(S) Test Script Recorder: controls JMeter’s Proxy settings.

Test Script Recorder

A few View Results Tree are located here and there for debugging purpose.

Test Script Recorder Settings

Let’s now examine the most interesting Script Recorder Settings:

  • Global Settings

    • Port: HTTP and HTTPS proxy port. The proxy will be running on this TCP port, listening for http requests,
    • HTTPS Domains: List of domain (or host) names for HTTPS. Use this to pre-generate certificates for all servers you wish to record. Example: httpbin.org,
  • Test Plan Content:

    • Target Controller: by default, everything is recorded within Recording Controller. But you can change it to whatever you want (like the Thread Group directly),
    • Grouping: groups http request by trying to determine which requests belong to the same page,
    • Capture HTTP Headers: creates HTTP Headers Manager as http request child, capturing the headers sent by the web browser. Leave checked as most http headers are important,
  • HTTP Sampler Settings:

    • Use Keep-Alive: enable HTTP Keep-Alive to signal that the connection should be kept open for further messages (by default for HTTP 1.1). Most sites are HTTP 1.1 compliant now,
    • Follow Redirects: generates only a single HTTP Request when multiple HTTP redirections are detected, and enables Follow Redirects on it.

JMeter Recorder Request Filtering

JMeter Recorder Request Filtering

In addition to general settings, the recorder offers the ability to filter requests. How does it work? Based on inclusion and exclusion patterns, the recorder chooses if a request must be stored during the record or not.

What are filters for? Mostly for filtering out resources like images, CSS Stylesheets and/or Javascript files. But, that’s not mandatory. In fact, it may be less realistic to filter those resources since they are part of the application anyway.

It’s time to record http requests using JMeter’s Proxy!

HTTPS Setup

Recording HTTPS websites requires a bit more work than plain HTTP websites. Let’s see why.

Let’s start JMeter’s Proxy Recorder:

  • Select HTTP(s) Test Script Recorder within the tree on the left,
  • Click on Start button: a dialog should show up asking to install CA Root Certificate. This certificate must be installed within the web browser to support recording HTTPs traffic.

Root Certificate Dialog

Root Certificate Dialog

It may look complex at first glance, but don’t worry. Let me explain why you see this.

TLS/SSL (The S in HTTPS) guarantees that there are no spies between you and the server you are contacting (no proxies). Normally, you use an HTTP CONNECT to open up a TCP connection through the proxy. In this case, the proxy will not be able to decrypt the traffic and directly tunnel you to the remote server.

If you want the proxy to decrypt HTTPS Traffic, you need to take the following approach:

  • Client starts an HTTPS session,
  • Proxy transparently intercepts the connection and returns a generated (and weak) SSL certificate, signed by a CA (Certificate Authority) that is unconditionally trusted by the client, (we’ll see how)
  • Proxy starts an HTTPS session to target,
  • Proxy verifies integrity of SSL certificate; failing if the certificate is invalid,
  • Finally, Proxy streams content, decrypts it and re-encrypts it with intermediate certificate.

That’s known as MITM Attack.

MITM Attack

JMeter’s Proxy is based on Man-In-The-Middle Attack to decrypt HTTPS Traffic

Said otherwise, we need to install and trust JMeter’s Root Certificate to allow JMeter’s Proxy to decrypt HTTPS traffic. Trust me, there is no risk unless you leak the Root certificate to a malicious third party.

JMeter’s Certificate Authority

JMeter’s SSL Certificate Authority

JMeter generates a Root Certificate Authority within the <JMETER_HOME>/bin folder. You should find a file named ApacheJMeterTemporaryRootCA.crt in this folder. Let’s see how to install it in common web browsers.

Root CA Validity

By default, JMeter generates a Root CA valid only 7 days. That’s annoying since we need to redo the procedures below every week. But, there is a way to hack this.

Open <JMETER_HOME>/bin/jmeter.properties and locate the following lines:

1
2
# The default validity for certificates created by JMeter
#proxy.cert.validity=7

For example, to have certificates valid for a year, change it to:

1
2
# The default validity for certificates created by JMeter
proxy.cert.validity=365

Remember to:

  • Stop JMeter,
  • Change the jmeter.properties,
  • Delete any existing <JMETER_HOME> / bin / ApacheJMeterTemporaryRootCA.crt,
  • And restart JMeter.

That should save you from repeating the browser installation procedures below too often.

Firefox Setup

To install JMeter’s Trusted Root Certificate Authority in Firefox:

  • Open Firefox,

Firefox Menu

  • Open main menu and select Preferences,

Firefox Prefs Menu

  • Select Privacy & Security settings and scroll-down to the bottom of the page,

Firefox Privacy Settings

  • Click on View Certificates then click on Import,

Firefox Certificates

  • Select the ApacheJMeterTemporaryRootCA.crt located in <JMETER_HOME>/bin folder. (<JMETER_HOME> is where JMeter is installed),

Firefox Trust Certificate

  • You should see the certificate within the Certificate Manager.

JMeter Root CA Installed in Firefox

That’s it! It should take you only a few minutes to install it.

Google Chrome Setup

Let’s see now how to install JMeter’s Trusted Root Certificate Authority in Google Chrome:

  • Open Google Chrome,
  • Click on main menu,

Chrome Menu

  • Then click on Settings,

Chrome Menu

  • In the search field, enter privacy and scroll down to Manage Certificates,

Chrome Privacy Settings

  • Click on Authorities, then click on Import,
  • Select the ApacheJMeterTemporaryRootCA.crt located in <JMETER_HOME>/bin folder. (<JMETER_HOME> is where JMeter is installed),

Chrome Import Authorities

  • Check Trust this certificate for identifying websites,

Chrome Trust Certificate

  • Finally, you should see JMeter’s Root Certificate Authority installed.

Chrome Certificate Install

That required quite a bit of work to compile! But we have fully working HTTPS Recording in both web browsers.

Now, we’re ready to configure those browsers with JMeter’s Proxy settings.

Proxy Setup

Firefox Setup

To configure JMeter’s Proxy in Firefox:

  • Open Firefox,

Firefox Menu

  • Open main menu and select Preferences,

Firefox Prefs Menu

  • Select General section, then scroll-down to Network Proxy,

Firefox General Menu

  • Finally enter both http and https proxies with hostname localhost and port 8888 (default proxy port).

Firefox Proxy Settings

  • Click on OK.

Firefox is now configured with JMeter’s proxy settings and ready to record http and https requests.

Google Chrome Setup

To configure JMeter’s Proxy in Google Chrome:

  • Open Google Chrome,
  • Click on main menu,

Chrome Menu

  • Then click on Settings,

Chrome Menu

  • Enter proxy and select Open Proxy Settings. It should open system wide proxy settings. (depends on operating system)

Chrome Menu

  • Finally enter both http and https proxies with hostname localhost and port 8888 (default proxy port).

Just beware that setting system wide proxy settings affects all applications sensitive to those settings (not just web browsers).

Recording The Scenario

We’re finally reaching the most entertaining part of the tutorial: recording the script! If you’re still there (and I won’t mind if you’re already sleeping), let’s try to record HTTPBin.

JMeter Start Recording

Click on the Start button within the HTTP(S) Test Script Recorder to start JMeter’s proxy. Click on OK when the Root CA dialog appears as see previously. In this example, we’ll use Firefox because its proxy settings are confined.

Firefox Proxy Issue

If you ever see the message The proxy is refusing connections within Firefox, please check:

  • You have started the HTTP(S) Test Script Recorder by clicking on Start button,
  • That proxy settings are properly set to the appropriate hostname and port.

It usually boils down to the points described above.

Firefox HTTPBin

Now browse to https://httpbin.org. You should see requests filling in within the Recording Controller.

JMeter HTTPBin Recording

Congratulations! You’ve just recorded an SSL protected website using JMeter. Once you are finished, go back to JMeter’s Recorder, and click on Stop to stop the recording. Remember proxy settings are still set within Firefox. Any attempt to browse while JMeter’s proxy is stopped / not running will result in the The proxy is refusing connections error.

Additional resources

In case you find JMeter recording too cumbersome, you may want to use the HAR import feature of OctoPerf to get there.
It’s available even with a free account and you can export your script back as a JMX anytime.

After recording it’s also time to rework the recorded script like explained in our JMeter REST API Testing guide:

  • Handling dynamic parameters,
  • making the script more realistic and random,
  • etc.

You’re new to JMeter? No worries. We have cooked a JMeter Tutorial for beginners too.

Using the JMeter HTTP(S) Test Script Recorder:

By using the Recording Controller we can easily record the website navigation script and use it for the load testing. Now we see that step by step how you can use it-

Step 1: Need below software

Apache JMeter – Download and run the .bat/.sh file from the bin folder. (.bat for window & .sh for Linux)

Java 6 or later – Download and proper installation of Java.

Mozilla Firefox – Download and proper installation of Mozilla.

Step 2: Run the .bat/.sh file from the bin folder.

Step 3: Now build a test plan

  • Add the Thread Group to Test Plan
    Right-click on Test Plan > Add > Threads (Users)

Test Plan 1

Add Thread Group 2

Number of Threads– Total number of users which we want to hit on the server.
For example: – here we will hit the 10 users at a time on the server.

Ramp-Up Period– Time given the next user to hit on the server.
For example: – Suppose we have 10 users (Number of Thread) and Ramp up period is 10. Then we are giving each user 1 second to hit the server.

Loop Count– We want to execute the same operation two times continuously then we need to increase the loop count as 1. It means 10 people will hit the server one time.

Add Thread Group 3

Step 4: Add the Recording Controller

  • Right-click on Thread Group > Add > Logic controller > Recording Controller

Recording Controller  4

Step 5: Add HTTP Request Defaults

  • Right Click on Workbench –> Add–> Config Elements –> HTTP Request Defaults
  • We are added the HTTP Request Defaults causes we will send the multiple request to the same web server.

Http Request default 5

HTTP Request Defaults contain the two important parts-

  1. Server Name or IP
  2. Port Number

Server Name or IP: Enter the url or IP address of the site on which you want to perform the load testing.

Port Number: Enter the default port number 8080.

Http Request default 6

Step 6: Add HTTP Test Script Recorder 

  • Right Click on Workbench–> Add–> Non-Test Elements –> HTTP Test Script Recorder.

Proxy server 7

Port: Fill the 9090 sometimes 8080 port is busy.

Target Controller:  Add the place where you want to record the script. Here we choose –use recording controller.

URL Pattern to Include/Exclude: When the page is loaded then images are loaded, some are restricted so allow the all. URL Patterns to Include”. This will create a blank entry.

Proxy server 8

Step 7: Setting of the browser proxy

  1. Open Firefox Browser.
  2. Click on Tools shown at the top menu.
  3. Click on Options shown under Tools
  4. Click on Network tab shown on the window after clicking Options.
  5. Click on Settings Button.

Mozila

Mozila 1

6. Click on Manual proxy configuration
7. Enter localhost and Port 9090.

Mozila 2

Mozila 3

8. Click ok button.

Step 8: Installation of the CA Certificate in the browser-

  • When you click on the start button on the HTTP(S) Test Script Recorder then the below screen is appeared-

Certificate 10

  • Click on the ok button.
  • Open the Mozilla Browser.
  • Go to the tools > Option > Advanced > encryption > View certificate

Certificate 11

  • Click on the view certificates then below screen appear-

Certificate 12

  • Click on the import button and go to the bin folder and install the CA certificate-

Certificate 13

  • View the certificate and select the check box and click on the ok button.
  • Click the all ok button.

Step 9: Now Record the Script

  •  Now enter the url in the browser and navigate the screen according you.
  • After completion the navigation stop the recording from the HTTP Test Script Recorder.

Step 10: Add the Listener

Listerner14

Step 11: Now save the Test Plan

Sve 15

Step 12: Now Run the Test Plan

Start run 16

Step 13: After completed the process check the result-

  •  Aggregate Graph

Aggregate Graph 17

  • Aggregate Report

Aggregate Report 18

  • Graph Result

Graph Results 19

  • Summary Report

Summary Report 20

*************************************E*N*D***********************************

Please share your views….

What is the Logic Controller?

Logic Controllers let you define the order of processing request in a Thread. It lets you control “when” to send a user request to a web server. For example, you can use Random Controllers to send HTTP requests to the server randomly

Logic Controllers determine the order in which user request is executed.

Some commonly used Logic controllers are below:

How to use Controllers in JMeter

Recording Controller:

JMeter can record your Testing steps; a recording controller is a placeholder to store these recording steps.

How to use Controllers in JMeter

Simple Controller:

Simple Controller is just a container for user request.

How to use Controllers in JMeter

Loop Controller:

Loop Controller makes the user request run a specified number of times or run forever as shown in figure:

How to use Controllers in JMeter

Random Controller:

Random Controller makes all the user requests run in the random order in each loop period.

For example, you have 3 user requests to website http://www.google.com in following order:

  1. HTTP request
  2. FTP request
  3. JDBC request

These 3 requests should run 5 times. Total 15 user requests will be sent to Google server by JMeter.

In sequential order, requests are sent sequentially in following order:

HTTP request ->FTP request->JDBC request

for each loop.

How to use Controllers in JMeter

In random order, requests are sent as randomly,

FTP request ->HTTP request->JDBC request

Or

JDBC request ->FTP request->HTTP request

For each loop.

Module Controller:

The goal of Module Controller is to add modularity to JMeter.

The general idea is that web applications consist of small units of functionality (i.e. Logon, Create Account, Logoff…). This functionality can be stored in Simple Controller as “modules”. Module Controller will choose which module needs to run.

How to use Controllers in JMeter

Consider the following scenario –

You want to simulate:

  • 50 users logging out,
  • 100 users logging in
  • 30 users search www.google.com

You can use JMeter to create 3 modules. Each module simulates each user activity: Login, Logout, and Search.

How to use Controllers in JMeter

The Module controller chooses which module needs to run.

How to use Controllers in JMeter

Other Important Controllers:

  • Interleave Controller: picks up and makes one of user request run in each loop of the thread.
  • Runtime Controller: controls how long its children are allowed to run.

For example, if you specified Runtime Controller 10 seconds, JMeter will run your test for 10 seconds.

How to use Controllers in JMeter

  • Transaction Controller: measures the overall time taken to finish a test execution
  • Include Controller: is designed to use an external test plan. This controller allows you to use multiple test plans in JMeter. See detail in JMeter Performance Testing.

Loop Controller Example

This section shows you step-by-step instruction to add Loop Controller set to your current performance test plan.

The Loop Controller makes the samplers run as a certain number of times, in addition to the loop value you specified for the Thread Group. For example, if you

  • Add one HTTP Request to a Loop Controller with a loop count 50
  • Configure the Thread Group loop count to 2
  • Then, JMeter will send a total of 50 * 2 = 100 HTTP Requests.

This is the roadmap of this example:

How to use Controllers in JMeter

Step 1) Configuring Thread Group

We re-use the Step 1, 2 in tutorial JMeter Performance Testing.

  1. Add Thread Group

Right click on the Test Plan and add a new thread group: Add-> Threads (Users) ->Thread Group

But in Thread Group control panel, enter Thread Properties as follows:

How to use Controllers in JMeter

It will make one user request to the web server google.com and run it 2 times.

  1. Add JMeter elements

Add HTTP request default to www.google.com.

  1. Adding Loop Controller

Right Click Thread Group -> Logic Controller -> Loop Controller

How to use Controllers in JMeter

Step 2) Configuring Loop Controller

Add value 50 to Loop Count field as below figure. It will make one user request to the web server google.com run it 50 times, in addition to the loop value =2, you specified for the Thread Group above.So JMeter will send a total of 2 * 50 = 100 HTTP Requests.

How to use Controllers in JMeter

Right click Loop Controller, Add -> Sampler -> HTTP request

How to use Controllers in JMeter

Step 3) Add View Results in Table

We re-use Step 2 in Timer to add View Results in Table

So the test plan is shown in below figure

How to use Controllers in JMeter

Step 4) Run your test

Now return View Results in Table, click Start button on the Menu bar (Ctrl+R) to run a test

As shown in the figure below, JMeter simulates one user request, which is sent 100 times, to the web server http://www.google.com/. The Test is stopped after a user request was sent in 100 times.

How to use Controllers in JMeter

Troubleshooting:

  1. If you face the issue while running the above scenario … do the following
  2. Check whether you are connecting to the internet via a proxy. If yes, remove the proxy.
  3. Open a new instance of Jmeter
  4. Open the ControllerTestPlan.jmx in Jmeter
  5. Click on Thread Group -> View Result in Table
  6. Run the Test

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Techsys dll 1c ошибка
  • Techstream ошибка unable to connect to vim